@quandev104/pi-style 0.1.4 → 0.1.5

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.
Files changed (33) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +8 -4
  3. package/dist/extensions/pi-style.js +3789 -1278
  4. package/dist/extensions/pi-style.js.map +1 -1
  5. package/extension-src/pi-style/app/command-service.ts +2 -0
  6. package/extension-src/pi-style/domain/config-normalization.ts +21 -5
  7. package/extension-src/pi-style/domain/config-presets.ts +1 -1
  8. package/extension-src/pi-style/domain/config-types.ts +7 -3
  9. package/extension-src/pi-style/domain/theme.ts +6 -1
  10. package/extension-src/pi-style/features/editor/index.ts +169 -27
  11. package/extension-src/pi-style/features/messages/index.ts +66 -0
  12. package/extension-src/pi-style/features/tools/bash-execution.ts +112 -0
  13. package/extension-src/pi-style/features/tools/boxed/bash.ts +154 -130
  14. package/extension-src/pi-style/features/tools/boxed/batch.ts +50 -27
  15. package/extension-src/pi-style/features/tools/boxed/command-shape.ts +136 -0
  16. package/extension-src/pi-style/features/tools/boxed/find.ts +2 -2
  17. package/extension-src/pi-style/features/tools/boxed/gh.ts +1012 -0
  18. package/extension-src/pi-style/features/tools/boxed/git.ts +1960 -0
  19. package/extension-src/pi-style/features/tools/boxed/grep.ts +2 -2
  20. package/extension-src/pi-style/features/tools/boxed/output-tree.ts +9 -10
  21. package/extension-src/pi-style/features/tools/boxed/read.ts +3 -3
  22. package/extension-src/pi-style/features/tools/boxed/write.ts +2 -1
  23. package/extension-src/pi-style/pi/compatibility-coordinator.ts +17 -0
  24. package/extension-src/pi-style/pi/compatibility-probe.ts +104 -10
  25. package/extension-src/pi-style/pi/compatibility-registry.ts +19 -3
  26. package/extension-src/pi-style/pi/index.ts +18 -1
  27. package/extension-src/pi-style/pi/session-coordinator.ts +24 -0
  28. package/extension-src/pi-style/shared/box.ts +8 -4
  29. package/extension-src/pi-style/shared/split-diff.ts +9 -9
  30. package/package.json +1 -1
  31. package/themes/titanium-light.json +82 -0
  32. package/themes/titanium.json +79 -0
  33. package/themes/.gitkeep +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../extension-src/pi-style/shared/ansi.ts","../../extension-src/pi-style/shared/box.ts","../../extension-src/pi-style/shared/elapsed.ts","../../extension-src/pi-style/shared/render-budget.ts","../../extension-src/pi-style/shared/theme-extras.ts","../../extension-src/pi-style/features/tools/boxed/output-tree.ts","../../extension-src/pi-style/features/tools/boxed/session-config.ts","../../extension-src/pi-style/features/tools/boxed/batch.ts","../../extension-src/pi-style/domain/config-diagnostics.ts","../../extension-src/pi-style/domain/config-presets.ts","../../extension-src/pi-style/domain/config-types.ts","../../extension-src/pi-style/domain/status-presets.ts","../../extension-src/pi-style/domain/config-normalization.ts","../../extension-src/pi-style/domain/config-migrations.ts","../../extension-src/pi-style/app/config-storage.ts","../../extension-src/pi-style/app/command-service.ts","../../extension-src/pi-style/app/commands.ts","../../extension-src/pi-style/pi/config-host.ts","../../extension-src/pi-style/pi/commands.ts","../../extension-src/pi-style/pi/session-coordinator.ts","../../extension-src/pi-style/app/doctor.ts","../../extension-src/pi-style/domain/config-diff.ts","../../extension-src/pi-style/domain/status.ts","../../extension-src/pi-style/features/editor/index.ts","../../extension-src/pi-style/domain/theme.ts","../../extension-src/pi-style/features/startup/logo.ts","../../extension-src/pi-style/features/startup/index.ts","../../extension-src/pi-style/domain/status-renderer.ts","../../extension-src/pi-style/features/status-line/index.ts","../../extension-src/pi-style/shared/disposable-store.ts","../../extension-src/pi-style/app/providers.ts","../../extension-src/pi-style/app/render-scheduler.ts","../../extension-src/pi-style/app/snapshot.ts","../../extension-src/pi-style/app/runtime.ts","../../extension-src/pi-style/app/index.ts","../../extension-src/pi-style/features/messages/special-blocks.ts","../../extension-src/pi-style/features/messages/boxed-block.ts","../../extension-src/pi-style/features/tools/boxed/bash.ts","../../extension-src/pi-style/features/tools/boxed/shared.ts","../../extension-src/pi-style/features/tools/boxed/grep.ts","../../extension-src/pi-style/domain/config-authorization.ts","../../extension-src/pi-style/pi/compatibility-probe.ts","../../extension-src/pi-style/features/messages/index.ts","../../extension-src/pi-style/features/tools/index.ts","../../extension-src/pi-style/features/tools/boxed/edit.ts","../../extension-src/pi-style/shared/split-diff.ts","../../extension-src/pi-style/features/tools/boxed/fallback.ts","../../extension-src/pi-style/features/tools/boxed/find.ts","../../extension-src/pi-style/features/tools/boxed/ls.ts","../../extension-src/pi-style/features/tools/boxed/quick-edit.ts","../../extension-src/pi-style/features/tools/boxed/read.ts","../../extension-src/pi-style/features/tools/boxed/write.ts","../../extension-src/pi-style/features/tools/boxed/index.ts","../../extension-src/pi-style/pi/compatibility-registry.ts","../../extension-src/pi-style/pi/compatibility-coordinator.ts","../../extension-src/pi-style/pi/config-session.ts","../../extension-src/pi-style/pi/operational-state.ts","../../extension-src/pi-style/pi/startup-resources.ts","../../extension-src/pi-style/pi/session-usage.ts","../../extension-src/pi-style/pi/index.ts"],"sourcesContent":["function isFinal(byte: string): boolean {\n\treturn byte >= \"@\" && byte <= \"~\";\n}\n\nconst CUBE_STEPS = [0, 95, 135, 175, 215, 255] as const;\n\nfunction xterm256ToRgb(index: number): { r: number; g: number; b: number } | undefined {\n\tif (index >= 0 && index < 16) {\n\t\t// Base 16 palette approximation used by the gradient logic.\n\t\tconst base = [\n\t\t\t[0, 0, 0],\n\t\t\t[128, 0, 0],\n\t\t\t[0, 128, 0],\n\t\t\t[128, 128, 0],\n\t\t\t[0, 0, 128],\n\t\t\t[128, 0, 128],\n\t\t\t[0, 128, 128],\n\t\t\t[192, 192, 192],\n\t\t\t[128, 128, 128],\n\t\t\t[255, 0, 0],\n\t\t\t[0, 255, 0],\n\t\t\t[255, 255, 0],\n\t\t\t[0, 0, 255],\n\t\t\t[255, 0, 255],\n\t\t\t[0, 255, 255],\n\t\t\t[255, 255, 255],\n\t\t] as const;\n\t\tconst entry = base[index] ?? [0, 0, 0];\n\t\tconst [r, g, b] = entry;\n\t\treturn { r, g, b };\n\t}\n\tif (index >= 16 && index < 232) {\n\t\tconst cube = index - 16;\n\t\treturn {\n\t\t\tr: CUBE_STEPS[Math.floor(cube / 36)] ?? 0,\n\t\t\tg: CUBE_STEPS[Math.floor((cube % 36) / 6)] ?? 0,\n\t\t\tb: CUBE_STEPS[cube % 6] ?? 0,\n\t\t};\n\t}\n\tif (index >= 232 && index < 256) {\n\t\tconst gray = 8 + 10 * (index - 232);\n\t\treturn { r: gray, g: gray, b: gray };\n\t}\n\treturn undefined;\n}\n\n/**\n * Parse an ANSI foreground prefix into RGB. Supports 24-bit `38;2;r;g;b` and\n * 256-color `38;5;N` forms; returns undefined when the prefix is empty or not\n * a foreground color (e.g. `38;5;Nm` reset fragments).\n */\nexport function parseAnsiFgToRgb(prefix: string): { r: number; g: number; b: number } | undefined {\n\tconst esc = \"\\u001b\";\n\tconst direct = new RegExp(`^${esc}\\\\[38;2;(\\\\d{1,3});(\\\\d{1,3});(\\\\d{1,3})m$`).exec(prefix);\n\tif (direct) {\n\t\tconst r = Number.parseInt(direct[1] ?? \"0\", 10);\n\t\tconst g = Number.parseInt(direct[2] ?? \"0\", 10);\n\t\tconst b = Number.parseInt(direct[3] ?? \"0\", 10);\n\t\tif (r <= 255 && g <= 255 && b <= 255) return { r, g, b };\n\t}\n\tconst indexed = new RegExp(`^${esc}\\\\[38;5;(\\\\d{1,3})m$`).exec(prefix);\n\tif (indexed) {\n\t\tconst index = Number.parseInt(indexed[1] ?? \"0\", 10);\n\t\tif (index <= 255) return xterm256ToRgb(index);\n\t}\n\treturn undefined;\n}\nexport function stripAnsi(value: string): string {\n\tlet output = \"\";\n\tfor (let i = 0; i < value.length; i++) {\n\t\tif (value.charCodeAt(i) !== 27) {\n\t\t\toutput += value[i];\n\t\t\tcontinue;\n\t\t}\n\t\ti++;\n\t\tif (value[i] === \"[\") {\n\t\t\twhile (i + 1 < value.length && !isFinal(value[i + 1] ?? \"\")) i++;\n\t\t\ti++;\n\t\t} else if (value[i] === \"]\") {\n\t\t\twhile (i + 1 < value.length && value.charCodeAt(i + 1) !== 7) {\n\t\t\t\ti++;\n\t\t\t\tif (value.charCodeAt(i) === 27 && value[i + 1] === \"\\\\\") {\n\t\t\t\t\ti++;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Consume the OSC terminator (BEL, or the ESC\\\\ already consumed above)\n\t\t\t// so it is not emitted as a visible character.\n\t\t\tif (i + 1 < value.length && value.charCodeAt(i + 1) === 7) i++;\n\t\t}\n\t}\n\treturn output;\n}\nexport function visibleWidth(value: string): number {\n\treturn [...stripAnsi(value)].length;\n}\nexport function resetAnsi(value: string): string {\n\treturn `${value}\\x1b[0m`;\n}\n\n/** Return the value unchanged when it fits the width; truncate it otherwise. */\nexport function fitAnsiWidth(value: string, width: number, ellipsis = \"…\"): string {\n\treturn visibleWidth(value) <= width ? value : truncateAnsi(value, width, ellipsis);\n}\nexport function truncateAnsi(value: string, width: number, ellipsis = \"…\"): string {\n\tif (width <= 0) return \"\";\n\tif (visibleWidth(value) <= width) return resetAnsi(value);\n\tlet output = \"\";\n\tlet visible = 0;\n\tfor (let i = 0; i < value.length && visible < width - visibleWidth(ellipsis); i++) {\n\t\tif (value.charCodeAt(i) === 27) {\n\t\t\tconst start = i;\n\t\t\ti++;\n\t\t\twhile (i + 1 < value.length && !isFinal(value[i + 1] ?? \"\")) i++;\n\t\t\ti++;\n\t\t\toutput += value.slice(start, i + 1);\n\t\t\tcontinue;\n\t\t}\n\t\toutput += value[i];\n\t\tvisible++;\n\t}\n\treturn resetAnsi(output + ellipsis);\n}\nexport function wrapAnsi(value: string, width: number): string[] {\n\tif (width <= 0) return [\"\"];\n\tconst lines: string[] = [];\n\tlet line = \"\";\n\tfor (const word of value.split(/\\s+/)) {\n\t\tconst next = line ? `${line} ${word}` : word;\n\t\tif (visibleWidth(next) <= width) line = next;\n\t\telse {\n\t\t\tif (line) lines.push(resetAnsi(line));\n\t\t\tline = truncateAnsi(word, width);\n\t\t}\n\t}\n\tif (line || lines.length === 0) lines.push(resetAnsi(line));\n\treturn lines;\n}\n\n// ── Hex color + background helpers ──\n\nexport const RESET_BACKGROUND = \"\\x1b[49m\";\nexport const ERASE_TO_END_OF_LINE = \"\\x1b[K\";\nconst ESC = \"\\x1b\";\n\nexport function isHexColor(value: string): boolean {\n\tconst cleaned = value.replace(\"#\", \"\");\n\treturn cleaned.length === 3\n\t\t? /^[0-9a-fA-F]{3}$/.test(cleaned)\n\t\t: (cleaned.length === 6 || cleaned.length === 8) && /^[0-9a-fA-F]+$/.test(cleaned);\n}\n\nexport function hexToRgb(hex: string): { r: number; g: number; b: number } {\n\tconst cleaned = hex.replace(\"#\", \"\");\n\tif (cleaned.length === 3) {\n\t\tconst r = Number.parseInt((cleaned[0] ?? \"\") + (cleaned[0] ?? \"\"), 16);\n\t\tconst g = Number.parseInt((cleaned[1] ?? \"\") + (cleaned[1] ?? \"\"), 16);\n\t\tconst b = Number.parseInt((cleaned[2] ?? \"\") + (cleaned[2] ?? \"\"), 16);\n\t\treturn { r, g, b };\n\t}\n\tif ((cleaned.length !== 6 && cleaned.length !== 8) || !/^[0-9a-fA-F]+$/.test(cleaned)) {\n\t\treturn { r: 0, g: 0, b: 0 };\n\t}\n\tconst r = Number.parseInt(cleaned.slice(0, 2), 16);\n\tconst g = Number.parseInt(cleaned.slice(2, 4), 16);\n\tconst b = Number.parseInt(cleaned.slice(4, 6), 16);\n\treturn { r, g, b };\n}\n\nfunction channelToHex(value: number): string {\n\treturn Math.max(0, Math.min(255, Math.round(value)))\n\t\t.toString(16)\n\t\t.padStart(2, \"0\");\n}\n\nexport function rgbToHex(rgb: { r: number; g: number; b: number }): string {\n\treturn `#${channelToHex(rgb.r)}${channelToHex(rgb.g)}${channelToHex(rgb.b)}`;\n}\n\nconst CUBE_VALUES = [0, 95, 135, 175, 215, 255] as const;\nconst GRAY_VALUES = Array.from({ length: 24 }, (_, i) => 8 + i * 10);\n\nfunction _ansi256ToRgb(index: number): { r: number; g: number; b: number } {\n\tif (index >= 232) {\n\t\tconst gray = 8 + (index - 232) * 10;\n\t\treturn { r: gray, g: gray, b: gray };\n\t}\n\tconst cubeIndex = Math.max(0, index - 16);\n\tconst redIndex = Math.floor(cubeIndex / 36);\n\tconst greenIndex = Math.floor((cubeIndex % 36) / 6);\n\tconst blueIndex = cubeIndex % 6;\n\treturn { r: CUBE_VALUES[redIndex] ?? 0, g: CUBE_VALUES[greenIndex] ?? 0, b: CUBE_VALUES[blueIndex] ?? 0 };\n}\n\nconst _ANSI_16_RGB: ReadonlyArray<readonly [number, number, number]> = [\n\t[0, 0, 0],\n\t[128, 0, 0],\n\t[0, 128, 0],\n\t[128, 128, 0],\n\t[0, 0, 128],\n\t[128, 0, 128],\n\t[0, 128, 128],\n\t[192, 192, 192],\n\t[128, 128, 128],\n\t[255, 0, 0],\n\t[0, 255, 0],\n\t[255, 255, 0],\n\t[0, 0, 255],\n\t[255, 0, 255],\n\t[0, 255, 255],\n\t[255, 255, 255],\n] as const;\n\nfunction colorDistance(r1: number, g1: number, b1: number, r2: number, g2: number, b2: number): number {\n\tconst dr = r1 - r2;\n\tconst dg = g1 - g2;\n\tconst db = b1 - b2;\n\treturn dr * dr * 0.299 + dg * dg * 0.587 + db * db * 0.114;\n}\n\nfunction findClosestCubeIndex(value: number): number {\n\tlet minDist = Number.POSITIVE_INFINITY;\n\tlet minIdx = 0;\n\tfor (let i = 0; i < CUBE_VALUES.length; i++) {\n\t\tconst dist = Math.abs(value - (CUBE_VALUES[i] ?? 0));\n\t\tif (dist < minDist) {\n\t\t\tminDist = dist;\n\t\t\tminIdx = i;\n\t\t}\n\t}\n\treturn minIdx;\n}\n\nfunction findClosestGrayIndex(gray: number): number {\n\tlet minDist = Number.POSITIVE_INFINITY;\n\tlet minIdx = 0;\n\tfor (let i = 0; i < GRAY_VALUES.length; i++) {\n\t\tconst dist = Math.abs(gray - (GRAY_VALUES[i] ?? 0));\n\t\tif (dist < minDist) {\n\t\t\tminDist = dist;\n\t\t\tminIdx = i;\n\t\t}\n\t}\n\treturn minIdx;\n}\n\nfunction rgbTo256(r: number, g: number, b: number): number {\n\tconst rIdx = findClosestCubeIndex(r);\n\tconst gIdx = findClosestCubeIndex(g);\n\tconst bIdx = findClosestCubeIndex(b);\n\tconst cubeR = CUBE_VALUES[rIdx] ?? 0;\n\tconst cubeG = CUBE_VALUES[gIdx] ?? 0;\n\tconst cubeB = CUBE_VALUES[bIdx] ?? 0;\n\tconst cubeIndex = 16 + 36 * rIdx + 6 * gIdx + bIdx;\n\tconst cubeDist = colorDistance(r, g, b, cubeR, cubeG, cubeB);\n\n\tconst gray = Math.round(0.299 * r + 0.587 * g + 0.114 * b);\n\tconst grayIdx = findClosestGrayIndex(gray);\n\tconst grayValue = GRAY_VALUES[grayIdx] ?? 0;\n\tconst grayIndex = 232 + grayIdx;\n\tconst grayDist = colorDistance(r, g, b, grayValue, grayValue, grayValue);\n\n\tconst spread = Math.max(r, g, b) - Math.min(r, g, b);\n\tif (spread < 10 && grayDist < cubeDist) return grayIndex;\n\treturn cubeIndex;\n}\n\n/** Color-mode-aware escape prefix/suffix pairs for a hex color (cached per mode+hex). */\nfunction colorEscapes(mode: string, hex: string, kind: \"fg\" | \"bg\"): { prefix: string; suffix: string } | undefined {\n\tif (!isHexColor(hex)) return undefined;\n\tconst { r, g, b } = hexToRgb(hex);\n\tconst cacheKey = `${mode}:${kind}:${hex}`;\n\tconst cache = kind === \"fg\" ? fgEscapeCache : bgEscapeCache;\n\tlet cached = cache.get(cacheKey);\n\tif (!cached) {\n\t\tif (mode === \"256color\") {\n\t\t\tconst idx = rgbTo256(r, g, b);\n\t\t\tcached = {\n\t\t\t\tprefix: `\\x1b[${kind === \"fg\" ? 38 : 48};5;${idx}m`,\n\t\t\t\tsuffix: kind === \"fg\" ? \"\\x1b[39m\" : RESET_BACKGROUND,\n\t\t\t};\n\t\t} else {\n\t\t\tcached = {\n\t\t\t\tprefix: `\\x1b[${kind === \"fg\" ? 38 : 48};2;${r};${g};${b}m`,\n\t\t\t\tsuffix: kind === \"fg\" ? \"\\x1b[39m\" : RESET_BACKGROUND,\n\t\t\t};\n\t\t}\n\t\tcache.set(cacheKey, cached);\n\t}\n\treturn cached;\n}\n\nconst fgEscapeCache = new Map<string, { prefix: string; suffix: string }>();\nconst bgEscapeCache = new Map<string, { prefix: string; suffix: string }>();\n\n/** Foreground-styling helper: accepts a theme (for getColorMode) or \"truecolor\". */\nexport function fgHex(theme: { getColorMode?: () => string } | undefined, hex: string, text: string): string {\n\tconst mode = typeof theme?.getColorMode === \"function\" ? theme.getColorMode() : \"truecolor\";\n\tconst escapes = colorEscapes(mode, hex, \"fg\");\n\tif (!escapes) return text;\n\treturn `${escapes.prefix}${text}${escapes.suffix}`;\n}\n\n/** Background ANSI prefix for a hex color, or \"\" when not a hex color. */\nexport function bgHexAnsi(theme: { getColorMode?: () => string } | undefined, hex: string): string {\n\tconst mode = typeof theme?.getColorMode === \"function\" ? theme.getColorMode() : \"truecolor\";\n\treturn colorEscapes(mode, hex, \"bg\")?.prefix ?? \"\";\n}\n\nexport function bgHex(theme: { getColorMode?: () => string } | undefined, hex: string, text: string): string {\n\tconst mode = typeof theme?.getColorMode === \"function\" ? theme.getColorMode() : \"truecolor\";\n\tconst escapes = colorEscapes(mode, hex, \"bg\");\n\tif (!escapes) return text;\n\treturn `${escapes.prefix}${text}${escapes.suffix}`;\n}\n\n/** Whether an SGR code sequence contains a background-affecting action (set/reset). */\nfunction finalBackgroundAction(rawCodes: string): \"none\" | \"reset\" | \"set\" {\n\tconst codes = rawCodes.split(\";\").filter(Boolean);\n\tif (codes.length === 0) return \"reset\";\n\tlet action: \"none\" | \"reset\" | \"set\" = \"none\";\n\tconst sgrColorParameterEnd = (index: number): number => {\n\t\tconst code = Number(codes[index]);\n\t\tif (code !== 38 && code !== 48) return index;\n\t\tconst mode = Number(codes[index + 1]);\n\t\tif (mode === 2) return Math.min(codes.length - 1, index + 4);\n\t\tif (mode === 5) return Math.min(codes.length - 1, index + 2);\n\t\treturn index;\n\t};\n\tfor (let i = 0; i < codes.length; i++) {\n\t\tconst code = Number(codes[i]);\n\t\tif (code === 0 || code === 49) {\n\t\t\taction = \"reset\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (code === 48) {\n\t\t\taction = \"set\";\n\t\t\ti = sgrColorParameterEnd(i);\n\t\t\tcontinue;\n\t\t}\n\t\tif (code === 38) {\n\t\t\ti = sgrColorParameterEnd(i);\n\t\t\tcontinue;\n\t\t}\n\t\tif ((code >= 40 && code <= 47) || (code >= 100 && code <= 107)) action = \"set\";\n\t}\n\treturn action;\n}\n\nfunction removeStandaloneBackgroundReset(rawCodes: string): string {\n\tconst codes = rawCodes.split(\";\").filter(Boolean);\n\tif (codes.length === 0) return \"0\";\n\tconst rebuilt: string[] = [];\n\tconst sgrColorParameterEnd = (index: number): number => {\n\t\tconst code = Number(codes[index]);\n\t\tif (code !== 38 && code !== 48) return index;\n\t\tconst mode = Number(codes[index + 1]);\n\t\tif (mode === 2) return Math.min(codes.length - 1, index + 4);\n\t\tif (mode === 5) return Math.min(codes.length - 1, index + 2);\n\t\treturn index;\n\t};\n\tfor (let i = 0; i < codes.length; i++) {\n\t\tconst code = Number(codes[i]);\n\t\tif (code === 49) continue;\n\t\tconst end = sgrColorParameterEnd(i);\n\t\tfor (let j = i; j <= end; j++) rebuilt.push(codes[j] ?? \"\");\n\t\ti = end;\n\t}\n\treturn rebuilt.join(\";\");\n}\n\n/** Re-apply a background after reset sequences so a fill survives nested resets. */\nexport function keepAnsiBackgroundAcrossResets(text: string, bgAnsi: string): string {\n\tif (!text) return text;\n\treturn text.replace(new RegExp(`${ESC}\\\\[([0-9;]*)m`, \"g\"), (sequence, rawCodes) => {\n\t\tconst codes = String(rawCodes ?? \"\");\n\t\tif (finalBackgroundAction(codes) !== \"reset\") return sequence;\n\t\tconst rebuilt = removeStandaloneBackgroundReset(codes);\n\t\treturn `${rebuilt ? `\\x1b[${rebuilt}m` : \"\"}${bgAnsi}`;\n\t});\n}\n\n/** Wrap text in a background fill that survives nested resets; optional fill-to-end-of-line. */\nexport function wrapAnsiBackground(text: string, bgAnsi: string, options: { fillToEnd?: boolean } = {}): string {\n\tif (!bgAnsi || bgAnsi === RESET_BACKGROUND) return text;\n\tconst body = keepAnsiBackgroundAcrossResets(text, bgAnsi);\n\tconst fill = options.fillToEnd ? `${bgAnsi}${ERASE_TO_END_OF_LINE}` : \"\";\n\treturn `${bgAnsi}${body}${fill}${RESET_BACKGROUND}`;\n}\n","// Boxed tool-call/result rendering primitives.\n//\n// Two deliberate design points:\n//\n// 1. Background painting is removed. Boxed lines are foreground-only; the\n// enclosing native ToolExecutionComponent container applies the semantic\n// status background (toolPendingBg / toolErrorBg / toolSuccessBg), and the\n// message-block Box applies customMessageBg. This avoids double-background\n// conflicts and keeps pi-style's patches renderer-scoped.\n//\n// 2. Theme functions are accessed through a minimal structural interface\n// (BoxTheme) instead of `any`.\n\nimport { homedir } from \"node:os\";\nimport { relative, resolve } from \"node:path\";\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport { fgHex, isHexColor, stripAnsi } from \"./ansi.js\";\nimport { formatToolMetrics, getElapsedMs, type MetricResultLike } from \"./elapsed.js\";\nimport {\n\tboxedResultRenderBudget,\n\tclampRenderLine,\n\tDEFAULT_COLLAPSED_RENDER_LINES,\n\tfastBoxLineContent,\n\tsafeTruncateToWidth,\n\tsafeVisibleWidth,\n\tsafeWrapTextWithAnsi,\n} from \"./render-budget.js\";\nimport { getThemeExtra } from \"./theme-extras.js\";\n\n/** Minimal structural view of Pi's Theme as used by the boxed renderers. */\nexport interface BoxTheme {\n\tfg(color: string, text: string): string;\n\tbold?(text: string): string;\n\titalic?(text: string): string;\n\tinverse?(text: string): string;\n\tgetColorMode?(): string;\n}\n\nexport interface BoxedRenderOptions {\n\twidthKey?: string;\n\t/** Detail embedded in the top-border title after the tool name (e.g. the path). */\n\theaderDetail?: string;\n\tisError?: boolean;\n\tisPartial?: boolean;\n\tisPending?: boolean;\n\t/** Execution has started but the tool is still running (title `◌` instead of `✓`). */\n\trunning?: boolean;\n\t/** A result renderer already produced a continuation for this call, so the call\n\t * leaves the box open instead of closing it with a pending label. */\n\tresultSeen?: boolean;\n\tpendingText?: string;\n\t/** Verbatim bottom-border label for the pending/running card (overrides the\n\t * `… ${pendingText}` default, e.g. a live `◌ Running · 12.4s` status). */\n\tpendingLabel?: string;\n\tstate?: Record<string, unknown>;\n\t/** Wall-clock elapsed override (used when metrics are not in result.details). */\n\telapsedMs?: number;\n\t/** Width-dependent content lines rendered between the top border and the\n\t * footer border of a compact box (replaces the blank breathing line).\n\t * Each returned line is truncated to the box inner width by the renderer.\n\t * Returns an empty array for no body (blank line preserved). */\n\tbodyLines?: (contentWidth: number) => string[];\n\t/** Right-side label embedded in the compact box bottom border before the\n\t * corner (e.g. an expand hint such as `Ctrl+O for more`). */\n\tbottomRightLabel?: string;\n}\n\nexport function isExpanded(options: { expanded?: boolean } | undefined): boolean {\n\treturn typeof options?.expanded === \"boolean\" ? options.expanded : false;\n}\n\nexport function shortenPath(path: string): string {\n\tconst home = homedir();\n\tif (path.startsWith(home)) return `~${path.slice(home.length)}`;\n\treturn path;\n}\n\nexport function resolveAbsolutePath(rawPath: string, cwd: string): string {\n\tconst path = rawPath.trim();\n\tif (!path) return \"\";\n\n\tconst home = process.env.HOME;\n\tif (home && (path === \"~\" || path.startsWith(\"~/\"))) {\n\t\treturn path === \"~\" ? home : resolve(home, path.slice(2));\n\t}\n\n\treturn resolve(cwd, path);\n}\n\nexport function resolveRelativePath(rawPath: string, cwd: string): string {\n\tconst absPath = resolveAbsolutePath(rawPath, cwd);\n\tif (!absPath) return \"(unknown)\";\n\tconst relPath = relative(cwd, absPath).replace(/\\\\/g, \"/\");\n\treturn relPath || \".\";\n}\n\nexport function replaceTabs(text: string): string {\n\treturn text.replace(/\\t/g, \" \");\n}\n\nexport function getTextOutput(result: MetricResultLike | undefined): string {\n\tif (!result?.content) return \"\";\n\tconst textBlocks = result.content.filter((contentBlock) => {\n\t\tif (!contentBlock || typeof contentBlock !== \"object\") return false;\n\t\treturn (contentBlock as { type?: unknown }).type === \"text\";\n\t});\n\treturn textBlocks\n\t\t.map((contentBlock) => String((contentBlock as { text?: unknown }).text ?? \"\"))\n\t\t.join(\"\\n\")\n\t\t.replace(/\\r/g, \"\");\n}\n\nexport function stripTrailingNotice(text: string): string {\n\tconst normalized = (text ?? \"\").replace(/\\r/g, \"\").trimEnd();\n\tif (!normalized) return \"\";\n\tif (normalized.startsWith(\"[\") && normalized.endsWith(\"]\")) return \"\";\n\tconst noticeStart = normalized.lastIndexOf(\"\\n\\n[\");\n\tif (noticeStart >= 0 && normalized.endsWith(\"]\")) {\n\t\treturn normalized.slice(0, noticeStart).trimEnd();\n\t}\n\treturn normalized;\n}\n\nexport function extractTrailingNotice(text: string): string | null {\n\tconst normalized = (text ?? \"\").replace(/\\r/g, \"\").trimEnd();\n\tif (!normalized) return null;\n\tif (normalized.startsWith(\"[\") && normalized.endsWith(\"]\")) return normalized;\n\tconst noticeStart = normalized.lastIndexOf(\"\\n\\n[\");\n\tif (noticeStart >= 0 && normalized.endsWith(\"]\")) {\n\t\treturn normalized.slice(noticeStart + 2).trimEnd();\n\t}\n\treturn null;\n}\n\nexport function countLines(text: string): number {\n\tconst normalized = (text ?? \"\").replace(/\\r/g, \"\").replace(/\\n+$/g, \"\");\n\tif (!normalized) return 0;\n\treturn normalized.split(\"\\n\").length;\n}\n\nexport function countWords(text: string): number {\n\tlet count = 0;\n\tlet inWord = false;\n\tfor (const char of text) {\n\t\tconst isWord = /[\\p{L}\\p{N}_'-]/u.test(char);\n\t\tif (isWord && !inWord) count++;\n\t\tinWord = isWord;\n\t}\n\treturn count;\n}\n\nexport function formatCompactCount(value: number): string {\n\tif (value < 1000) return `${Math.round(value)}`;\n\tif (value < 10000) return `${(value / 1000).toFixed(1)}k`;\n\tif (value < 1000000) return `${Math.round(value / 1000)}k`;\n\tif (value < 10000000) return `${(value / 1000000).toFixed(1)}M`;\n\treturn `${Math.round(value / 1000000)}M`;\n}\n\nexport function formatBoxedWords(text: string): string {\n\treturn `~${formatCompactCount(countWords(text))} words`;\n}\n\nexport function badge(theme: BoxTheme, label: string): string {\n\tconst tagBg = getThemeExtra(theme, \"tagBgColor\");\n\tif (tagBg && isHexColor(tagBg)) {\n\t\treturn theme.inverse\n\t\t\t? theme.inverse(fgHex(theme, tagBg, theme.bold ? theme.bold(` ${label} `) : ` ${label} `))\n\t\t\t: fgHex(theme, tagBg, theme.bold ? theme.bold(` ${label} `) : ` ${label} `);\n\t}\n\treturn theme.inverse ? theme.inverse(theme.bold ? theme.bold(` ${label} `) : ` ${label} `) : ` ${label} `;\n}\n\nexport function parens(theme: BoxTheme, text: string, skipTextColor?: boolean): string {\n\tconst bracketColor = getThemeExtra(theme, \"parensBracketColor\");\n\tconst openParen = bracketColor && isHexColor(bracketColor) ? fgHex(theme, bracketColor, \"(\") : \"(\";\n\tconst closeParen = bracketColor && isHexColor(bracketColor) ? fgHex(theme, bracketColor, \")\") : \")\";\n\tlet innerBase: string;\n\tif (skipTextColor) {\n\t\tinnerBase = text;\n\t} else {\n\t\tconst textColor = getThemeExtra(theme, \"parensTextColor\");\n\t\tinnerBase = textColor && isHexColor(textColor) ? fgHex(theme, textColor, text) : text;\n\t}\n\tconst inner = typeof theme?.bold === \"function\" ? theme.bold(innerBase) : `\\x1b[1m${innerBase}\\x1b[22m`;\n\treturn `${openParen}${inner}${closeParen}`;\n}\n\nconst BOX_HORIZONTAL = \"─\";\nconst BOX_VERTICAL = \"│\";\nconst BOX_SIDE_PADDING = 2;\nconst BOX_MIN_WIDTH = 12;\nconst BOX_ROUND_TOP_LEFT = \"╭\";\nconst BOX_ROUND_TOP_RIGHT = \"╮\";\nconst BOX_ROUND_BOTTOM_LEFT = \"╰\";\nconst BOX_ROUND_BOTTOM_RIGHT = \"╯\";\nconst BOX_DIVIDER_LEFT = \"├\";\nconst BOX_DIVIDER_RIGHT = \"┤\";\n/** Dash run before the right corner when a right-side border label is present. */\nconst BOX_LABELED_RIGHT_DASH_MIN = 3;\nconst BOX_WIDTH_CACHE = new Map<string, number>();\n\nexport function boxWidth(width: number): number {\n\treturn Math.max(BOX_MIN_WIDTH, width);\n}\n\nexport function boxInnerWidth(width: number): number {\n\treturn Math.max(1, boxWidth(width) - 2 - BOX_SIDE_PADDING * 2);\n}\n\nfunction _tightBoxWidth(\n\tavailableWidth: number,\n\tcontentLines: string[],\n\tlabelWidths: number[] = [],\n\twidthKey?: string,\n): number {\n\tconst contentWidth = contentLines.reduce((max, line) => Math.max(max, safeVisibleWidth(line)), 0);\n\tconst labelWidth = labelWidths.reduce((max, width) => Math.max(max, width), 0);\n\tconst neededWidth = Math.max(\n\t\tBOX_MIN_WIDTH,\n\t\tcontentWidth + 2 + BOX_SIDE_PADDING * 2,\n\t\tlabelWidth + 2 + BOX_SIDE_PADDING * 2,\n\t);\n\tconst measuredWidth = Math.min(boxWidth(availableWidth), neededWidth);\n\tif (!widthKey) return measuredWidth;\n\tconst cachedWidth = BOX_WIDTH_CACHE.get(widthKey) ?? 0;\n\tconst nextWidth = Math.min(boxWidth(availableWidth), Math.max(cachedWidth, measuredWidth));\n\tBOX_WIDTH_CACHE.set(widthKey, nextWidth);\n\treturn nextWidth;\n}\n\nexport function boxedToolWidthKey(toolName: string, detail: string): string {\n\treturn `${toolName}:${detail}`;\n}\n\nexport function formatToolName(toolName: string): string {\n\tconst spaced = toolName\n\t\t.replace(/[_-]+/g, \" \")\n\t\t.replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n\t\t.replace(/([A-Z]+)([A-Z][a-z])/g, \"$1 $2\")\n\t\t.trim();\n\treturn spaced.replace(/\\b\\w/g, (char) => char.toUpperCase()) || toolName;\n}\n\nfunction formatToolParamName(name: string): string {\n\tconst spaced = name\n\t\t.replace(/[_-]+/g, \" \")\n\t\t.replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n\t\t.replace(/([A-Z]+)([A-Z][a-z])/g, \"$1 $2\")\n\t\t.trim();\n\treturn spaced ? spaced[0]?.toUpperCase() + spaced.slice(1) : name;\n}\n\nconst MAX_PARAM_VALUE_LENGTH = 120;\n\nfunction formatOperationSummary(value: unknown): string | undefined {\n\tif (!Array.isArray(value) || value.length === 0) return undefined;\n\tif (!value.every((item) => item && typeof item === \"object\" && !Array.isArray(item))) return undefined;\n\tconst types = Array.from(new Set(value.map((item) => String((item as { type?: unknown }).type ?? \"operation\"))));\n\tconst typeSummary =\n\t\ttypes.length === 1\n\t\t\t? ` (${types[0]})`\n\t\t\t: types.length > 1\n\t\t\t\t? ` (${types.slice(0, 3).join(\", \")}${types.length > 3 ? \", …\" : \"\"})`\n\t\t\t\t: \"\";\n\treturn `${value.length} ${value.length === 1 ? \"operation\" : \"operations\"}${typeSummary}`;\n}\n\nfunction formatToolParamValue(value: unknown): string {\n\tif (value === undefined) return \"\";\n\tif (value === null) return \"null\";\n\tif (typeof value === \"string\") {\n\t\tif (value.length <= MAX_PARAM_VALUE_LENGTH) return value;\n\t\treturn `${value.slice(0, MAX_PARAM_VALUE_LENGTH)}…`;\n\t}\n\tif (typeof value === \"number\" || typeof value === \"boolean\" || typeof value === \"bigint\") return String(value);\n\tif (Array.isArray(value)) {\n\t\tif (value.length === 0) return \"[]\";\n\t\treturn formatOperationSummary(value) ?? `${value.length} ${value.length === 1 ? \"item\" : \"items\"}`;\n\t}\n\tif (typeof value === \"object\" && value !== null) {\n\t\tconst keys = Object.keys(value);\n\t\tif (keys.length === 0) return \"{}\";\n\t\treturn `{${keys.length} ${keys.length === 1 ? \"key\" : \"keys\"}}`;\n\t}\n\ttry {\n\t\tconst json = JSON.stringify(value);\n\t\tif (json.length <= MAX_PARAM_VALUE_LENGTH) return json;\n\t\treturn `${json.slice(0, MAX_PARAM_VALUE_LENGTH)}…`;\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n\nexport function formatToolParamLines(args: unknown, theme?: BoxTheme): string[] {\n\tif (args === undefined || args === null) return [];\n\tif (typeof args !== \"object\" || Array.isArray(args)) {\n\t\tconst value = formatToolParamValue(args);\n\t\treturn value ? [`Params: ${value}`] : [];\n\t}\n\n\tconst entries = Object.entries(args as Record<string, unknown>).filter(([, value]) => value !== undefined);\n\tif (entries.length === 0) return [];\n\n\tconst lines: string[] = [];\n\tfor (const [key, value] of entries) {\n\t\tconst formattedValue = formatToolParamValue(value);\n\t\tif (!formattedValue) continue;\n\t\tconst [firstLine = \"\", ...restLines] = formattedValue.replace(/\\r/g, \"\").split(\"\\n\");\n\t\tconst keyLabel = formatToolParamName(key);\n\t\tif (theme) {\n\t\t\tlines.push(`${theme.fg(\"dim\", `${keyLabel}:`)} ${theme.fg(\"text\", firstLine)}`);\n\t\t\tlines.push(...restLines.map((line) => ` ${theme.fg(\"text\", line)}`));\n\t\t} else {\n\t\t\tlines.push(`${keyLabel}: ${firstLine}`);\n\t\t\tlines.push(...restLines.map((line) => ` ${line}`));\n\t\t}\n\t}\n\treturn lines;\n}\n\nconst RESET_INTENSITY = \"\\x1b[22m\";\n\nfunction colorFromExtra(theme: BoxTheme, extraKey: string, fallbackColor: string, text: string): string {\n\tconst color = getThemeExtra(theme, extraKey);\n\tif (color) {\n\t\tif (isHexColor(color)) return fgHex(theme, color, text);\n\t\ttry {\n\t\t\treturn theme.fg(color, text);\n\t\t} catch {\n\t\t\t// Fall back to semantic theme color below.\n\t\t}\n\t}\n\treturn theme.fg(fallbackColor, text);\n}\n\nfunction formatBoxedStatusIcon(theme: BoxTheme, isError?: boolean): string {\n\tconst icon = isError ? \"✗\" : \"✓\";\n\treturn theme.fg(isError ? \"error\" : \"success\", icon);\n}\n\n/**\n * Colored `➔ Name` prefix for tool titles (identity color). The status glyph\n * (✓/◌/✗) is appended separately by formatBoxedToolTitle.\n */\nexport function formatToolTitlePrefix(theme: BoxTheme, name: string): string {\n\treturn colorFromExtra(theme, \"bashPromptColor\", \"bashMode\", `➔ ${name}`);\n}\n\nexport type BoxedTitleStatus = \"running\" | \"pending\";\n\n/**\n * Boxed tool title: `➔ Name ✓` when settled, `➔ Name ◌` while running, plain\n * `➔ Name` while pending, and a fully error-colored `➔ Name ✗` on failure.\n * The ✓/◌ glyphs are never shown before the tool settles, so a card that is\n * still executing never reads as finished.\n */\nexport function formatBoxedToolTitle(\n\ttheme: BoxTheme,\n\tname: string,\n\tisError?: boolean,\n\tstatus?: BoxedTitleStatus,\n): string {\n\t// On failure the whole title turns error-colored (not just the ✗) so a failed\n\t// tool reads instantly; on success the tool keeps its identity color and only\n\t// the ✓ carries the success color.\n\tconst coloredTitle = isError\n\t\t? theme.fg(\"error\", `➔ ${name} ✗`)\n\t\t: status === \"running\"\n\t\t\t? `${formatToolTitlePrefix(theme, name)} ${theme.fg(\"text\", \"◌\")}`\n\t\t\t: status === \"pending\"\n\t\t\t\t? formatToolTitlePrefix(theme, name)\n\t\t\t\t: `${formatToolTitlePrefix(theme, name)} ${formatBoxedStatusIcon(theme, false)}`;\n\treturn typeof theme?.bold === \"function\" ? theme.bold(coloredTitle) : coloredTitle;\n}\n\n/** Live running status label for pending/running cards and streaming footers. */\nexport function formatBoxedRunningStatus(theme: BoxTheme, elapsedMs: number | undefined): string {\n\tconst elapsed = elapsedMs === undefined ? \"\" : `${theme.fg(\"text\", ` · ${(elapsedMs / 1000).toFixed(1)}s`)}`;\n\treturn `${theme.fg(\"dim\", \"◌ Running\")}${elapsed}`;\n}\n\nfunction boxText(theme: BoxTheme, text: string): string {\n\treturn `${RESET_INTENSITY}${theme.fg(\"borderMuted\", text)}`;\n}\nfunction boxFrameText(theme: BoxTheme, text: string): string {\n\treturn `${RESET_INTENSITY}${theme.fg(\"border\", text)}`;\n}\n\nexport function boxedToolBgName(isError?: boolean, isPartial?: boolean): string {\n\treturn isPartial ? \"toolPendingBg\" : isError ? \"toolErrorBg\" : \"toolSuccessBg\";\n}\n\nexport function boxBorder(theme: BoxTheme, left: string, right: string, width: number): string {\n\tconst renderedWidth = boxWidth(width);\n\tconst innerWidth = renderedWidth - 2;\n\treturn boxFrameText(theme, `${left}${BOX_HORIZONTAL.repeat(innerWidth)}${right}`);\n}\n\n/**\n * Border line with an optional label embedded after the left corner and an\n * optional right-side label before the right corner, e.g.:\n *\n * ╭─ ➔ Bash ✓ ────────────╮\n * ├─ Response ────────────┤\n * ╰─ 0.00s · ~45 words ──── Ctrl+O for more ───╯\n */\nexport function boxLabeledBorder(\n\ttheme: BoxTheme,\n\tstart: string,\n\tend: string,\n\tleftLabel: string,\n\trightLabel: string | undefined,\n\twidth: number,\n): string {\n\tconst renderedWidth = boxWidth(width);\n\tlet left = leftLabel ?? \"\";\n\tconst right = rightLabel ?? \"\";\n\tlet leftWidth = safeVisibleWidth(left);\n\tconst rightWidth = safeVisibleWidth(right);\n\tconst leftOverhead = left ? 3 : 0; // \"─ \" prefix + \" \" suffix\n\tconst rightOverhead = right ? 2 : 0; // \" \" prefix + \" \" suffix\n\tlet rightFill = right ? BOX_LABELED_RIGHT_DASH_MIN : 0;\n\tlet fill =\n\t\trenderedWidth - start.length - end.length - leftOverhead - leftWidth - rightOverhead - rightWidth - rightFill;\n\n\tif (right && fill < 0) {\n\t\trightFill = 1;\n\t\tfill =\n\t\t\trenderedWidth - start.length - end.length - leftOverhead - leftWidth - rightOverhead - rightWidth - rightFill;\n\t}\n\n\tif (fill < 0) {\n\t\t// Too narrow for the labels: truncate the left label, keeping at least one\n\t\t// filler dash so the border stays closed.\n\t\tconst reserved =\n\t\t\tstart.length + end.length + leftOverhead + (right ? rightOverhead + rightWidth + rightFill : 0) + 1;\n\t\tconst maxLeft = renderedWidth - reserved;\n\t\tleft = maxLeft > 0 ? safeTruncateToWidth(left, maxLeft, \"…\") : \"\";\n\t\tleftWidth = safeVisibleWidth(left);\n\t\tfill =\n\t\t\trenderedWidth -\n\t\t\tstart.length -\n\t\t\tend.length -\n\t\t\t(left ? leftWidth + leftOverhead : 0) -\n\t\t\t(right ? rightOverhead + rightWidth + rightFill : 0);\n\t}\n\n\t// Style each border segment separately. Embedded labels carry their own\n\t// foreground escapes that end in \\x1b[39m (reset to the terminal default);\n\t// applying the border color to the whole line in one wrap would leave every\n\t// dash after a label in the default color, making one border render with\n\t// mixed brightness.\n\tconst parts: string[] = [boxFrameText(theme, `${start}${left ? \"─ \" : \"\"}`)];\n\tif (left) parts.push(left);\n\tparts.push(boxFrameText(theme, `${left ? \" \" : \"\"}${BOX_HORIZONTAL.repeat(Math.max(0, fill))}`));\n\tif (right) {\n\t\tparts.push(boxFrameText(theme, \" \"), right, boxFrameText(theme, ` ${BOX_HORIZONTAL.repeat(rightFill)}`));\n\t}\n\tparts.push(boxFrameText(theme, end));\n\treturn parts.join(\"\");\n}\n\n/** Empty content line used for breathing room inside a box. */\nexport function boxBlankLine(theme: BoxTheme, width: number): string {\n\tconst renderedWidth = boxWidth(width);\n\tconst contentWidth = boxInnerWidth(renderedWidth);\n\tconst sidePad = \" \".repeat(BOX_SIDE_PADDING);\n\treturn `${boxFrameText(theme, BOX_VERTICAL)}${sidePad}${\" \".repeat(contentWidth)}${sidePad}${boxFrameText(theme, BOX_VERTICAL)}`;\n}\n\nexport function boxLineAligned(theme: BoxTheme, left: string, right: string, width: number): string {\n\tconst renderedWidth = boxWidth(width);\n\tconst contentWidth = boxInnerWidth(renderedWidth);\n\tconst rightWidth = safeVisibleWidth(right);\n\tconst sidePad = \" \".repeat(BOX_SIDE_PADDING);\n\n\tif (!right || rightWidth >= contentWidth) {\n\t\treturn boxLine(theme, right || left, renderedWidth);\n\t}\n\n\tconst maxLeftWidth = Math.max(1, contentWidth - rightWidth - 1);\n\tconst truncatedLeft = safeTruncateToWidth(left, maxLeftWidth, \"…\");\n\tconst gap = \" \".repeat(Math.max(1, contentWidth - safeVisibleWidth(truncatedLeft) - rightWidth));\n\treturn `${boxFrameText(theme, BOX_VERTICAL)}${sidePad}${truncatedLeft}${gap}${right}${sidePad}${boxFrameText(theme, BOX_VERTICAL)}`;\n}\n\nexport function boxLineWithRight(theme: BoxTheme, left: string, right: string, width: number): string {\n\tconst renderedWidth = boxWidth(width);\n\tconst contentWidth = boxInnerWidth(renderedWidth);\n\tconst divider = ` ${boxText(theme, \"|\")} `;\n\tconst dividerWidth = safeVisibleWidth(divider);\n\tconst rightWidth = safeVisibleWidth(right);\n\tconst sidePad = \" \".repeat(BOX_SIDE_PADDING);\n\n\tif (!right || rightWidth + dividerWidth >= contentWidth) {\n\t\treturn boxLine(theme, right || left, renderedWidth);\n\t}\n\n\tconst maxLeftWidth = Math.max(1, contentWidth - dividerWidth - rightWidth - 1);\n\tconst truncatedLeft = safeTruncateToWidth(left, maxLeftWidth, \"…\");\n\tconst gap = \" \".repeat(Math.max(1, contentWidth - safeVisibleWidth(truncatedLeft) - dividerWidth - rightWidth));\n\treturn `${boxFrameText(theme, BOX_VERTICAL)}${sidePad}${truncatedLeft}${gap}${divider}${right}${sidePad}${boxFrameText(theme, BOX_VERTICAL)}`;\n}\n\nexport function boxLine(theme: BoxTheme, content: string, width: number): string {\n\tconst renderedWidth = boxWidth(width);\n\tconst contentWidth = boxInnerWidth(renderedWidth);\n\tconst fastContent = fastBoxLineContent(content, contentWidth);\n\tconst sidePad = \" \".repeat(BOX_SIDE_PADDING);\n\tif (fastContent) {\n\t\tconst fill = \" \".repeat(Math.max(0, contentWidth - fastContent.visibleWidth));\n\t\treturn `${boxFrameText(theme, BOX_VERTICAL)}${sidePad}${fastContent.text}${fill}${sidePad}${boxFrameText(theme, BOX_VERTICAL)}`;\n\t}\n\n\tconst truncated = safeTruncateToWidth(content, contentWidth, \"…\");\n\tconst fill = \" \".repeat(Math.max(0, contentWidth - safeVisibleWidth(truncated)));\n\treturn `${boxFrameText(theme, BOX_VERTICAL)}${sidePad}${truncated}${fill}${sidePad}${boxFrameText(theme, BOX_VERTICAL)}`;\n}\n\nexport function boxInsetDivider(theme: BoxTheme, width: number): string {\n\tconst renderedWidth = boxWidth(width);\n\tconst lineWidth = boxInnerWidth(renderedWidth);\n\tconst sidePad = \" \".repeat(BOX_SIDE_PADDING);\n\treturn `${boxFrameText(theme, BOX_VERTICAL)}${sidePad}${boxText(theme, BOX_HORIZONTAL.repeat(lineWidth))}${sidePad}${boxFrameText(theme, BOX_VERTICAL)}`;\n}\n\nexport function boxedWrappedLines(theme: BoxTheme, content: string, width: number): string[] {\n\treturn safeWrapTextWithAnsi(content, boxInnerWidth(width)).map((line) => boxLine(theme, line, width));\n}\n\nfunction boxedTruncatedLine(theme: BoxTheme, content: string, width: number): string {\n\treturn boxLine(theme, safeTruncateToWidth(content, boxInnerWidth(width), \"…\"), width);\n}\n\ntype RenderLinesCache = {\n\twidth: number;\n\tlines: string[];\n};\n\nfunction pushBoundedLines(target: string[], lines: string[], maxLines: number): boolean {\n\tconst slots = maxLines - target.length;\n\tif (slots <= 0) return false;\n\tif (lines.length > slots) {\n\t\ttarget.push(...lines.slice(0, slots));\n\t\treturn false;\n\t}\n\ttarget.push(...lines);\n\treturn true;\n}\n\nfunction renderBoxedOutputLines(\n\ttheme: BoxTheme,\n\toutputLines: string[],\n\twidth: number,\n\trawLineBudget = DEFAULT_COLLAPSED_RENDER_LINES,\n): string[] {\n\tconst budget = boxedResultRenderBudget(rawLineBudget);\n\tconst headLimit = Math.max(0, Math.min(budget.headLines, budget.maxRenderedLines));\n\tconst tailLimit = Math.max(0, Math.min(budget.tailLines, Math.max(0, budget.maxRenderedLines - headLimit - 1)));\n\tconst head: string[] = [];\n\tlet nextInputIndex = 0;\n\tlet truncated = false;\n\n\tfor (; nextInputIndex < outputLines.length; nextInputIndex++) {\n\t\tconst line = boxedTruncatedLine(theme, outputLines[nextInputIndex] ?? \"\", width);\n\t\tif (!pushBoundedLines(head, [line], headLimit)) {\n\t\t\ttruncated = true;\n\t\t\tnextInputIndex++;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!truncated && nextInputIndex >= outputLines.length) return head;\n\n\tconst tail: string[] = [];\n\tconst tailStart = Math.max(nextInputIndex, outputLines.length - tailLimit);\n\tfor (let i = tailStart; i < outputLines.length; i++) {\n\t\tconst line = boxedTruncatedLine(theme, outputLines[i] ?? \"\", width);\n\t\ttail.push(line);\n\t\tif (tail.length > tailLimit) tail.splice(0, tail.length - tailLimit);\n\t}\n\n\tconst skippedInputLines = Math.max(0, tailStart - nextInputIndex);\n\tconst skippedText =\n\t\tskippedInputLines > 0\n\t\t\t? `… rendered output truncated; ${skippedInputLines} input lines skipped before tail`\n\t\t\t: \"… rendered output truncated\";\n\treturn [...head, boxLine(theme, theme.fg(\"muted\", skippedText), width), ...tail];\n}\n\nexport function renderBoxedToolCall(\n\ttheme: BoxTheme,\n\ttoolName: string,\n\tdetailLines: string[],\n\toptions: BoxedRenderOptions = {},\n): Component {\n\tlet cache: RenderLinesCache | null = null;\n\treturn {\n\t\tinvalidate() {\n\t\t\tcache = null;\n\t\t},\n\t\trender(width: number): string[] {\n\t\t\tif (cache?.width === width) return cache.lines;\n\t\t\tconst title = formatBoxedToolTitle(\n\t\t\t\ttheme,\n\t\t\t\ttoolName,\n\t\t\t\toptions.isError,\n\t\t\t\toptions.isPending ? (options.running ? \"running\" : \"pending\") : undefined,\n\t\t\t);\n\t\t\tconst headerLabel = options.headerDetail ? `${title} · ${options.headerDetail}` : title;\n\t\t\tconst renderedWidth = boxWidth(width);\n\t\t\tconst lines = [\n\t\t\t\tboxLabeledBorder(theme, BOX_ROUND_TOP_LEFT, BOX_ROUND_TOP_RIGHT, headerLabel, undefined, renderedWidth),\n\t\t\t\tboxBlankLine(theme, renderedWidth),\n\t\t\t\t...detailLines.flatMap((line) => boxedWrappedLines(theme, line, renderedWidth)),\n\t\t\t];\n\t\t\tif (options.isPending && !options.resultSeen) {\n\t\t\t\t// Pending/running card: close the box with the status label. Once a\n\t\t\t\t// result renderer has produced a continuation, the box stays open and\n\t\t\t\t// that continuation closes it.\n\t\t\t\tconst pendingLabel =\n\t\t\t\t\toptions.pendingLabel ?? theme.fg(\"dim\", `… ${options.pendingText ?? \"Waiting for output…\"}`);\n\t\t\t\tlines.push(\n\t\t\t\t\tboxBlankLine(theme, renderedWidth),\n\t\t\t\t\tboxLabeledBorder(\n\t\t\t\t\t\ttheme,\n\t\t\t\t\t\tBOX_ROUND_BOTTOM_LEFT,\n\t\t\t\t\t\tBOX_ROUND_BOTTOM_RIGHT,\n\t\t\t\t\t\tpendingLabel,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t\trenderedWidth,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t// Leave the box open with trailing breathing room; the result renderer\n\t\t\t\t// continues it with the result divider.\n\t\t\t\tlines.push(boxBlankLine(theme, renderedWidth));\n\t\t\t}\n\t\t\tcache = { width, lines };\n\t\t\treturn lines;\n\t\t},\n\t};\n}\n\nconst COMPACT_FOOTER_KEY = \"__piStyleCompactFooter\";\nconst COMPACT_FOOTER_ERROR_KEY = \"__piStyleCompactFooterError\";\nconst COMPACT_FOOTER_PARTIAL_KEY = \"__piStyleCompactFooterPartial\";\n\nexport function clearCompactBoxedFooter(state: Record<string, unknown> | undefined): void {\n\tif (!state || typeof state !== \"object\") return;\n\tdelete state[COMPACT_FOOTER_KEY];\n\tdelete state[COMPACT_FOOTER_ERROR_KEY];\n\tdelete state[COMPACT_FOOTER_PARTIAL_KEY];\n}\n\nexport function renderCompactBoxedToolCall(\n\ttheme: BoxTheme,\n\ttoolName: string,\n\tdetailLine: string,\n\toptions: BoxedRenderOptions = {},\n): Component {\n\treturn {\n\t\tinvalidate() {},\n\t\trender(width: number): string[] {\n\t\t\tconst renderedWidth = boxWidth(width);\n\t\t\tconst title = formatBoxedToolTitle(\n\t\t\t\ttheme,\n\t\t\t\ttoolName,\n\t\t\t\toptions.isError,\n\t\t\t\toptions.isPending ? (options.running ? \"running\" : \"pending\") : undefined,\n\t\t\t);\n\t\t\tconst headerLabel = detailLine ? `${title} · ${detailLine}` : title;\n\t\t\tconst compactFooter =\n\t\t\t\ttypeof options.state?.[COMPACT_FOOTER_KEY] === \"string\" ? options.state[COMPACT_FOOTER_KEY] : \"\";\n\t\t\tconst _footerIsError = Boolean(options.state?.[COMPACT_FOOTER_ERROR_KEY]);\n\t\t\tconst _footerIsPartial = Boolean(options.state?.[COMPACT_FOOTER_PARTIAL_KEY]);\n\t\t\tconst bodyLines = options.bodyLines ? options.bodyLines(boxInnerWidth(renderedWidth)) : [];\n\t\t\tconst lines = [\n\t\t\t\tboxLabeledBorder(theme, BOX_ROUND_TOP_LEFT, BOX_ROUND_TOP_RIGHT, headerLabel, undefined, renderedWidth),\n\t\t\t\t...(bodyLines.length > 0\n\t\t\t\t\t? bodyLines.map((line) => boxLine(theme, line, renderedWidth))\n\t\t\t\t\t: [boxBlankLine(theme, renderedWidth)]),\n\t\t\t];\n\t\t\tif (compactFooter) {\n\t\t\t\tlines.push(\n\t\t\t\t\tboxLabeledBorder(\n\t\t\t\t\t\ttheme,\n\t\t\t\t\t\tBOX_ROUND_BOTTOM_LEFT,\n\t\t\t\t\t\tBOX_ROUND_BOTTOM_RIGHT,\n\t\t\t\t\t\tcompactFooter,\n\t\t\t\t\t\toptions.bottomRightLabel,\n\t\t\t\t\t\trenderedWidth,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else if (options.isPending) {\n\t\t\t\tconst pendingLabel =\n\t\t\t\t\toptions.pendingLabel ??\n\t\t\t\t\t(options.running\n\t\t\t\t\t\t? formatBoxedRunningStatus(theme, undefined)\n\t\t\t\t\t\t: theme.fg(\"dim\", `… ${options.pendingText ?? \"Waiting for output…\"}`));\n\t\t\t\tlines.push(\n\t\t\t\t\tboxLabeledBorder(\n\t\t\t\t\t\ttheme,\n\t\t\t\t\t\tBOX_ROUND_BOTTOM_LEFT,\n\t\t\t\t\t\tBOX_ROUND_BOTTOM_RIGHT,\n\t\t\t\t\t\tpendingLabel,\n\t\t\t\t\t\toptions.bottomRightLabel,\n\t\t\t\t\t\trenderedWidth,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t// No footer yet (transient, or the result opens the result divider):\n\t\t\t\t// leave the box open so the result renderer continues the same box.\n\t\t\t}\n\t\t\treturn lines;\n\t\t},\n\t};\n}\n\ntype BoxedResultBody = Component | ((contentWidth: number) => string[]);\n\nexport function renderBoxedToolResult(\n\ttheme: BoxTheme,\n\tbody: BoxedResultBody,\n\toptions: {\n\t\toutputLabel?: string;\n\t\tfooterLines?: string[];\n\t\temptyText?: string;\n\t\twidthKey?: string;\n\t\treferenceLines?: string[];\n\t\trenderLineBudget?: number;\n\t\t/** Left-side label embedded in the divider between the call and the result. May be a function of the box width (e.g. for width-dependent layout labels). */\n\t\tdividerLabel?: string | ((width: number) => string);\n\t\t/** Right-side label embedded in the divider between the call and the result. */\n\t\tdividerRightLabel?: string;\n\t\t/** Right-side label embedded in the bottom border (e.g. the expand hint). */\n\t\texpandHint?: string;\n\t\tisError?: boolean;\n\t\tisPartial?: boolean;\n\t\t/** Skip the result divider entirely (streaming continuation into an open call box). */\n\t\tshowDivider?: boolean;\n\t\t/** Error state marker prepended to the body (default `✗ Error`). */\n\t\terrorLabel?: string;\n\t} = {},\n): Component {\n\tlet cache: RenderLinesCache | null = null;\n\treturn {\n\t\tinvalidate() {\n\t\t\tcache = null;\n\t\t\tif (typeof body !== \"function\") body.invalidate();\n\t\t},\n\t\trender(width: number): string[] {\n\t\t\tif (cache?.width === width) return cache.lines;\n\t\t\tconst renderedWidth = boxWidth(width);\n\t\t\tconst maxContentWidth = boxInnerWidth(renderedWidth);\n\t\t\tconst bodyLines = typeof body === \"function\" ? body(maxContentWidth) : body.render(maxContentWidth);\n\t\t\tconst errorPrefix = options.isError ? [theme.fg(\"error\", options.errorLabel ?? \"✗ Error\")] : [];\n\t\t\tconst outputLines =\n\t\t\t\tbodyLines.length > 0\n\t\t\t\t\t? [...errorPrefix, ...bodyLines]\n\t\t\t\t\t: [theme.fg(\"muted\", `∅ ${options.emptyText ?? \"(no output)\"}`)];\n\t\t\tconst footerText = (options.footerLines ?? []).join(\" · \");\n\t\t\tconst dividerText =\n\t\t\t\ttypeof options.dividerLabel === \"function\"\n\t\t\t\t\t? options.dividerLabel(renderedWidth)\n\t\t\t\t\t: (options.dividerLabel ?? \"Response\");\n\t\t\tconst rendered = [\n\t\t\t\t...(options.showDivider === false\n\t\t\t\t\t? []\n\t\t\t\t\t: [\n\t\t\t\t\t\t\tboxLabeledBorder(\n\t\t\t\t\t\t\t\ttheme,\n\t\t\t\t\t\t\t\tBOX_DIVIDER_LEFT,\n\t\t\t\t\t\t\t\tBOX_DIVIDER_RIGHT,\n\t\t\t\t\t\t\t\ttheme.fg(\"dim\", dividerText),\n\t\t\t\t\t\t\t\toptions.dividerRightLabel ? theme.fg(\"dim\", options.dividerRightLabel) : undefined,\n\t\t\t\t\t\t\t\trenderedWidth,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t]),\n\t\t\t\tboxBlankLine(theme, renderedWidth),\n\t\t\t\t...renderBoxedOutputLines(theme, outputLines, renderedWidth, options.renderLineBudget ?? outputLines.length),\n\t\t\t\tboxBlankLine(theme, renderedWidth),\n\t\t\t\tboxLabeledBorder(\n\t\t\t\t\ttheme,\n\t\t\t\t\tBOX_ROUND_BOTTOM_LEFT,\n\t\t\t\t\tBOX_ROUND_BOTTOM_RIGHT,\n\t\t\t\t\tfooterText,\n\t\t\t\t\toptions.expandHint ? theme.fg(\"dim\", options.expandHint) : undefined,\n\t\t\t\t\trenderedWidth,\n\t\t\t\t),\n\t\t\t];\n\t\t\tcache = { width, lines: rendered };\n\t\t\treturn rendered;\n\t\t},\n\t};\n}\n\nexport function formatBoxedWallTime(result: MetricResultLike | undefined): string {\n\tconst elapsedMs = getElapsedMs(result);\n\tif (elapsedMs === undefined) return \"--\";\n\treturn `${(elapsedMs / 1000).toFixed(2)}s`;\n}\n\nexport function formatBoxedFooterFromValues(\n\ttheme: BoxTheme,\n\telapsedMs: number | undefined,\n\toutput: string,\n\textraParts: string[] = [],\n): string {\n\tconst wall = elapsedMs === undefined ? \"--\" : `${(elapsedMs / 1000).toFixed(2)}s`;\n\tconst elapsedPart = theme.fg(\"text\", wall);\n\tconst extraPartList = extraParts.filter(Boolean).map((part) => theme.fg(\"dim\", part));\n\tconst wordsPart = theme.fg(\"dim\", formatBoxedWords(output));\n\treturn [elapsedPart, ...extraPartList, wordsPart].join(theme.fg(\"dim\", \" · \"));\n}\n\nfunction formatBoxedFooterParts(\n\ttheme: BoxTheme,\n\tresult: MetricResultLike | undefined,\n\textraParts: string[] = [],\n\telapsedMs?: number,\n): string {\n\treturn formatBoxedFooterFromValues(theme, elapsedMs ?? getElapsedMs(result), getTextOutput(result), extraParts);\n}\n\nexport function formatBoxedFooter(\n\ttheme: BoxTheme,\n\tresult: MetricResultLike | undefined,\n\textraParts: string[] = [],\n\telapsedMs?: number,\n): string {\n\treturn formatBoxedFooterParts(theme, result, extraParts, elapsedMs);\n}\n\nexport function renderCompactBoxedFooter(\n\ttheme: BoxTheme,\n\tresult: MetricResultLike | undefined,\n\toptions: BoxedRenderOptions = {},\n): Component {\n\tif (options.state && typeof options.state === \"object\") {\n\t\toptions.state[COMPACT_FOOTER_KEY] = formatBoxedFooterParts(theme, result, [], options.elapsedMs);\n\t\toptions.state[COMPACT_FOOTER_ERROR_KEY] = Boolean(options.isError);\n\t\toptions.state[COMPACT_FOOTER_PARTIAL_KEY] = Boolean(options.isPartial);\n\t\treturn { invalidate() {}, render: () => [] };\n\t}\n\n\treturn {\n\t\tinvalidate() {},\n\t\trender(width: number): string[] {\n\t\t\tconst renderedWidth = boxWidth(width);\n\t\t\treturn [\n\t\t\t\tboxLabeledBorder(\n\t\t\t\t\ttheme,\n\t\t\t\t\tBOX_ROUND_BOTTOM_LEFT,\n\t\t\t\t\tBOX_ROUND_BOTTOM_RIGHT,\n\t\t\t\t\tformatBoxedFooterParts(theme, result, [], options.elapsedMs),\n\t\t\t\t\tundefined,\n\t\t\t\t\trenderedWidth,\n\t\t\t\t),\n\t\t\t];\n\t\t},\n\t};\n}\n\nconst TOOL_BODY_INDENT = 2;\nconst TOOL_RIGHT_MARGIN = 1;\n\nexport function renderToolCallHeader(\n\ttheme: BoxTheme,\n\tlabel: string,\n\tdetail: string,\n\tskipTextColor?: boolean,\n): Component {\n\treturn renderToolCallHeaderLines(theme, label, [parens(theme, detail, skipTextColor)]);\n}\n\nexport function getToolBodyWidth(width: number, spaces = TOOL_BODY_INDENT): number {\n\treturn Math.max(1, width - spaces - TOOL_RIGHT_MARGIN);\n}\n\nexport function renderToolCallHeaderLines(theme: BoxTheme, label: string, detailLines: string[]): Component {\n\tconst prefix = `${badge(theme, label)} `;\n\tconst indent = \" \".repeat(safeVisibleWidth(prefix));\n\treturn {\n\t\tinvalidate() {},\n\t\trender(width: number): string[] {\n\t\t\tconst bodyWidth = Math.max(1, width - safeVisibleWidth(prefix) - TOOL_RIGHT_MARGIN);\n\t\t\tconst output: string[] = [];\n\t\t\tfor (let i = 0; i < detailLines.length; i++) {\n\t\t\t\tconst wrapped = safeWrapTextWithAnsi(detailLines[i] ?? \"\", bodyWidth);\n\t\t\t\tif (i === 0) {\n\t\t\t\t\toutput.push(`${prefix}${wrapped[0] ?? \"\"}`);\n\t\t\t\t\toutput.push(...wrapped.slice(1).map((line) => `${indent}${line}`));\n\t\t\t\t} else {\n\t\t\t\t\toutput.push(...wrapped.map((line) => `${indent}${line}`));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn output.length > 0 ? output : [prefix.trimEnd()];\n\t\t},\n\t};\n}\n\nexport function indentToolBody(text: string, spaces = TOOL_BODY_INDENT): string {\n\tconst indent = \" \".repeat(spaces);\n\treturn text\n\t\t.split(\"\\n\")\n\t\t.map((line) => (line.length === 0 ? line : `${indent}${line}`))\n\t\t.join(\"\\n\");\n}\n\nexport function indentToolBodyLines(lines: string[], spaces = TOOL_BODY_INDENT): string[] {\n\tconst indent = \" \".repeat(spaces);\n\treturn lines.map((line) => (line.length === 0 ? line : `${indent}${line}`));\n}\n\nexport function formatToolOutputLine(\n\ttheme: BoxTheme,\n\tline: string,\n\tcolor: \"toolOutput\" | \"error\" | \"text\" = \"toolOutput\",\n): string {\n\tif (color === \"error\") return theme.fg(\"error\", line);\n\n\tconst clean = stripAnsi(line);\n\tif (/^##\\s/.test(clean)) return theme.fg(\"muted\", line);\n\tif (/^\\?\\?\\s/.test(clean))\n\t\treturn theme.bold ? theme.bold(theme.fg(\"syntaxVariable\", line)) : theme.fg(\"syntaxVariable\", line);\n\n\treturn theme.fg(color, line);\n}\n\nexport function selectRenderLines(text: string, maxLines: number, tail = false): { lines: string[]; omitted: number } {\n\tconst source = text ?? \"\";\n\tif (!source) return { lines: [], omitted: 0 };\n\tconst limit = Math.max(0, maxLines);\n\tconst selected: string[] = [];\n\tlet lineCount = 0;\n\tlet lineStart = 0;\n\n\tfor (let i = 0; i <= source.length; i++) {\n\t\tif (i < source.length && source[i] !== \"\\n\") continue;\n\t\tconst rawLine = source.slice(lineStart, i).replace(/\\r/g, \"\");\n\t\tlineCount++;\n\t\tif (limit > 0) {\n\t\t\tconst line = clampRenderLine(rawLine);\n\t\t\tif (tail) {\n\t\t\t\tselected.push(line);\n\t\t\t\tif (selected.length > limit) selected.shift();\n\t\t\t} else if (selected.length < limit) {\n\t\t\t\tselected.push(line);\n\t\t\t}\n\t\t}\n\t\tlineStart = i + 1;\n\t}\n\n\tif (selected.length === 1 && selected[0] === \"\") return { lines: [], omitted: 0 };\n\treturn { lines: selected, omitted: Math.max(0, lineCount - selected.length) };\n}\n\nexport function renderLines(\n\ttheme: BoxTheme,\n\ttext: string,\n\toptions: { expanded?: boolean },\n\tcfg: { maxLines: number; tail?: boolean; color?: \"toolOutput\" | \"error\"; width?: number } = { maxLines: 10 },\n): string {\n\tconst color = cfg.color ?? \"toolOutput\";\n\tconst { lines, omitted } = selectRenderLines(text, cfg.maxLines, cfg.tail);\n\tconst renderWidth = cfg.width ? getToolBodyWidth(cfg.width) : undefined;\n\tconst renderLine = (line: string) => {\n\t\tconst rendered = renderWidth ? safeTruncateToWidth(line, renderWidth, \"…\") : line;\n\t\treturn formatToolOutputLine(theme, rendered, color);\n\t};\n\n\tif (lines.length === 0) return \"\";\n\n\tlet output = lines.map(renderLine).join(\"\\n\");\n\tif (omitted <= 0) return output;\n\n\tconst hintText = isExpanded(options)\n\t\t? `... ${omitted} more lines omitted by render budget`\n\t\t: `... ${omitted} more lines, press Ctrl+o to expand`;\n\tconst hint = cfg.width ? safeTruncateToWidth(hintText, Math.max(1, cfg.width - 1), \"…\") : hintText;\n\toutput += theme.fg(\"muted\", `\\n\\n${hint}`);\n\n\treturn output;\n}\n\nexport function dimWithElapsed(theme: BoxTheme, summary: string, result: MetricResultLike | undefined): string {\n\tconst metrics = formatToolMetrics(result);\n\treturn metrics\n\t\t? `${theme.fg(\"dim\", summary)} ${theme.fg(\"dim\", \"–\")} ${theme.italic ? theme.italic(theme.fg(\"muted\", metrics)) : theme.fg(\"muted\", metrics)}`\n\t\t: theme.fg(\"dim\", summary);\n}\n\nexport function renderToolMetricsFooter(theme: BoxTheme, _width: number, metrics: string): string[] {\n\treturn metrics\n\t\t? [theme.italic ? theme.italic(theme.fg(\"muted\", `↳ ${metrics}`)) : theme.fg(\"muted\", `↳ ${metrics}`)]\n\t\t: [];\n}\n\nexport type { MetricResultLike };\n// Re-exported metric helpers so renderers import from a single box module.\nexport { getElapsedMs };\n","// Tool metrics: elapsed wall time + output size formatting and annotation.\n\nconst ELAPSED_KEY = \"__elapsedMs\";\nconst OUTPUT_CHARS_KEY = \"__outputChars\";\n\nexport interface MetricResultLike {\n\treadonly content?: readonly unknown[];\n\treadonly details?: unknown;\n}\n\nfunction getTextOutputLength(result: MetricResultLike): number {\n\tif (!Array.isArray(result.content)) return 0;\n\tlet length = 0;\n\tlet seenText = false;\n\tfor (const contentBlock of result.content) {\n\t\tif (!contentBlock || typeof contentBlock !== \"object\") continue;\n\t\tconst block = contentBlock as { type?: unknown; text?: unknown };\n\t\tif (block.type !== \"text\") continue;\n\t\tif (seenText) length += 1; // matches getTextOutput() joining text blocks with newlines\n\t\tlength += String(block.text ?? \"\").replace(/\\r/g, \"\").length;\n\t\tseenText = true;\n\t}\n\treturn length;\n}\n\nfunction formatCompactCount(value: number): string {\n\tif (value < 1000) return `${Math.round(value)}`;\n\tif (value < 10000) return `${(value / 1000).toFixed(1)}k`;\n\tif (value < 1000000) return `${Math.round(value / 1000)}k`;\n\tif (value < 10000000) return `${(value / 1000000).toFixed(1)}M`;\n\treturn `${Math.round(value / 1000000)}M`;\n}\n\nexport function formatElapsedMs(ms: number | undefined): string {\n\tif (typeof ms !== \"number\" || !Number.isFinite(ms)) return \"\";\n\tif (ms < 1000) return `${Math.round(ms)}ms`;\n\tconst s = ms / 1000;\n\treturn s < 10 ? `${s.toFixed(1)}s` : `${Math.round(s)}s`;\n}\n\nexport function formatOutputChars(chars: number | undefined): string {\n\tif (typeof chars !== \"number\" || !Number.isFinite(chars) || chars <= 0) return \"\";\n\treturn `${formatCompactCount(chars)} ${chars === 1 ? \"char\" : \"chars\"}`;\n}\n\nexport function formatToolMetricsFromValues(elapsedMs: number | undefined, outputChars: number | undefined): string {\n\treturn [formatElapsedMs(elapsedMs), formatOutputChars(outputChars)].filter(Boolean).join(\" · \");\n}\n\nexport function getElapsedMs(result: MetricResultLike | undefined): number | undefined {\n\tif (!result || typeof result.details !== \"object\" || result.details === null) return undefined;\n\tconst elapsed = (result.details as Record<string, unknown>)[ELAPSED_KEY];\n\treturn typeof elapsed === \"number\" && Number.isFinite(elapsed) ? elapsed : undefined;\n}\n\nexport function formatElapsed(result: MetricResultLike | undefined): string {\n\treturn formatElapsedMs(getElapsedMs(result));\n}\n\nexport function formatOutputSize(result: MetricResultLike | undefined): string {\n\treturn formatOutputChars(\n\t\t(result?.details as Record<string, unknown> | undefined)?.[OUTPUT_CHARS_KEY] as number | undefined,\n\t);\n}\n\nexport function formatToolMetrics(result: MetricResultLike | undefined): string {\n\treturn [formatElapsed(result), formatOutputSize(result)].filter(Boolean).join(\" · \");\n}\n\n/** Annotate elapsed/output metrics into a result's details (only when absent). */\nexport function annotateToolResultMetrics(result: MetricResultLike | undefined, elapsedMs?: number): void {\n\tif (!result || typeof result !== \"object\") return;\n\tif (!result.details || typeof result.details !== \"object\") {\n\t\t(result as { details?: unknown }).details = {};\n\t}\n\tconst details = result.details as Record<string, unknown>;\n\tconst existingElapsed = details[ELAPSED_KEY];\n\tif (\n\t\ttypeof elapsedMs === \"number\" &&\n\t\tNumber.isFinite(elapsedMs) &&\n\t\t(typeof existingElapsed !== \"number\" || !Number.isFinite(existingElapsed))\n\t) {\n\t\tdetails[ELAPSED_KEY] = elapsedMs;\n\t}\n\tif (typeof details[OUTPUT_CHARS_KEY] !== \"number\" || !Number.isFinite(details[OUTPUT_CHARS_KEY])) {\n\t\tdetails[OUTPUT_CHARS_KEY] = getTextOutputLength(result);\n\t}\n}\n","// Render budget + ANSI-safe width/truncation/wrapping helpers for boxed tool\n// presentation.\n\nimport {\n\ttruncateToWidth as tuiTruncateToWidth,\n\tvisibleWidth as tuiVisibleWidth,\n\twrapTextWithAnsi,\n} from \"@earendil-works/pi-tui\";\n\nexport const MAX_RENDER_LINE_CHARS = 2000;\nexport const DEFAULT_COLLAPSED_RENDER_LINES = 10;\nexport const MAX_BOXED_RESULT_RENDERED_HEAD_LINES = 40;\nexport const MAX_BOXED_RESULT_RENDERED_TAIL_LINES = 8;\nexport const MAX_BOXED_RESULT_RENDERED_LINES = 160;\n\nconst RENDER_TRUNCATION_SUFFIX = \"… (truncated)\";\nconst TRUNCATE_ELLIPSIS = \"…\";\nconst ANSI_RESET = \"\\x1b[0m\";\nconst ESC = \"\\x1b\";\nconst SGR_PREFIX_PATTERN = new RegExp(`^(?:${ESC}\\\\[[0-9;]*m)+`);\nconst SGR_SUFFIX_PATTERN = new RegExp(`(?:${ESC}\\\\[[0-9;]*m)+$`);\n\ntype SimpleSgrWrappedText = {\n\tprefix: string;\n\tbody: string;\n\tsuffix: string;\n\tkind: \"sgrAscii\" | \"sgrSimple\";\n};\n\ntype FastTextKind = \"ascii\" | \"sgrAscii\" | \"simple\" | \"sgrSimple\";\n\ntype FastTextWidth = {\n\tvisibleWidth: number;\n\tkind: FastTextKind;\n};\n\ntype FastTruncateResult = {\n\ttext: string;\n\tvisibleWidth: number;\n\tkind: FastTextKind;\n};\n\nexport type FastBoxLineContent = {\n\ttext: string;\n\tvisibleWidth: number;\n\tkind: FastTextKind;\n};\n\nexport type BoxedResultRenderBudget = {\n\theadLines: number;\n\ttailLines: number;\n\tmaxRenderedLines: number;\n};\n\n/**\n * Cut a string to a maximum UTF-16 length without splitting a surrogate pair\n * (emoji / supplementary-plane characters). A plain `slice` on a non-ASCII\n * boundary produces a lone surrogate that renders as the U+FFFD replacement\n * character (�).\n */\nexport function truncateAtCodePointBoundary(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\tconst code = text.charCodeAt(maxChars);\n\tconst end = code >= 0xdc00 && code <= 0xdfff ? maxChars - 1 : maxChars;\n\treturn text.slice(0, end);\n}\n\nexport function clampRenderLine(line: string, maxChars = MAX_RENDER_LINE_CHARS): string {\n\tif (line.length <= maxChars) return line;\n\treturn truncateAtCodePointBoundary(line, maxChars) + RENDER_TRUNCATION_SUFFIX;\n}\n\nfunction isPrintableAsciiCode(code: number): boolean {\n\treturn code >= 0x20 && code <= 0x7e;\n}\n\nfunction isSimpleWidthOneGlyphCode(code: number): boolean {\n\tif (code >= 0x2500 && code <= 0x257f) return true; // box drawing\n\tif (code >= 0x2580 && code <= 0x259f) return true; // block elements\n\tif (code >= 0x25a0 && code <= 0x25ff) return true; // geometric shapes used by UI status marks\n\tif (code >= 0x2800 && code <= 0x28ff) return true; // braille loader frames\n\treturn (\n\t\tcode === 0x00b2 || // ²\n\t\tcode === 0x00b7 || // ·\n\t\tcode === 0x03c0 || // π\n\t\tcode === 0x2013 || // –\n\t\tcode === 0x2014 || // —\n\t\tcode === 0x2022 || // •\n\t\tcode === 0x2026 || // …\n\t\tcode === 0x2191 || // ↑\n\t\tcode === 0x2192 || // →\n\t\tcode === 0x2193 || // ↓\n\t\tcode === 0x21b3 || // ↳\n\t\tcode === 0x2205 || // ∅\n\t\tcode === 0x2248 || // ≈\n\t\tcode === 0x22ef || // ⋯\n\t\tcode === 0x2387 || // ⎇\n\t\tcode === 0x23f9 || // ⏹\n\t\tcode === 0x270e || // ✎\n\t\tcode === 0x2713 || // ✓\n\t\tcode === 0x2717 || // ✗\n\t\tcode === 0x276f || // ❯\n\t\tcode === 0x2794 // ➔\n\t);\n}\n\nfunction isSimpleWidthOneCode(code: number): boolean {\n\treturn isPrintableAsciiCode(code) || isSimpleWidthOneGlyphCode(code);\n}\n\nfunction breakLongAsciiWord(word: string, width: number): string[] {\n\tconst lines: string[] = [];\n\tfor (let i = 0; i < word.length; i += width) {\n\t\tlines.push(word.slice(i, i + width));\n\t}\n\treturn lines.length > 0 ? lines : [\"\"];\n}\n\nfunction wrapPrintableAsciiLine(line: string, width: number): string[] {\n\tif (!line) return [\"\"];\n\tif (line.length <= width) return [line];\n\n\tconst wrapped: string[] = [];\n\tlet currentLine = \"\";\n\tlet currentVisibleLength = 0;\n\tlet tokenStart = 0;\n\n\twhile (tokenStart < line.length) {\n\t\tconst tokenIsSpace = line[tokenStart] === \" \";\n\t\tlet tokenEnd = tokenStart + 1;\n\t\twhile (tokenEnd < line.length && (line[tokenEnd] === \" \") === tokenIsSpace) tokenEnd++;\n\n\t\tconst token = line.slice(tokenStart, tokenEnd);\n\t\tconst tokenVisibleLength = token.length;\n\t\tif (tokenVisibleLength > width && !tokenIsSpace) {\n\t\t\tif (currentLine) {\n\t\t\t\twrapped.push(currentLine.trimEnd());\n\t\t\t\tcurrentLine = \"\";\n\t\t\t\tcurrentVisibleLength = 0;\n\t\t\t}\n\t\t\tconst broken = breakLongAsciiWord(token, width);\n\t\t\twrapped.push(...broken.slice(0, -1));\n\t\t\tcurrentLine = broken[broken.length - 1] ?? \"\";\n\t\t\tcurrentVisibleLength = currentLine.length;\n\t\t\ttokenStart = tokenEnd;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst totalNeeded = currentVisibleLength + tokenVisibleLength;\n\t\tif (totalNeeded > width && currentVisibleLength > 0) {\n\t\t\twrapped.push(currentLine.trimEnd());\n\t\t\tif (tokenIsSpace) {\n\t\t\t\tcurrentLine = \"\";\n\t\t\t\tcurrentVisibleLength = 0;\n\t\t\t} else {\n\t\t\t\tcurrentLine = token;\n\t\t\t\tcurrentVisibleLength = tokenVisibleLength;\n\t\t\t}\n\t\t} else {\n\t\t\tcurrentLine += token;\n\t\t\tcurrentVisibleLength += tokenVisibleLength;\n\t\t}\n\n\t\ttokenStart = tokenEnd;\n\t}\n\n\tif (currentLine) wrapped.push(currentLine);\n\treturn wrapped.length > 0 ? wrapped.map((wrappedLine) => wrappedLine.trimEnd()) : [\"\"];\n}\n\nfunction matchSimpleSgrWrappedText(text: string): SimpleSgrWrappedText | null {\n\tconst prefixMatch = SGR_PREFIX_PATTERN.exec(text);\n\tconst suffixMatch = SGR_SUFFIX_PATTERN.exec(text);\n\tif (!prefixMatch || !suffixMatch) return null;\n\tconst prefix = prefixMatch[0];\n\tconst suffix = suffixMatch[0];\n\tconst bodyStart = prefix.length;\n\tconst bodyEnd = suffixMatch.index;\n\tif (bodyEnd < bodyStart) return null;\n\n\tconst body = text.slice(bodyStart, bodyEnd);\n\tconst bodyWidth = knownVisibleWidth(body);\n\tif (!bodyWidth || bodyWidth.kind === \"sgrAscii\" || bodyWidth.kind === \"sgrSimple\") return null;\n\treturn { prefix, body, suffix, kind: bodyWidth.kind === \"ascii\" ? \"sgrAscii\" : \"sgrSimple\" };\n}\n\nfunction wrapSimpleSgrWrappedText(\n\ttext: string,\n\twidth: number,\n): { lines: string[]; kind: \"sgrAscii\" | \"sgrSimple\" } | null {\n\tconst match = matchSimpleSgrWrappedText(text);\n\tif (!match) return null;\n\treturn {\n\t\tlines: wrapPrintableAsciiLine(match.body, width).map((line) => `${match.prefix}${line}${match.suffix}`),\n\t\tkind: match.kind,\n\t};\n}\n\nfunction readSgrSequenceEnd(text: string, offset: number): number {\n\tif (text.charCodeAt(offset) !== 0x1b || text[offset + 1] !== \"[\") return -1;\n\tlet cursor = offset + 2;\n\twhile (cursor < text.length) {\n\t\tconst code = text.charCodeAt(cursor);\n\t\tif (code === 0x6d) return cursor + 1; // m\n\t\tif (code !== 0x3b && (code < 0x30 || code > 0x39)) return -1; // ; or 0-9\n\t\tcursor++;\n\t}\n\treturn -1;\n}\n\nfunction knownVisibleWidth(text: string): FastTextWidth | null {\n\tlet width = 0;\n\tlet sawSgr = false;\n\tlet sawSimpleGlyph = false;\n\tfor (let i = 0; i < text.length; ) {\n\t\tconst sgrEnd = readSgrSequenceEnd(text, i);\n\t\tif (sgrEnd > i) {\n\t\t\tsawSgr = true;\n\t\t\ti = sgrEnd;\n\t\t\tcontinue;\n\t\t}\n\t\tconst code = text.charCodeAt(i);\n\t\tif (!isSimpleWidthOneCode(code)) return null;\n\t\tif (!isPrintableAsciiCode(code)) sawSimpleGlyph = true;\n\t\twidth++;\n\t\ti++;\n\t}\n\tif (sawSgr) return { visibleWidth: width, kind: sawSimpleGlyph ? \"sgrSimple\" : \"sgrAscii\" };\n\treturn { visibleWidth: width, kind: sawSimpleGlyph ? \"simple\" : \"ascii\" };\n}\n\nfunction knownEllipsisWidth(text: string): number | null {\n\tif (text === TRUNCATE_ELLIPSIS) return 1;\n\treturn knownVisibleWidth(text)?.visibleWidth ?? null;\n}\n\nfunction truncatePrintableAscii(\n\ttext: string,\n\twidth: number,\n\tellipsis = TRUNCATE_ELLIPSIS,\n): { text: string; visibleWidth: number } {\n\tif (width <= 0) return { text: \"\", visibleWidth: 0 };\n\tif (text.length <= width) return { text, visibleWidth: text.length };\n\tconst ellipsisWidth = knownEllipsisWidth(ellipsis);\n\tif (ellipsisWidth === null) return { text: text.slice(0, width), visibleWidth: width };\n\tif (ellipsisWidth >= width) {\n\t\tif (ellipsis === TRUNCATE_ELLIPSIS) return { text: TRUNCATE_ELLIPSIS, visibleWidth: 1 };\n\t\treturn { text: ellipsis.slice(0, width), visibleWidth: Math.min(width, ellipsis.length) };\n\t}\n\tconst targetWidth = Math.max(0, width - ellipsisWidth);\n\treturn { text: `${text.slice(0, targetWidth)}${ellipsis}`, visibleWidth: targetWidth + ellipsisWidth };\n}\n\nfunction truncateSgrAscii(\n\ttext: string,\n\twidth: number,\n\tellipsis: string,\n\tvisibleWidth: number,\n): { text: string; visibleWidth: number } | null {\n\tif (visibleWidth <= width) return { text, visibleWidth };\n\tconst ellipsisWidth = knownEllipsisWidth(ellipsis);\n\tif (ellipsisWidth === null) return null;\n\tif (ellipsisWidth >= width) return truncatePrintableAscii(ellipsis, width, \"\");\n\n\tconst targetWidth = Math.max(0, width - ellipsisWidth);\n\tlet keptWidth = 0;\n\tlet output = \"\";\n\tfor (let i = 0; i < text.length && keptWidth < targetWidth; ) {\n\t\tconst sgrEnd = readSgrSequenceEnd(text, i);\n\t\tif (sgrEnd > i) {\n\t\t\toutput += text.slice(i, sgrEnd);\n\t\t\ti = sgrEnd;\n\t\t\tcontinue;\n\t\t}\n\t\tconst code = text.charCodeAt(i);\n\t\tif (!isSimpleWidthOneCode(code)) return null;\n\t\toutput += text[i] ?? \"\";\n\t\tkeptWidth++;\n\t\ti++;\n\t}\n\treturn { text: `${output}${ANSI_RESET}${ellipsis}${ANSI_RESET}`, visibleWidth: keptWidth + ellipsisWidth };\n}\n\nfunction fastTruncateText(text: string, width: number, ellipsis = TRUNCATE_ELLIPSIS): FastTruncateResult | null {\n\tconst knownWidth = knownVisibleWidth(text);\n\tif (!knownWidth) return null;\n\tif (knownWidth.kind === \"ascii\" || knownWidth.kind === \"simple\")\n\t\treturn { ...truncatePrintableAscii(text, width, ellipsis), kind: knownWidth.kind };\n\n\tconst simple = matchSimpleSgrWrappedText(text);\n\tif (simple) {\n\t\tconst truncated = truncatePrintableAscii(simple.body, width, ellipsis);\n\t\treturn {\n\t\t\ttext: `${simple.prefix}${truncated.text}${simple.suffix}`,\n\t\t\tvisibleWidth: truncated.visibleWidth,\n\t\t\tkind: simple.kind,\n\t\t};\n\t}\n\n\tconst truncated = truncateSgrAscii(text, width, ellipsis, knownWidth.visibleWidth);\n\treturn truncated ? { ...truncated, kind: knownWidth.kind } : null;\n}\n\nexport function safeVisibleWidth(text: string): number {\n\tconst fastWidth = knownVisibleWidth(text);\n\tif (fastWidth) return fastWidth.visibleWidth;\n\tif (text === TRUNCATE_ELLIPSIS) return 1;\n\treturn tuiVisibleWidth(text);\n}\n\nexport function safeTruncateToWidth(text: string, maxWidth: number, ellipsis = \"...\", pad = false): string {\n\tconst width = Math.floor(maxWidth);\n\tif (!Number.isFinite(width) || width <= 0) return \"\";\n\tif (text.length === 0) return pad ? \" \".repeat(width) : \"\";\n\n\tconst truncated = fastTruncateText(text, width, ellipsis);\n\tif (truncated)\n\t\treturn pad ? `${truncated.text}${\" \".repeat(Math.max(0, width - truncated.visibleWidth))}` : truncated.text;\n\n\treturn tuiTruncateToWidth(text, maxWidth, ellipsis, pad);\n}\n\nexport function fastBoxLineContent(content: string, width: number): FastBoxLineContent | null {\n\tconst contentWidth = Math.floor(width);\n\tif (!Number.isFinite(contentWidth) || contentWidth <= 0) return null;\n\n\treturn fastTruncateText(content, contentWidth);\n}\n\nexport function safeWrapTextWithAnsi(text: string, width: number, maxChars = MAX_RENDER_LINE_CHARS): string[] {\n\tconst clamped = clampRenderLine(text, maxChars);\n\tconst wrapWidth = Math.floor(width);\n\tif (!Number.isFinite(wrapWidth) || wrapWidth <= 0) {\n\t\treturn wrapTextWithAnsi(clamped, width);\n\t}\n\tconst clampedWidth = knownVisibleWidth(clamped);\n\tif (clampedWidth?.kind === \"ascii\" || clampedWidth?.kind === \"simple\") {\n\t\treturn wrapPrintableAsciiLine(clamped, wrapWidth);\n\t}\n\tconst simpleSgrWrapped = wrapSimpleSgrWrappedText(clamped, wrapWidth);\n\tif (simpleSgrWrapped) {\n\t\treturn simpleSgrWrapped.lines;\n\t}\n\treturn wrapTextWithAnsi(clamped, width);\n}\n\nexport function boxedResultRenderBudget(\n\trawLineBudget: number = DEFAULT_COLLAPSED_RENDER_LINES,\n): BoxedResultRenderBudget {\n\tconst rawLines = Math.max(\n\t\t0,\n\t\tMath.floor(Number.isFinite(rawLineBudget) ? rawLineBudget : DEFAULT_COLLAPSED_RENDER_LINES),\n\t);\n\tconst maxRenderedLines = Math.max(1, Math.min(rawLines * 3, MAX_BOXED_RESULT_RENDERED_LINES));\n\tconst tailLines = Math.min(\n\t\tMath.ceil(rawLines * 0.15),\n\t\tMAX_BOXED_RESULT_RENDERED_TAIL_LINES,\n\t\tMath.max(0, maxRenderedLines - 1),\n\t);\n\tconst headLines = Math.min(\n\t\trawLines,\n\t\tMAX_BOXED_RESULT_RENDERED_HEAD_LINES,\n\t\tMath.max(1, maxRenderedLines - tailLines - 1),\n\t);\n\n\treturn { headLines, tailLines, maxRenderedLines };\n}\n","// Theme extras reader.\n//\n// Reads extension-specific \"extras\" plus raw theme vars/export values from the\n// active theme's JSON file on disk. Pi does not expose all of these raw values\n// through the theme object, so we locate and parse the file directly.\n//\n// pi-style constraint: no filesystem I/O inside render. The cache is populated\n// by `syncThemeExtras(theme, force)` at session start and on theme change; the\n// render-facing `getThemeExtra`/`getThemePageBackground`/`getThemeVarBackground`\n// read cached values only and return \"\" (graceful fallback) when unavailable.\n\nimport { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { isHexColor } from \"../shared/ansi.js\";\n\nconst extensionDir = dirname(fileURLToPath(import.meta.url));\n\nexport const THEME_EXTRA_DEFAULTS: Readonly<Record<string, string>> = Object.freeze({\n\tassistantPrefix: \"•\",\n\tassistantPrefixColor: \"\",\n\tdividerChar: \"─\",\n\tdividerColor: \"\",\n\tshowDivider: \"true\",\n\tquoteStyle: \"false\",\n\tquoteChar: \"┆\",\n\tquoteColor: \"\",\n\tinputBorderColor: \"\",\n\tbashPromptColor: \"\",\n\ttagBgColor: \"\",\n\tparensTextColor: \"\",\n\tparensBracketColor: \"\",\n\tslashSelectedColor: \"\",\n\tslashCommandColor: \"\",\n\tslashDescriptionColor: \"\",\n\tslashHintColor: \"\",\n\tuserBoxBorderColor: \"\",\n\tgitInsertionColor: \"#2ea043\",\n\tgitDeletionColor: \"#f85149\",\n});\n\nlet cachedExtras: Record<string, string | boolean> | null = null;\nlet cachedVars: Record<string, string> | null = null;\nlet cachedColors: Record<string, string> | null = null;\nlet cachedThemeExport: Record<string, string> | null = null;\nlet cachedThemeName: string | null = null;\n\ntype ThemeDiscovery = {\n\textras: Record<string, string | boolean> | null;\n\tvars: Record<string, string> | null;\n\tcolors: Record<string, string> | null;\n\tthemeExport: Record<string, string> | null;\n};\n\nfunction themeDiscoveryFromContent(content: unknown): ThemeDiscovery | null {\n\tif (!content || typeof content !== \"object\") return null;\n\tconst record = content as Record<string, unknown>;\n\tconst extras =\n\t\trecord.extras && typeof record.extras === \"object\" ? (record.extras as Record<string, string | boolean>) : null;\n\tconst vars = record.vars && typeof record.vars === \"object\" ? (record.vars as Record<string, string>) : null;\n\tconst colors = record.colors && typeof record.colors === \"object\" ? (record.colors as Record<string, string>) : null;\n\tconst themeExport =\n\t\trecord.export && typeof record.export === \"object\" ? (record.export as Record<string, string>) : null;\n\treturn extras || vars || colors || themeExport ? { extras, vars, colors, themeExport } : null;\n}\n\nfunction readThemeDiscoveryFromPath(filePath: string): ThemeDiscovery | null {\n\ttry {\n\t\tif (!filePath || !existsSync(filePath)) return null;\n\t\tconst content = JSON.parse(readFileSync(filePath, \"utf-8\")) as unknown;\n\t\treturn themeDiscoveryFromContent(content);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction resolveThemeSourcePath(theme: unknown): string {\n\tif (!theme || typeof theme !== \"object\") return \"\";\n\tconst record = theme as Record<string, unknown>;\n\tif (typeof record.sourcePath === \"string\") return record.sourcePath;\n\tconst definition =\n\t\trecord.definition && typeof record.definition === \"object\"\n\t\t\t? (record.definition as Record<string, unknown>)\n\t\t\t: undefined;\n\treturn typeof definition?.sourcePath === \"string\" ? definition.sourcePath : \"\";\n}\n\nfunction addThemeDir(searchDirs: Set<string>, dir: string): void {\n\tif (existsSync(dir)) searchDirs.add(dir);\n}\n\nfunction addBundledThemeDirs(searchDirs: Set<string>): void {\n\tfor (const root of [extensionDir, process.cwd()]) {\n\t\tfor (const scope of [\"@earendil-works\", \"@mariozechner\"]) {\n\t\t\taddThemeDir(\n\t\t\t\tsearchDirs,\n\t\t\t\tresolve(root, \"node_modules\", scope, \"pi-coding-agent\", \"dist\", \"modes\", \"interactive\", \"theme\"),\n\t\t\t);\n\t\t\taddThemeDir(searchDirs, resolve(root, \"node_modules\", scope, \"pi-coding-agent\", \"dist\", \"theme\"));\n\t\t}\n\t}\n}\n\nfunction collectThemeDirs(root: string, searchDirs: Set<string>, maxDepth = 4): void {\n\tif (maxDepth < 0 || !existsSync(root)) return;\n\ttry {\n\t\tfor (const entry of readdirSync(root, { withFileTypes: true })) {\n\t\t\tif (!entry.isDirectory() || entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n\t\t\tconst dir = join(root, entry.name);\n\t\t\tif (entry.name === \"themes\") {\n\t\t\t\tsearchDirs.add(dir);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcollectThemeDirs(dir, searchDirs, maxDepth - 1);\n\t\t}\n\t} catch {\n\t\t// best effort discovery only\n\t}\n}\n\nfunction readSettingsPackagePaths(settingsPath: string): string[] {\n\tif (!existsSync(settingsPath)) return [];\n\ttry {\n\t\tconst settings = JSON.parse(readFileSync(settingsPath, \"utf-8\")) as Record<string, unknown>;\n\t\tconst entries = [\n\t\t\t...(Array.isArray(settings.packages) ? settings.packages : []),\n\t\t\t...(Array.isArray(settings.extensions) ? settings.extensions : []),\n\t\t];\n\t\treturn entries\n\t\t\t.map((entry) =>\n\t\t\t\ttypeof entry === \"string\"\n\t\t\t\t\t? entry\n\t\t\t\t\t: entry && typeof entry === \"object\"\n\t\t\t\t\t\t? String((entry as Record<string, unknown>).source ?? \"\")\n\t\t\t\t\t\t: \"\",\n\t\t\t)\n\t\t\t.filter((entry) => entry && !entry.startsWith(\"npm:\") && !entry.startsWith(\"git:\"));\n\t} catch {\n\t\treturn [];\n\t}\n}\n\n/** Scan known theme directories for a JSON file whose \"name\" matches themeName. */\nfunction discoverThemeExtras(themeName: string): ThemeDiscovery | null {\n\tconst searchDirs = new Set<string>();\n\n\taddThemeDir(searchDirs, join(homedir(), \".pi\", \"agent\", \"themes\"));\n\taddThemeDir(searchDirs, resolve(process.cwd(), \".pi\", \"themes\"));\n\taddBundledThemeDirs(searchDirs);\n\tcollectThemeDirs(join(homedir(), \".pi\", \"agent\", \"git\"), searchDirs);\n\tcollectThemeDirs(resolve(process.cwd(), \".pi\", \"git\"), searchDirs);\n\n\tconst localPackagePaths = [\n\t\t...readSettingsPackagePaths(join(homedir(), \".pi\", \"agent\", \"settings.json\")),\n\t\t...readSettingsPackagePaths(resolve(process.cwd(), \".pi\", \"settings.json\")),\n\t];\n\tfor (const packagePath of localPackagePaths) {\n\t\taddThemeDir(searchDirs, resolve(process.cwd(), packagePath, \"themes\"));\n\t}\n\n\tfor (const dir of searchDirs) {\n\t\ttry {\n\t\t\tfor (const file of readdirSync(dir)) {\n\t\t\t\tif (!file.endsWith(\".json\")) continue;\n\t\t\t\tconst filePath = join(dir, file);\n\t\t\t\ttry {\n\t\t\t\t\tconst content = JSON.parse(readFileSync(filePath, \"utf-8\")) as Record<string, unknown>;\n\t\t\t\t\tif (content?.name === themeName) {\n\t\t\t\t\t\tconst result = themeDiscoveryFromContent(content);\n\t\t\t\t\t\tif (result) return result;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// skip unparsable theme files\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// skip unreadable directories\n\t\t}\n\t}\n\n\treturn null;\n}\n\nfunction resolveThemeName(theme: unknown): string | null {\n\tif (!theme || typeof theme !== \"object\") return null;\n\tconst record = theme as Record<string, unknown>;\n\tconst definition =\n\t\trecord.definition && typeof record.definition === \"object\"\n\t\t\t? (record.definition as Record<string, unknown>)\n\t\t\t: undefined;\n\tif (typeof definition?.name === \"string\") return definition.name;\n\tif (typeof record.name === \"string\") return record.name;\n\ttry {\n\t\tconst settingsPath = join(homedir(), \".pi\", \"agent\", \"settings.json\");\n\t\tif (existsSync(settingsPath)) {\n\t\t\tconst settings = JSON.parse(readFileSync(settingsPath, \"utf-8\")) as Record<string, unknown>;\n\t\t\tif (typeof settings.theme === \"string\") return settings.theme;\n\t\t}\n\t} catch {\n\t\t// fall through\n\t}\n\treturn null;\n}\n\nfunction readThemeToken(name: string): string {\n\tconst varValue = cachedVars && typeof cachedVars[name] === \"string\" ? cachedVars[name] : \"\";\n\tif (varValue) return varValue;\n\treturn cachedColors && typeof cachedColors[name] === \"string\" ? cachedColors[name] : \"\";\n}\n\nfunction resolveThemeColorToken(value: string): string {\n\tlet resolved = value;\n\tconst seen = new Set<string>();\n\tfor (let depth = 0; depth < 8; depth++) {\n\t\tif (!resolved) return \"\";\n\t\tif (isHexColor(resolved)) return resolved;\n\t\tif (seen.has(resolved)) return \"\";\n\t\tseen.add(resolved);\n\n\t\tconst next = readThemeToken(resolved);\n\t\tif (!next) return \"\";\n\t\tresolved = next;\n\t}\n\treturn \"\";\n}\n\nfunction resolveThemeExtraValue(key: string, value: string): string {\n\tif (!key.endsWith(\"Color\")) return value;\n\treturn resolveThemeColorToken(value) || value;\n}\n\nfunction resolveThemeExportColor(key: string): string {\n\tif (!cachedThemeExport) return \"\";\n\tconst value = cachedThemeExport[key];\n\tif (typeof value !== \"string\" || !value) return \"\";\n\tconst resolved = cachedVars && typeof cachedVars[value] === \"string\" ? cachedVars[value] : value;\n\treturn isHexColor(resolved) ? resolved : \"\";\n}\n\n/** Populate the extras cache from a theme (session start / theme change only). */\nexport function setFullTheme(theme: unknown, force = false): void {\n\tconst themeName = resolveThemeName(theme);\n\tconst sourcePath = resolveThemeSourcePath(theme);\n\tif (!themeName && !sourcePath) return;\n\n\tconst cacheKey = sourcePath || themeName;\n\tif (\n\t\t!force &&\n\t\tcacheKey === cachedThemeName &&\n\t\t(cachedExtras !== null || cachedVars !== null || cachedColors !== null || cachedThemeExport !== null)\n\t)\n\t\treturn;\n\n\tcachedThemeName = cacheKey;\n\tconst result = readThemeDiscoveryFromPath(sourcePath) ?? (themeName ? discoverThemeExtras(themeName) : null);\n\tcachedExtras = result?.extras ?? null;\n\tcachedVars = result?.vars ?? null;\n\tcachedColors = result?.colors ?? null;\n\tcachedThemeExport = result?.themeExport ?? null;\n}\n\nexport function resetThemeExtrasCache(): void {\n\tcachedExtras = null;\n\tcachedVars = null;\n\tcachedColors = null;\n\tcachedThemeExport = null;\n\tcachedThemeName = null;\n}\n\n/** Resolve a theme-extra key from the cache; \"\" when unavailable (graceful fallback). */\nexport function getThemeExtra(_theme: unknown, key: string): string {\n\tconst extraValue = cachedExtras?.[key];\n\tif (typeof extraValue === \"string\" || typeof extraValue === \"boolean\") {\n\t\treturn resolveThemeExtraValue(key, String(extraValue));\n\t}\n\treturn resolveThemeExtraValue(key, THEME_EXTRA_DEFAULTS[key] ?? \"\");\n}\n\nexport function getThemePageBackground(_theme: unknown): string {\n\tconst directBg = cachedVars && typeof cachedVars.bg === \"string\" ? cachedVars.bg : \"\";\n\tif (isHexColor(directBg)) return directBg;\n\treturn resolveThemeExportColor(\"pageBg\");\n}\n\nexport function getThemeVarBackground(_theme: unknown, varName: string): string {\n\tconst value = cachedVars && typeof cachedVars[varName] === \"string\" ? cachedVars[varName] : \"\";\n\tconst resolved = cachedVars && value && typeof cachedVars[value] === \"string\" ? cachedVars[value] : value;\n\treturn isHexColor(resolved) ? resolved : \"\";\n}\n","// Boxless output-tree primitives shared by the ls/find/grep/bash renderers.\n//\n// ls/find/grep and bash `ls/find/grep/rg` results render their parsed output as\n// a **boxless tree panel** — a summary header line followed by `├─/└─` rows —\n// instead of a boxed command/response shell. This module owns:\n//\n// - output parsers that turn native tool text (entries, paths, `file:line:`\n// match lines) into structured records, dropping trailing truncation notices;\n// - `renderOutputTree`, which lays out a flat list of entries under a header\n// (used by lone ls/find and bash ls/find);\n// - `renderGrepTree`, which lays out grep matches grouped by file (used by grep\n// and bash grep/rg).\n//\n// Design notes:\n// - Pure + theme-consuming: no filesystem, no global state, no caching (callers\n// cache at the component boundary).\n// - Every row is width-safe via safeTruncateToWidth; the header is never\n// truncated by this layer (callers pass a concise, pre-sized header).\n// - Tree indent matches the quiet-tool batch panel (` ├─`) so the panels read\n// as one visual family.\n\nimport type { BoxTheme } from \"../../../shared/box.js\";\nimport { safeTruncateToWidth } from \"../../../shared/render-budget.js\";\n\n/** Indent for top-level tree rows; matches the quiet-tool batch panel. */\nexport const TREE_INDENT = \" \";\n/** Extra indent for rows nested under a grouping node. */\nexport const TREE_CHILD_INDENT = \" \";\n/** Default number of entries/matches shown before collapsing to \"… N more\". */\nexport const OUTPUT_TREE_HEAD_LIMIT = 6;\n\n// ── Nerd Font file-type icons ───────────────────────────────────────────────\n// Only used when the session glyph mode is nerd (see withIcons). Unicode/ASCII\n// modes render plain entries.\n\nconst FILE_ICON_FOLDER = \"\\u{F415}\"; // (nf-md-folder)\nconst FILE_ICON_DEFAULT = \"\\u{E612}\"; // (nf-seti-default)\n/** Search (magnifying-glass) icon for find/grep headers (nf-fa-search). */\nexport const SEARCH_ICON = \"\\u{F002}\";\nconst FILE_ICONS: Readonly<Record<string, string>> = {\n\tts: \"\\u{E628}\", // (nf-seti-typescript)\n\ttsx: \"\\u{E7BA}\", // (nf-seti-react)\n\tjs: \"\\u{E62C}\", // (nf-seti-javascript)\n\tjsx: \"\\u{E7BA}\", // (nf-seti-react)\n\tmjs: \"\\u{E62C}\",\n\tcjs: \"\\u{E62C}\",\n\tjson: \"\\u{E62B}\", // (nf-seti-json)\n\tmd: \"\\u{E609}\", // (nf-seti-markdown)\n\tmdx: \"\\u{E609}\",\n\tcss: \"\\u{E749}\", // (nf-seti-css)\n\tscss: \"\\u{E749}\",\n\tsass: \"\\u{E749}\",\n\tless: \"\\u{E749}\",\n\thtml: \"\\u{E60E}\", // (nf-seti-html)\n\thtm: \"\\u{E60E}\",\n\tpy: \"\\u{E606}\", // (nf-seti-python)\n\tgo: \"\\u{E627}\", // (nf-seti-go)\n\trs: \"\\u{E7A8}\", // (nf-seti-rust)\n\tsh: \"\\u{E795}\", // (nf-seti-shell)\n\tbash: \"\\u{E795}\",\n\tzsh: \"\\u{E795}\",\n\tfish: \"\\u{E795}\",\n\tyml: \"\\u{E615}\", // (nf-seti-yaml)\n\tyaml: \"\\u{E615}\",\n\ttoml: \"\\u{E615}\",\n\tjava: \"\\u{E738}\", // (nf-seti-java)\n\tc: \"\\u{E61E}\", // (nf-seti-c)\n\th: \"\\u{E61E}\",\n\tcpp: \"\\u{E61E}\",\n\thpp: \"\\u{E61E}\",\n\tcs: \"\\u{E61E}\",\n\tsvg: \"\\u{E62A}\", // (nf-seti-svg)\n\tpng: \"\\u{E61D}\", // (nf-seti-image)\n\tjpg: \"\\u{E61D}\",\n\tjpeg: \"\\u{E61D}\",\n\tgif: \"\\u{E61D}\",\n\twebp: \"\\u{E61D}\",\n\tpdf: \"\\u{E67A}\", // (nf-seti-pdf)\n\tdockerfile: \"\\u{E7B0}\", // (nf-seti-docker)\n\tlock: \"\\u{E7B0}\",\n\tgitignore: \"\\u{E702}\", // (nf-seti-git)\n\tgitattributes: \"\\u{E702}\",\n\tvue: \"\\u{ED43}\", // (nf-vue)\n\tsvelte: \"\\u{E697}\",\n};\n\n/** Nerd Font file-type icon for a path, or \"\" when not applicable. */\nexport function fileIcon(path: string): string {\n\tif (path.endsWith(\"/\")) return FILE_ICON_FOLDER;\n\tconst name = path.split(\"/\").pop() ?? path;\n\tconst lower = name.toLowerCase();\n\tconst ext = lower.includes(\".\") ? lower.slice(lower.lastIndexOf(\".\") + 1) : lower;\n\treturn FILE_ICONS[ext] ?? FILE_ICONS[lower] ?? FILE_ICON_DEFAULT;\n}\n\n/** Lines produced by these native tools to signal truncation (already in the\n * output text, not separate metadata). Dropped before parsing. */\nconst NOTICE_LINE_PATTERN = /^\\[[^\\]]*\\]$/;\n\n/** A parsed grep match line. Context lines are not surfaced in the tree. */\nexport interface GrepMatch {\n\treadonly file: string;\n\treadonly line: number;\n\treadonly content: string;\n}\n\n/** Drop trailing tool notices (`[Showing last …]`, `[Truncated: …]`) and blanks. */\nfunction stripNotices(text: string): string[] {\n\treturn text\n\t\t.replace(/\\r/g, \"\")\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trimEnd())\n\t\t.filter((line) => line.length > 0 && !NOTICE_LINE_PATTERN.test(line.trim()));\n}\n\n/**\n * Parse native `ls` output into display entries. Directories keep their `/`\n * suffix; the `(empty directory)` placeholder and truncation notices are\n * removed. Output is already sorted alphabetically by the tool.\n */\nexport function parseLsOutput(rawText: string): string[] {\n\treturn stripNotices(rawText)\n\t\t.map((line) => line.trim())\n\t\t.filter((line) => line.length > 0 && line !== \"(empty directory)\");\n}\n\n/**\n * Parse `ls -l`/`ls -la` long-format output into display entries: the entry\n * name is the text after the time column; directory names get a trailing `/`.\n * The `total N` summary and `.`/`..` entries are dropped. Standard POSIX\n * columns: perms links owner group size month day time name. macOS `@`/`+`\n * permission suffixes are tolerated.\n */\nexport function parseLsLongOutput(rawText: string): string[] {\n\tconst entries: string[] = [];\n\tfor (const line of stripNotices(rawText)) {\n\t\tif (!/^[bcdlsp-][rwxtsST-]{9}/.test(line)) continue;\n\t\tconst parts = line.split(/\\s+/);\n\t\tconst name = parts.slice(8).join(\" \").trim();\n\t\tif (!name || name === \".\" || name === \"..\") continue;\n\t\tconst isDir = (parts[0] ?? \"\").startsWith(\"d\");\n\t\tentries.push(isDir ? `${name}/` : name);\n\t}\n\treturn entries;\n}\n\n/**\n * Parse native `find` output into display paths (one per line). Notices are\n * removed. The native tool returns paths relative to the search directory.\n */\nexport function parseFindOutput(rawText: string): string[] {\n\treturn stripNotices(rawText)\n\t\t.map((line) => line.trim())\n\t\t.filter((line) => line.length > 0);\n}\n\n// Match line: path/to/file.ts:42: matched content (Pi grep adds a space;\n// ripgrep/grep emit no space). Context lines (path-line- …) are dropped.\nconst GREP_MATCH_PATTERN = /^(.*):(\\d+):[ \\t]?(.*)$/;\n// Single-file ripgrep/grep output: `42: content` (no filename).\nconst GREP_BARE_PATTERN = /^(\\d+):[ \\t]?(.*)$/;\n\n/**\n * Parse native `grep` output into match records. Only real match lines\n * (`file:line: content`) are kept; context lines (`file-line- …`) are dropped\n * so the tree stays focused on hits. Trailing notices are removed.\n */\nexport function parseGrepOutput(rawText: string): GrepMatch[] {\n\tconst matches: GrepMatch[] = [];\n\tfor (const line of stripNotices(rawText)) {\n\t\tconst match = GREP_MATCH_PATTERN.exec(line);\n\t\tif (!match) continue;\n\t\tconst [, file, lineNo, content] = match;\n\t\tif (!file || lineNo === undefined || content === undefined) continue;\n\t\tconst parsed = Number(lineNo);\n\t\tif (!Number.isFinite(parsed) || parsed < 1) continue;\n\t\tmatches.push({ file, line: parsed, content });\n\t}\n\treturn matches;\n}\n\n/**\n * Parse single-file grep/ripgrep output — `line: content` without a filename —\n * attributing every match to the given file. Used by bash `grep pattern file`.\n */\nexport function parseGrepBareOutput(rawText: string, file: string): GrepMatch[] {\n\tconst matches: GrepMatch[] = [];\n\tfor (const line of stripNotices(rawText)) {\n\t\tconst match = GREP_BARE_PATTERN.exec(line);\n\t\tif (!match) continue;\n\t\tconst parsed = Number(match[1]);\n\t\tif (!Number.isFinite(parsed) || parsed < 1) continue;\n\t\tmatches.push({ file, line: parsed, content: match[2] ?? \"\" });\n\t}\n\treturn matches;\n}\n\n/** Group grep matches by file, preserving first-seen order. */\nexport function groupMatchesByFile(matches: readonly GrepMatch[]): { file: string; matches: GrepMatch[] }[] {\n\tconst order: string[] = [];\n\tconst buckets = new Map<string, GrepMatch[]>();\n\tfor (const match of matches) {\n\t\tlet bucket = buckets.get(match.file);\n\t\tif (!bucket) {\n\t\t\tbucket = [];\n\t\t\tbuckets.set(match.file, bucket);\n\t\t\torder.push(match.file);\n\t\t}\n\t\tbucket.push(match);\n\t}\n\treturn order.map((file) => ({ file, matches: buckets.get(file) ?? [] }));\n}\n\nexport interface OutputTreeOptions {\n\t/** Maximum entries shown before the \"… N more\" row. */\n\theadLimit?: number;\n\t/** Singular noun used in the collapse row (default \"file\"); pluralized automatically. */\n\tmoreUnit?: string;\n\t/** Optional ANSI-themed color for entry text (defaults to \"toolOutput\"). */\n\tentryColor?: string;\n\t/** Indent prefix applied to every row (defaults to TREE_INDENT). */\n\tindent?: string;\n\t/** Nerd Font mode: prefix each entry with its file-type icon. */\n\twithIcons?: boolean;\n}\n\n/**\n * Render a flat output tree: `<header>` then `├─/└─` rows for the first entries\n * and a trailing `└─ … N more <unit>` row when truncated. Used by lone ls/find\n * (and bash ls/find).\n */\nexport function renderOutputTree(\n\ttheme: BoxTheme,\n\theader: string,\n\tentries: readonly string[],\n\twidth: number,\n\toptions: OutputTreeOptions = {},\n): string[] {\n\tconst headLimit = options.headLimit ?? OUTPUT_TREE_HEAD_LIMIT;\n\tconst moreUnit = options.moreUnit ?? \"file\";\n\tconst entryColor = options.entryColor ?? \"toolOutput\";\n\tconst indent = options.indent ?? TREE_INDENT;\n\tconst safeWidth = Math.max(1, width);\n\tconst label = (entry: string) => (options.withIcons && entry ? `${fileIcon(entry)} ${entry}` : entry);\n\n\tconst out: string[] = [safeTruncateToWidth(header, safeWidth, \"…\")];\n\tif (entries.length === 0) return out;\n\n\tconst visible = entries.slice(0, headLimit);\n\tconst more = entries.length - visible.length;\n\tconst lastIndex = visible.length - 1;\n\tfor (let i = 0; i < visible.length; i++) {\n\t\tconst branch = i < lastIndex || more > 0 ? \"├─\" : \"└─\";\n\t\tconst line = `${indent}${theme.fg(\"borderMuted\", branch)} ${theme.fg(entryColor, label(visible[i] ?? \"\"))}`;\n\t\tout.push(safeTruncateToWidth(line, safeWidth, \"…\"));\n\t}\n\tif (more > 0) {\n\t\tconst line = `${indent}${theme.fg(\"borderMuted\", \"└─\")} ${theme.fg(\"dim\", `… ${more} more ${pluralForm(moreUnit, more)}`)}`;\n\t\tout.push(safeTruncateToWidth(line, safeWidth, \"…\"));\n\t}\n\treturn out;\n}\n\nexport interface GrepTreeOptions {\n\t/** Maximum matches shown (across all files) before the \"… N more\" row. */\n\theadLimit?: number;\n\t/** Indent prefix applied to top-level rows. */\n\tindent?: string;\n\t/** Nerd Font mode: prefix file nodes with their file-type icon. */\n\twithIcons?: boolean;\n}\n\nfunction formatMatchRow(theme: BoxTheme, match: GrepMatch): string {\n\t// Match rows render in the output text color (not primary) so they read like\n\t// the matched code; only the file nodes carry the primary color.\n\tconst label = theme.fg(\"toolOutput\", `*${match.line}`);\n\tconst sep = theme.fg(\"borderMuted\", \"│\");\n\treturn `${label}${sep} ${theme.fg(\"toolOutput\", match.content)}`;\n}\n\n/**\n * Render a grep matches tree: `<header>` then matches grouped by file. With a\n * single file the matches are direct children; with several files each file is\n * a `├─ file` node and its matches hang off an indented trunk beneath. A\n * trailing `└─ … N more matches` row appears when the match budget is exceeded.\n */\nexport function renderGrepTree(\n\ttheme: BoxTheme,\n\theader: string,\n\tmatches: readonly GrepMatch[],\n\twidth: number,\n\toptions: GrepTreeOptions = {},\n): string[] {\n\tconst headLimit = options.headLimit ?? OUTPUT_TREE_HEAD_LIMIT;\n\tconst indent = options.indent ?? TREE_INDENT;\n\tconst safeWidth = Math.max(1, width);\n\n\tconst out: string[] = [safeTruncateToWidth(header, safeWidth, \"…\")];\n\tif (matches.length === 0) return out;\n\n\tconst groups = groupMatchesByFile(matches);\n\tconst singleFile = groups.length === 1;\n\n\t// First decide which matches fit the budget so branch glyphs (├─ vs └─) and\n\t// the trailing \"… N more\" row stay consistent.\n\tconst budget = matches.slice(0, headLimit);\n\tconst remaining = matches.length - budget.length;\n\tconst truncated = remaining > 0;\n\tconst totalVisible = budget.length;\n\n\tconst push = (line: string) => out.push(safeTruncateToWidth(line, safeWidth, \"…\"));\n\n\tif (singleFile) {\n\t\tbudget.forEach((match, index) => {\n\t\t\tconst isLast = index === totalVisible - 1 && !truncated;\n\t\t\tpush(`${indent}${theme.fg(\"borderMuted\", isLast ? \"└─\" : \"├─\")} ${formatMatchRow(theme, match)}`);\n\t\t});\n\t} else {\n\t\t// Walk the budget, tracking position within each file group so the file\n\t\t// node and its match subtree render as one connected unit.\n\t\tlet shown = 0;\n\t\tfor (let gi = 0; gi < groups.length && shown < totalVisible; gi++) {\n\t\t\tconst group = groups[gi];\n\t\t\tif (!group) continue;\n\t\t\tconst isLastGroup = gi === groups.length - 1;\n\t\t\tconst trunk = isLastGroup ? \" \" : theme.fg(\"borderMuted\", \"│\");\n\n\t\t\tconst visibleHere: GrepMatch[] = [];\n\t\t\tfor (const match of group.matches) {\n\t\t\t\tif (shown >= totalVisible) break;\n\t\t\t\tvisibleHere.push(match);\n\t\t\t\tshown++;\n\t\t\t}\n\t\t\tif (visibleHere.length === 0) continue;\n\n\t\t\tconst groupIsLastRendered = shown >= totalVisible && !truncated;\n\t\t\tconst fileLabel = options.withIcons ? `${fileIcon(group.file)} ${group.file}` : group.file;\n\t\t\t// File nodes use the primary (accent) color, matching read/ls/find paths.\n\t\t\tpush(`${indent}${theme.fg(\"borderMuted\", groupIsLastRendered ? \"└─\" : \"├─\")} ${theme.fg(\"accent\", fileLabel)}`);\n\n\t\t\tvisibleHere.forEach((match, index) => {\n\t\t\t\tconst isLastInGroup = index === visibleHere.length - 1;\n\t\t\t\tconst isLastOverall = groupIsLastRendered && isLastInGroup;\n\t\t\t\tpush(\n\t\t\t\t\t`${indent}${trunk}${TREE_CHILD_INDENT}${theme.fg(\"borderMuted\", isLastOverall ? \"└─\" : \"├─\")} ${formatMatchRow(theme, match)}`,\n\t\t\t\t);\n\t\t\t});\n\t\t}\n\t}\n\n\tif (truncated) {\n\t\tpush(\n\t\t\t`${indent}${theme.fg(\"borderMuted\", \"└─\")} ${theme.fg(\"dim\", `… ${remaining} more ${pluralForm(\"match\", remaining)}`)}`,\n\t\t);\n\t}\n\treturn out;\n}\n\n/** Return the pluralized form of a noun for the given count. */\nexport function pluralForm(noun: string, count: number): string {\n\tif (count === 1) return noun;\n\treturn /(s|x|z|ch|sh)$/i.test(noun) ? `${noun}es` : `${noun}s`;\n}\n\n/** Pluralize a count noun: \"1 file\" / \"3 files\", \"1 match\" / \"3 matches\". */\nexport function pluralize(count: number, noun: string): string {\n\treturn `${count} ${pluralForm(noun, count)}`;\n}\n","// Per-session render configuration for boxed tool presentation.\n//\n// Set once per session by the compatibility coordinator; read inside renderers.\n// Kept out of the render path (no filesystem/config reads during render).\n\nexport interface ToolsRenderConfig {\n\tmaxCollapsedLines: number;\n\tmaxExpandedLines: number;\n\tdimOutput: boolean;\n\tshowElapsed: boolean;\n\t/** Open-tree glyph for the done batch header (nerd `\\u{F111}` / unicode `●`). */\n\tbatchOpenGlyph: string;\n\t/** Nerd Font mode is active: file-type icons render in output trees. */\n\tnerdFonts: boolean;\n}\n\nlet sessionToolsConfig: ToolsRenderConfig = {\n\tmaxCollapsedLines: 10,\n\tmaxExpandedLines: 50,\n\tdimOutput: false,\n\tshowElapsed: true,\n\tbatchOpenGlyph: \"●\",\n\tnerdFonts: false,\n};\n\nexport function setToolsRenderConfig(config: Partial<ToolsRenderConfig>): void {\n\tsessionToolsConfig = { ...sessionToolsConfig, ...config };\n}\n\nexport function getToolsRenderConfig(): ToolsRenderConfig {\n\treturn sessionToolsConfig;\n}\n\n// Wall-clock elapsed tracking through the renderer context state (no tool\n// re-registration, so result.details has no execution timing).\n//\n// Elapsed is computed live from the recorded start on every read, so a running\n// tool keeps growing its displayed time. The value only freezes once the\n// execution end is recorded (terminal result), which keeps the completed footer\n// stable across later re-renders (expand toggles, terminal resizes).\n\nconst STARTED_AT_KEY = \"__piStyleStartedAt\";\nconst ENDED_AT_KEY = \"__piStyleEndedAt\";\nconst RESULT_SEEN_KEY = \"__piStyleResultSeen\";\nconst TICKER_KEY = \"__piStyleElapsedTicker\";\n\nexport function recordExecutionStarted(state: Record<string, unknown> | undefined, executionStarted: boolean): void {\n\tif (!executionStarted || !state || typeof state !== \"object\") return;\n\tif (typeof state[STARTED_AT_KEY] !== \"number\") state[STARTED_AT_KEY] = performance.now();\n}\n\n/** Freeze the elapsed at the first terminal render (idempotent). */\nexport function recordExecutionEnded(state: Record<string, unknown> | undefined): void {\n\tif (!state || typeof state !== \"object\") return;\n\tif (typeof state[ENDED_AT_KEY] !== \"number\") state[ENDED_AT_KEY] = performance.now();\n}\n\nexport function getStateElapsedMs(state: Record<string, unknown> | undefined): number | undefined {\n\tif (!state || typeof state !== \"object\") return undefined;\n\tconst started = state[STARTED_AT_KEY];\n\tif (typeof started !== \"number\") return undefined;\n\tconst ended = state[ENDED_AT_KEY];\n\tif (typeof ended === \"number\") return Math.max(0, ended - started);\n\treturn Math.max(0, performance.now() - started);\n}\n\n/** Whether a result renderer already produced a continuation for this call. */\nexport function isResultSeen(state: Record<string, unknown> | undefined): boolean {\n\treturn Boolean(state && typeof state === \"object\" && state[RESULT_SEEN_KEY] === true);\n}\n\n/** Record that a result renderer ran for this call (streaming or final). */\nexport function markResultSeen(state: Record<string, unknown> | undefined): void {\n\tif (!state || typeof state !== \"object\") return;\n\tstate[RESULT_SEEN_KEY] = true;\n}\n\ntype TickerHandle = ReturnType<typeof setInterval>;\n\n/** States that currently own a 1s elapsed-render interval, for session cleanup. */\nconst tickerStates = new Set<Record<string, unknown>>();\n\n/**\n * While a tool is running, re-render once per second so live elapsed labels\n * tick without any output events. Idempotent per state.\n */\nexport function startElapsedTicker(state: Record<string, unknown> | undefined, invalidate: () => void): void {\n\tif (!state || typeof state !== \"object\") return;\n\tif (state[TICKER_KEY] !== undefined) return;\n\tstate[TICKER_KEY] = setInterval(() => invalidate(), 1000) as unknown as TickerHandle;\n\ttickerStates.add(state);\n}\n\n/** Stop a running tool's elapsed ticker (terminal result, error, session end). */\nexport function stopElapsedTicker(state: Record<string, unknown> | undefined): void {\n\tif (!state || typeof state !== \"object\") return;\n\tconst handle = state[TICKER_KEY] as TickerHandle | undefined;\n\tif (handle !== undefined) clearInterval(handle);\n\tdelete state[TICKER_KEY];\n\ttickerStates.delete(state);\n}\n\n/** Stop every elapsed ticker (session start/shutdown). */\nexport function stopAllElapsedTickers(): void {\n\tfor (const state of tickerStates) {\n\t\tconst handle = state[TICKER_KEY] as TickerHandle | undefined;\n\t\tif (handle !== undefined) clearInterval(handle);\n\t\tdelete state[TICKER_KEY];\n\t}\n\ttickerStates.clear();\n}\n","// Consecutive quiet-tool (read/ls/find) call batching.\n//\n// Groups back-to-back calls of the same quiet tool inside one assistant turn\n// into a single collapsible, **boxless** tree panel instead of one boxed panel\n// per call. The first call of a batch becomes its leader: the leader's call\n// component renders the whole panel (header + tree), reading the live batch\n// state on every render pass. Subsequent members render zero lines, so they\n// consume no vertical space.\n//\n// Design notes:\n// - No caching in the batch panel: it reads the module-level registry on every\n// render, so member completions (which trigger ui.requestRender via Pi's\n// tool_execution_end handler) are picked up without cross-component\n// invalidation plumbing.\n// - Batch boundaries: a new batch starts when the active batch is closed. The\n// active batch closes when a non-batchable tool call is dispatched\n// (boxed/index.ts), when a new message starts (pi/index.ts), and on session\n// reset (session-coordinator.ts). Lone calls render the same boxless tree\n// (a batch of one) — there is no boxed single-call special case.\n// - No surrounding box: indentation and tree glyphs (├─/└─) carry the\n// hierarchy; the header line is the summary (` Read (N) · 0.08s`).\n// - Errors stay visible: failed members are always rendered inline (even in the\n// collapsed state), with their error text indented beneath the path.\n// - read members render a single path row. ls/find members render their parsed\n// output as a file subtree (flat for a lone call, nested per member when\n// batched) — see renderOutputBatchPanel. Pending/failed members without output\n// fall back to the path row.\n\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport { stripAnsi } from \"../../../shared/ansi.js\";\nimport { type BoxTheme, formatToolTitlePrefix } from \"../../../shared/box.js\";\nimport { safeTruncateToWidth } from \"../../../shared/render-budget.js\";\nimport {\n\tfileIcon,\n\tOUTPUT_TREE_HEAD_LIMIT,\n\tpluralForm,\n\trenderOutputTree,\n\tSEARCH_ICON,\n\tTREE_CHILD_INDENT,\n\tTREE_INDENT,\n} from \"./output-tree.js\";\nimport { getToolsRenderConfig } from \"./session-config.js\";\nimport type { BoxedToolContext } from \"./shared.js\";\n\n/** Quiet tools whose calls group into a single batch panel. */\nexport const BATCHABLE_TOOL_NAMES: ReadonlySet<string> = new Set([\"read\", \"ls\", \"find\"]);\n\nexport function isBatchableTool(toolName: unknown): boolean {\n\treturn typeof toolName === \"string\" && BATCHABLE_TOOL_NAMES.has(toolName);\n}\n\nexport interface BatchToolMeta {\n\treadonly toolName: string;\n\t/** Human label shown in the batch header (e.g. \"Read\", \"List\", \"Find\"). */\n\treadonly label: string;\n\t/** Header label for output-tree panels: \"Glob\" for find, \"List\" for ls. */\n\treadonly headerLabel?: string;\n}\n\nexport type BatchMemberStatus = \"pending\" | \"running\" | \"done\";\n\nexport interface BatchMember {\n\treadonly toolCallId: string;\n\tdetail: string;\n\tstatus: BatchMemberStatus;\n\tisError: boolean;\n\terrorText?: string;\n\t/** find glob pattern (header detail for output panels). */\n\tpattern?: string;\n\t/** Display path (header detail for output panels). */\n\tpathLabel?: string;\n\t/** Parsed output entries once the result arrives (ls/find). `undefined` until\n\t * the result is registered; an empty array means a successful zero-entry\n\t * result (e.g. an empty directory). */\n\toutputEntries?: string[];\n}\n\nexport interface BatchState {\n\treadonly meta: BatchToolMeta;\n\treadonly leaderId: string;\n\treadonly startedAt: number;\n\tcompletedAt?: number;\n\tclosed: boolean;\n\treadonly members: BatchMember[];\n}\n\n/** Tree head limit: only the first few members are listed, the rest collapse. */\nconst BATCH_TREE_HEAD_LIMIT = 5;\n/** Per-member file subtree head limit in a batched output panel. */\nconst BATCH_MEMBER_FILE_HEAD_LIMIT = 4;\nconst BATCH_ERROR_LINES = 2;\n/** Indent for tree lines below the header. */\nconst BATCH_TREE_INDENT = TREE_INDENT;\n\n/** Component rendered for non-leader batch members (zero height). */\nexport const EMPTY_BATCH_COMPONENT: Component = Object.freeze({\n\tinvalidate() {},\n\trender() {\n\t\treturn [];\n\t},\n});\n\nlet activeBatch: BatchState | undefined;\nconst batchByCallId = new Map<string, BatchState>();\n\n/** Close the current batch: no new members join; existing panels keep rendering. */\nexport function closeActiveBatch(): void {\n\tif (!activeBatch) return;\n\tactiveBatch.closed = true;\n\tactiveBatch = undefined;\n}\n\n/** Reset all batch state (session start/shutdown). */\nexport function resetBatchRegistry(): void {\n\tactiveBatch = undefined;\n\tbatchByCallId.clear();\n}\n\nfunction createBatch(\n\tmeta: BatchToolMeta,\n\tleaderId: string,\n\tdetail: string,\n\topts: { pattern?: string; pathLabel?: string } = {},\n): BatchState {\n\tconst batch: BatchState = {\n\t\tmeta,\n\t\tleaderId,\n\t\tstartedAt: performance.now(),\n\t\tclosed: false,\n\t\tmembers: [\n\t\t\t{\n\t\t\t\ttoolCallId: leaderId,\n\t\t\t\tdetail,\n\t\t\t\tstatus: \"pending\",\n\t\t\t\tisError: false,\n\t\t\t\t...(opts.pattern ? { pattern: opts.pattern } : {}),\n\t\t\t\t...(opts.pathLabel ? { pathLabel: opts.pathLabel } : {}),\n\t\t\t},\n\t\t],\n\t};\n\tactiveBatch = batch;\n\tbatchByCallId.set(leaderId, batch);\n\treturn batch;\n}\n\n/**\n * Register a call renderer invocation. Idempotent per toolCallId: re-fires\n * (updateDisplay on the same component) reuse the call's existing batch, even\n * after the batch was closed.\n */\nexport function registerBatchCall(\n\tmeta: BatchToolMeta,\n\tdetail: string,\n\tcontext: BoxedToolContext,\n\topts: { pattern?: string; pathLabel?: string } = {},\n): { batch: BatchState; isLeader: boolean } {\n\tconst existing = batchByCallId.get(context.toolCallId);\n\tif (existing) {\n\t\tconst member = existing.members.find((entry) => entry.toolCallId === context.toolCallId);\n\t\tif (member) {\n\t\t\tmember.detail = detail;\n\t\t\tif (opts.pattern !== undefined) member.pattern = opts.pattern;\n\t\t\tif (opts.pathLabel !== undefined) member.pathLabel = opts.pathLabel;\n\t\t}\n\t\treturn { batch: existing, isLeader: existing.leaderId === context.toolCallId };\n\t}\n\tconst current = activeBatch;\n\tif (!current || current.closed || current.meta.toolName !== meta.toolName) {\n\t\tcloseActiveBatch();\n\t\treturn { batch: createBatch(meta, context.toolCallId, detail, opts), isLeader: true };\n\t}\n\tconst member: BatchMember = {\n\t\ttoolCallId: context.toolCallId,\n\t\tdetail,\n\t\tstatus: \"pending\",\n\t\tisError: false,\n\t\t...(opts.pattern ? { pattern: opts.pattern } : {}),\n\t\t...(opts.pathLabel ? { pathLabel: opts.pathLabel } : {}),\n\t};\n\tcurrent.members.push(member);\n\tbatchByCallId.set(context.toolCallId, current);\n\treturn { batch: current, isLeader: false };\n}\n\nexport interface BatchResultData {\n\treadonly isPartial: boolean;\n\treadonly isError: boolean;\n\treadonly errorText: string | undefined;\n\t/** Parsed output entries (ls/find) stored on the member for tree rendering. */\n\treadonly entries?: string[];\n}\n\n/**\n * Register a result renderer invocation: updates the member's status/metadata\n * and records batch completion once every member has settled. The member's\n * display detail stays as registered by the call renderer (the result context's\n * args may be normalized differently).\n */\nexport function registerBatchResult(\n\tmeta: BatchToolMeta,\n\tdata: BatchResultData,\n\tcontext: BoxedToolContext,\n): { batch: BatchState | undefined; isLeader: boolean } {\n\tconst batch = batchByCallId.get(context.toolCallId);\n\tif (!batch || batch.meta.toolName !== meta.toolName) return { batch: undefined, isLeader: false };\n\tconst member = batch.members.find((entry) => entry.toolCallId === context.toolCallId);\n\tif (member) {\n\t\tmember.status = data.isPartial ? \"running\" : \"done\";\n\t\tmember.isError = !data.isPartial && data.isError;\n\t\tif (member.isError && data.errorText !== undefined) member.errorText = data.errorText;\n\t\telse delete member.errorText;\n\t\tif (data.entries !== undefined) member.outputEntries = data.entries;\n\t}\n\tif (batch.completedAt === undefined && batch.members.every((entry) => entry.status === \"done\")) {\n\t\tbatch.completedAt = performance.now();\n\t}\n\treturn { batch, isLeader: batch.leaderId === context.toolCallId };\n}\n\ninterface BatchStatus {\n\treadonly total: number;\n\treadonly done: number;\n\treadonly failed: number;\n\treadonly allDone: boolean;\n\treadonly elapsedMs: number | undefined;\n}\n\nfunction batchStatus(batch: BatchState): BatchStatus {\n\tlet done = 0;\n\tlet failed = 0;\n\tfor (const member of batch.members) {\n\t\tif (member.status !== \"done\") continue;\n\t\tdone++;\n\t\tif (member.isError) failed++;\n\t}\n\tconst total = batch.members.length;\n\tconst allDone = done === total;\n\treturn {\n\t\ttotal,\n\t\tdone,\n\t\tfailed,\n\t\tallDone,\n\t\telapsedMs: allDone && batch.completedAt !== undefined ? batch.completedAt - batch.startedAt : undefined,\n\t};\n}\n\nfunction formatElapsed(theme: BoxTheme, elapsedMs: number): string {\n\treturn theme.fg(\"dim\", ` · ${(elapsedMs / 1000).toFixed(2)}s`);\n}\n\nfunction bold(theme: BoxTheme, text: string): string {\n\treturn typeof theme?.bold === \"function\" ? theme.bold(text) : text;\n}\n\nfunction isOutputTool(meta: BatchToolMeta): boolean {\n\treturn meta.toolName === \"ls\" || meta.toolName === \"find\";\n}\n\n/** Header line: state glyph + batch label(count) + progress/elapsed (no box). */\nfunction formatBatchHeader(theme: BoxTheme, batch: BatchState, status: BatchStatus): string {\n\tconst label = `${batch.meta.headerLabel ?? batch.meta.label} (${status.total})`;\n\tif (status.failed > 0) return theme.fg(\"error\", bold(theme, `✗ ${label} · ${status.failed} failed`));\n\tif (status.allDone) {\n\t\tconst glyph = getToolsRenderConfig().batchOpenGlyph;\n\t\tconst elapsed = status.elapsedMs === undefined ? \"\" : formatElapsed(theme, status.elapsedMs);\n\t\treturn `${theme.fg(\"text\", bold(theme, `${glyph} ${label}`))}${elapsed}`;\n\t}\n\tif (status.done > 0)\n\t\treturn `${theme.fg(\"text\", bold(theme, `◌ ${label}`))}${theme.fg(\"dim\", ` · ${status.done}/${status.total}`)}`;\n\treturn bold(theme, formatToolTitlePrefix(theme, label));\n}\n\nfunction memberGlyph(theme: BoxTheme, member: BatchMember, show: boolean): string {\n\tif (!show) return \"\";\n\tif (member.isError) return theme.fg(\"error\", \"✗\");\n\tif (member.status === \"done\") return theme.fg(\"success\", \"✓\");\n\treturn theme.fg(\"text\", \"◌\");\n}\n\nfunction renderErrorLines(theme: BoxTheme, errorText: string, width: number): string[] {\n\tconst raw = stripAnsi(errorText)\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trim())\n\t\t.filter((line) => line.length > 0);\n\tif (raw.length === 0) return [];\n\tconst prefix = `${theme.fg(\"borderMuted\", \" │ \")}`;\n\tconst out = raw\n\t\t.slice(0, BATCH_ERROR_LINES)\n\t\t.map((line) => safeTruncateToWidth(`${prefix}${theme.fg(\"error\", line)}`, Math.max(1, width), \"…\"));\n\tif (raw.length > BATCH_ERROR_LINES)\n\t\tout.push(safeTruncateToWidth(`${prefix}${theme.fg(\"error\", \"…\")}`, Math.max(1, width), \"…\"));\n\treturn out;\n}\n\nfunction renderBatchTree(theme: BoxTheme, batch: BatchState, status: BatchStatus, width: number): string[] {\n\tconst showGlyphs = !status.allDone || status.failed > 0;\n\tconst visible = batch.members.slice(0, BATCH_TREE_HEAD_LIMIT);\n\tconst more = batch.members.length - visible.length;\n\tconst lastIndex = visible.length - 1;\n\tconst out: string[] = [];\n\tfor (let i = 0; i < visible.length; i++) {\n\t\tconst member = visible[i];\n\t\tif (!member) continue;\n\t\tconst branch = i < lastIndex || more > 0 ? \"├─\" : \"└─\";\n\t\tconst glyph = memberGlyph(theme, member, showGlyphs);\n\t\t// Primary color for files read successfully, error red for failures.\n\t\tconst pathColor = member.isError ? \"error\" : member.status === \"done\" ? \"accent\" : \"text\";\n\t\tconst line = `${BATCH_TREE_INDENT}${theme.fg(\"borderMuted\", branch)}${glyph ? ` ${glyph}` : \"\"} ${theme.fg(pathColor, member.detail)}`;\n\t\tout.push(safeTruncateToWidth(line, Math.max(1, width), \"…\"));\n\t\tif (member.isError && member.errorText) out.push(...renderErrorLines(theme, member.errorText, width));\n\t}\n\tif (more > 0) {\n\t\tout.push(\n\t\t\tsafeTruncateToWidth(\n\t\t\t\t`${BATCH_TREE_INDENT}${theme.fg(\"borderMuted\", \"└─\")} ${theme.fg(\"dim\", `${more} more`)}`,\n\t\t\t\tMath.max(1, width),\n\t\t\t\t\"…\",\n\t\t\t),\n\t\t);\n\t}\n\treturn out;\n}\n\n/** Header for a lone (batch-of-one) ls/find output panel: `Glob: <pattern> <N> files · in <path>`. */\nfunction formatLoneOutputHeader(theme: BoxTheme, meta: BatchToolMeta, member: BatchMember): string {\n\tconst label = meta.headerLabel ?? meta.label;\n\tconst count = member.outputEntries?.length ?? 0;\n\tconst filesPart = theme.fg(\"accent\", `${count} ${count === 1 ? \"file\" : \"files\"}`);\n\tconst patternPart = meta.toolName === \"find\" && member.pattern ? `${theme.fg(\"text\", member.pattern)} ` : \"\";\n\tconst pathPart = member.pathLabel ? theme.fg(\"dim\", ` · in ${member.pathLabel}`) : \"\";\n\t// ls/find headers carry the magnifying-glass icon in Nerd Font mode,\n\t// matching find/grep.\n\tconst icon = getToolsRenderConfig().nerdFonts ? `${SEARCH_ICON} ` : \"\";\n\treturn `${icon}${bold(theme, `${label}:`)} ${patternPart}${filesPart}${pathPart}`;\n}\n\n/** Nested file subtree for one member inside a batched (2+) output panel. */\nfunction renderMemberSubtree(theme: BoxTheme, member: BatchMember, isLastMember: boolean, width: number): string[] {\n\tconst safeWidth = Math.max(1, width);\n\tconst trunk = isLastMember ? \" \" : theme.fg(\"borderMuted\", \"│\");\n\tconst out: string[] = [];\n\n\t// Member header row: path + file count (or status glyph when not done).\n\tconst entries = member.outputEntries ?? [];\n\tif (member.isError) {\n\t\tconst line = `${BATCH_TREE_INDENT}${theme.fg(\"borderMuted\", isLastMember ? \"└─\" : \"├─\")} ${theme.fg(\"error\", \"✗\")} ${theme.fg(\"error\", member.pathLabel ?? member.detail)}`;\n\t\tout.push(safeTruncateToWidth(line, safeWidth, \"…\"));\n\t\tif (member.errorText) out.push(...renderErrorLines(theme, member.errorText, width));\n\t\treturn out;\n\t}\n\tif (member.status !== \"done\" || member.outputEntries === undefined) {\n\t\tconst glyph = member.status === \"done\" ? theme.fg(\"success\", \"✓\") : theme.fg(\"text\", \"◌\");\n\t\tconst line = `${BATCH_TREE_INDENT}${theme.fg(\"borderMuted\", isLastMember ? \"└─\" : \"├─\")} ${glyph} ${theme.fg(\"text\", member.pathLabel ?? member.detail)}`;\n\t\tout.push(safeTruncateToWidth(line, safeWidth, \"…\"));\n\t\treturn out;\n\t}\n\n\tconst countLabel = theme.fg(\"dim\", ` · ${entries.length} ${pluralForm(\"file\", entries.length)}`);\n\tconst headerLine = `${BATCH_TREE_INDENT}${theme.fg(\"borderMuted\", isLastMember ? \"└─\" : \"├─\")} ${theme.fg(\"accent\", member.pathLabel ?? member.detail)}${countLabel}`;\n\tout.push(safeTruncateToWidth(headerLine, safeWidth, \"…\"));\n\n\tconst visible = entries.slice(0, BATCH_MEMBER_FILE_HEAD_LIMIT);\n\tconst more = entries.length - visible.length;\n\tconst lastIndex = visible.length - 1;\n\tconst icons = getToolsRenderConfig().nerdFonts;\n\tfor (let i = 0; i < visible.length; i++) {\n\t\tconst entry = visible[i] ?? \"\";\n\t\tconst label = icons && entry ? `${fileIcon(entry)} ${entry}` : entry;\n\t\tconst branch = i < lastIndex || more > 0 ? \"├─\" : \"└─\";\n\t\tconst line = `${BATCH_TREE_INDENT}${trunk}${TREE_CHILD_INDENT}${theme.fg(\"borderMuted\", branch)} ${theme.fg(\"toolOutput\", label)}`;\n\t\tout.push(safeTruncateToWidth(line, safeWidth, \"…\"));\n\t}\n\tif (more > 0) {\n\t\tconst line = `${BATCH_TREE_INDENT}${trunk}${TREE_CHILD_INDENT}${theme.fg(\"borderMuted\", \"└─\")} ${theme.fg(\"dim\", `… ${more} more ${pluralForm(\"file\", more)}`)}`;\n\t\tout.push(safeTruncateToWidth(line, safeWidth, \"…\"));\n\t}\n\treturn out;\n}\n\n/** ls/find output panel: lone call renders a flat tree; a batch renders nested subtrees. */\nfunction renderOutputBatchPanel(theme: BoxTheme, batch: BatchState, status: BatchStatus, width: number): string[] {\n\tconst safeWidth = Math.max(1, width);\n\n\t// Lone successful call with output: flat tree under a `Glob:/List:` header.\n\tif (batch.members.length === 1) {\n\t\tconst member = batch.members[0];\n\t\tif (member && member.outputEntries !== undefined && !member.isError) {\n\t\t\tconst header = safeTruncateToWidth(formatLoneOutputHeader(theme, batch.meta, member), safeWidth, \"…\");\n\t\t\treturn renderOutputTree(theme, header, member.outputEntries, safeWidth, {\n\t\t\t\theadLimit: OUTPUT_TREE_HEAD_LIMIT,\n\t\t\t\tmoreUnit: \"file\",\n\t\t\t\tentryColor: \"toolOutput\",\n\t\t\t\tindent: BATCH_TREE_INDENT,\n\t\t\t\twithIcons: getToolsRenderConfig().nerdFonts,\n\t\t\t});\n\t\t}\n\t\t// Pending/error/empty-without-entries: fall through to the path-only panel.\n\t}\n\n\t// Batched (2+) or a not-yet-ready lone call: per-member rows/subtrees.\n\tconst header = safeTruncateToWidth(formatBatchHeader(theme, batch, status), safeWidth, \"…\");\n\tconst out: string[] = [header];\n\tconst visible = batch.members.slice(0, BATCH_TREE_HEAD_LIMIT);\n\tconst more = batch.members.length - visible.length;\n\tvisible.forEach((member, index) => {\n\t\tconst isLast = index === visible.length - 1 && more <= 0;\n\t\tout.push(...renderMemberSubtree(theme, member, isLast, safeWidth));\n\t});\n\tif (more > 0) {\n\t\tout.push(\n\t\t\tsafeTruncateToWidth(\n\t\t\t\t`${BATCH_TREE_INDENT}${theme.fg(\"borderMuted\", \"└─\")} ${theme.fg(\"dim\", `${more} more`)}`,\n\t\t\t\tsafeWidth,\n\t\t\t\t\"…\",\n\t\t\t),\n\t\t);\n\t}\n\treturn out;\n}\n\nfunction renderBatchPanelLines(theme: BoxTheme, batch: BatchState, status: BatchStatus, width: number): string[] {\n\t// The tree stays open in every state, including for a lone call: no boxed\n\t// single-call special case, no collapsed single-line summary.\n\tif (isOutputTool(batch.meta) && batch.members.some((member) => member.outputEntries !== undefined)) {\n\t\treturn renderOutputBatchPanel(theme, batch, status, width);\n\t}\n\tconst header = safeTruncateToWidth(formatBatchHeader(theme, batch, status), Math.max(1, width), \"…\");\n\tconst lines = [header];\n\tlines.push(...renderBatchTree(theme, batch, status, width));\n\treturn lines;\n}\n\n/**\n * Leader call component: renders the live batch panel (header + tree) reading\n * the registry on every render pass. Members render EMPTY_BATCH_COMPONENT.\n */\nexport function renderBatchAwareCall(theme: BoxTheme, batch: BatchState): Component {\n\treturn {\n\t\tinvalidate() {},\n\t\trender(width: number): string[] {\n\t\t\treturn renderBatchPanelLines(theme, batch, batchStatus(batch), width);\n\t\t},\n\t};\n}\n\n/**\n * Empty result component for the batch leader. The panel lives in the call\n * component; the result adds nothing. Deliberately NOT the shared member\n * singleton, so the decoration's hideBatchMember (identity-compared to\n * EMPTY_BATCH_COMPONENT) never hides the leader.\n */\nexport function emptyBatchResult(): Component {\n\treturn {\n\t\tinvalidate() {},\n\t\trender() {\n\t\t\treturn [];\n\t\t},\n\t};\n}\n","export type ConfigDiagnosticLevel = \"warning\" | \"error\";\nexport interface ConfigDiagnostic {\n\treadonly code: string;\n\treadonly level: ConfigDiagnosticLevel;\n\treadonly path: string;\n\treadonly message: string;\n}\n\nexport function boundedDiagnostics(items: readonly ConfigDiagnostic[], limit = 32): readonly ConfigDiagnostic[] {\n\tconst seen = new Set<string>();\n\tconst result: ConfigDiagnostic[] = [];\n\tfor (const item of items) {\n\t\tconst key = `${item.level}:${item.code}:${item.path}:${item.message}`;\n\t\tif (seen.has(key)) continue;\n\t\tseen.add(key);\n\t\tresult.push(Object.freeze(item));\n\t\tif (result.length >= limit) break;\n\t}\n\treturn Object.freeze(result);\n}\n","import type { PiStyleConfig, PresetName } from \"./config-types.js\";\n\n/** Code-defined coordinated defaults. Explicit fields are merged after these values. */\nexport const CONFIG_PRESETS: Readonly<Record<PresetName, Readonly<PiStyleConfig>>> = Object.freeze({\n\tdefault: Object.freeze({\n\t\tstartup: { mode: \"compact\" },\n\t}),\n\tminimal: Object.freeze({\n\t\tstatusLine: { layout: { left: [\"path\", \"git\"], right: [\"context_pct\"], secondary: [] } },\n\t\teditor: { style: \"native\", frame: \"native\", showMetadata: false },\n\t\tstartup: { mode: \"off\" },\n\t\tmessages: { enabled: false },\n\t\ttools: { enabled: false },\n\t\ttheme: { terminalBackgroundSync: \"off\" },\n\t}),\n\tcompact: Object.freeze({\n\t\tstatusLine: {\n\t\t\tlayout: { left: [\"model\", \"thinking\", \"git\"], right: [\"context_pct\"], secondary: [\"extension_statuses\"] },\n\t\t},\n\t\teditor: { style: \"compact\", frame: \"auto\", showMetadata: false },\n\t\tstartup: { mode: \"compact\" },\n\t}),\n\tfull: Object.freeze({\n\t\tstatusLine: {\n\t\t\tlayout: {\n\t\t\t\tleft: [\"hostname\", \"model\", \"thinking\", \"path\", \"git\", \"session\"],\n\t\t\t\tright: [\"token_in\", \"token_out\", \"cache_read\", \"cost\", \"context_pct\", \"time_spent\", \"time\"],\n\t\t\t\tsecondary: [\"extension_statuses\"],\n\t\t\t},\n\t\t},\n\t\teditor: { style: \"boxed\", frame: \"outline\", showMetadata: true },\n\t\tstartup: { mode: \"overlay\", showResources: true },\n\t}),\n\tascii: Object.freeze({\n\t\teditor: { style: \"compact\", frame: \"auto\" },\n\t\tstartup: { mode: \"compact\" },\n\t\ttheme: { nerdFonts: \"off\", terminalBackgroundSync: \"off\" },\n\t}),\n\tnative: Object.freeze({\n\t\tstatusLine: { layout: { left: [\"model\", \"path\"], right: [\"context_pct\"], secondary: [] } },\n\t\teditor: { style: \"native\", frame: \"native\", showMetadata: false },\n\t\tstartup: { mode: \"off\" },\n\t\tmessages: { enabled: false },\n\t\ttools: { enabled: false },\n\t\ttheme: { terminalBackgroundSync: \"off\" },\n\t}),\n});\n\nexport function presetConfig(name: unknown): Readonly<PiStyleConfig> {\n\treturn CONFIG_PRESETS[(typeof name === \"string\" && name in CONFIG_PRESETS ? name : \"default\") as PresetName];\n}\n","export const PI_STYLE_SCHEMA_VERSION = 1 as const;\n\nexport type Placement = \"above\" | \"below\";\nexport type NerdFontsMode = \"auto\" | \"on\" | \"off\";\nexport type ToggleMode = \"auto\" | \"on\" | \"off\";\nexport type PresetName = \"default\" | \"minimal\" | \"compact\" | \"full\" | \"ascii\" | \"native\";\nexport type EditorStyle = \"compact\" | \"boxed\" | \"dock\" | \"native\";\nexport type EditorFrame = \"auto\" | \"halfblock\" | \"line\" | \"solid\" | \"outline\" | \"native\";\n\nexport interface StatusCustomItemConfig {\n\tid: string;\n\tstatusKey: string;\n\tlabel?: string;\n\tpriority?: number;\n\tplacement?: \"left\" | \"right\" | \"secondary\";\n}\n\nexport interface PiStyleConfig {\n\tenabled?: boolean;\n\tpreset?: string;\n\tplacement?: string;\n\tstartup?: { mode?: string; showResources?: boolean; alwaysExpanded?: boolean };\n\tstatusLine?: {\n\t\tenabled?: boolean;\n\t\tseparator?: string;\n\t\tlayout?: { left?: string[]; right?: string[]; secondary?: string[] };\n\t\tdisabledSegments?: string[];\n\t\tcustomItems?: StatusCustomItemConfig[];\n\t\t/** Blank rows reserved below the primary status row (0 disables). */\n\t\tbottomMargin?: number;\n\t\t/** Context progress-bar cell count (default 10). */\n\t\tcontextBarWidth?: number;\n\t};\n\teditor?: { enabled?: boolean; style?: string; frame?: string; showMetadata?: boolean };\n\tmessages?: { enabled?: boolean; assistantPrefix?: boolean; specialBlocks?: boolean; hideThinkingLabel?: boolean };\n\ttools?: {\n\t\tenabled?: boolean;\n\t\tstyle?: string;\n\t\tmaxCollapsedLines?: number;\n\t\tmaxExpandedLines?: number;\n\t\tdimOutput?: boolean;\n\t\tshowElapsed?: boolean;\n\t};\n\ttheme?: {\n\t\tnerdFonts?: string;\n\t\tterminalBackgroundSync?: string;\n\t\tcolors?: Record<string, unknown>;\n\t\tglyphs?: Record<string, unknown>;\n\t};\n\tcompatibility?: {\n\t\tallowSafePatches?: boolean;\n\t\tallowCorePatches?: boolean;\n\t\tpreferExistingEditor?: boolean;\n\t\tpreferExistingFooter?: boolean;\n\t};\n\tdebug?: boolean;\n\tschemaVersion?: number;\n}\n\nexport interface NormalizedPiStyleConfig {\n\treadonly schemaVersion: typeof PI_STYLE_SCHEMA_VERSION;\n\treadonly enabled: boolean;\n\treadonly preset: PresetName;\n\treadonly placement: Placement;\n\treadonly startup: {\n\t\tmode: \"off\" | \"compact\" | \"overlay\";\n\t\tshowResources: boolean;\n\t\talwaysExpanded: boolean;\n\t};\n\treadonly statusLine: {\n\t\tenabled: boolean;\n\t\tseparator: string;\n\t\tlayout: { left: readonly string[]; right: readonly string[]; secondary: readonly string[] };\n\t\tdisabledSegments: readonly string[];\n\t\tcustomItems: readonly StatusCustomItemConfig[];\n\t\t/** Blank rows reserved below the primary status row (0 disables). */\n\t\tbottomMargin: number;\n\t\t/** Context progress-bar cell count. */\n\t\tcontextBarWidth: number;\n\t};\n\treadonly editor: { enabled: boolean; style: EditorStyle; frame: EditorFrame; showMetadata: boolean };\n\treadonly messages: { enabled: boolean; assistantPrefix: boolean; specialBlocks: boolean; hideThinkingLabel: boolean };\n\treadonly tools: {\n\t\tenabled: boolean;\n\t\tstyle: string;\n\t\tmaxCollapsedLines: number;\n\t\tmaxExpandedLines: number;\n\t\tdimOutput: boolean;\n\t\tshowElapsed: boolean;\n\t};\n\treadonly theme: {\n\t\tnerdFonts: NerdFontsMode;\n\t\tterminalBackgroundSync: ToggleMode;\n\t\tcolors: Readonly<Record<string, string>>;\n\t\tglyphs: Readonly<Record<string, string>>;\n\t};\n\treadonly compatibility: {\n\t\tallowSafePatches: boolean;\n\t\tallowCorePatches: boolean;\n\t\tpreferExistingEditor: boolean;\n\t\tpreferExistingFooter: boolean;\n\t};\n\t/** Internal provenance marker; never serialized or accepted as a command field. */\n\treadonly productCorePatchesExplicit?: boolean;\n\treadonly debug: boolean;\n}\n\nexport interface ConfigSources {\n\tdefaults?: unknown;\n\tglobal?: unknown;\n\tproject?: unknown;\n\tenvironment?: Record<string, string | undefined>;\n\tsession?: unknown;\n\tprojectTrusted?: boolean;\n}\n","import type { PresetName } from \"./config-types.js\";\nimport type { StatusLayout, StatusSegmentId } from \"./status.js\";\n\nexport const STATUS_PRESETS: Readonly<Record<PresetName, StatusLayout>> = Object.freeze({\n\tdefault: Object.freeze({\n\t\tleft: [\"path\", \"git\", \"context_bar\", \"cost\"],\n\t\tright: [\"model_effort\"],\n\t\tsecondary: [\"extension_statuses\"],\n\t}),\n\tminimal: Object.freeze({ left: [\"path\", \"git\"], right: [\"context_pct\"], secondary: [] }),\n\tcompact: Object.freeze({\n\t\tleft: [\"model\", \"thinking\", \"git\"],\n\t\tright: [\"context_pct\"],\n\t\tsecondary: [\"extension_statuses\"],\n\t}),\n\tfull: Object.freeze({\n\t\tleft: [\"hostname\", \"model\", \"thinking\", \"path\", \"git\", \"session\"],\n\t\tright: [\"token_in\", \"token_out\", \"cache_read\", \"cost\", \"context_pct\", \"time_spent\", \"time\"],\n\t\tsecondary: [\"extension_statuses\"],\n\t}),\n\tascii: Object.freeze({\n\t\tleft: [\"path\", \"git\", \"context_bar\", \"cost\"],\n\t\tright: [\"model_effort\"],\n\t\tsecondary: [\"extension_statuses\"],\n\t}),\n\tnative: Object.freeze({ left: [\"model\", \"path\"], right: [\"context_pct\"], secondary: [] }),\n});\n\nfunction unique(values: readonly unknown[]): StatusSegmentId[] {\n\tconst result: StatusSegmentId[] = [];\n\tfor (const value of values) {\n\t\tif (typeof value !== \"string\" || result.includes(value)) continue;\n\t\tresult.push(value);\n\t}\n\treturn result;\n}\n\nexport function normalizeStatusLayout(\n\tpreset: PresetName,\n\tinput:\n\t\t| {\n\t\t\t\tleft?: readonly unknown[] | undefined;\n\t\t\t\tright?: readonly unknown[] | undefined;\n\t\t\t\tsecondary?: readonly unknown[] | undefined;\n\t\t }\n\t\t| undefined,\n): StatusLayout {\n\tconst base = STATUS_PRESETS[preset] ?? STATUS_PRESETS.default;\n\tconst left = input?.left === undefined ? base.left : unique(input.left);\n\tconst right = input?.right === undefined ? base.right : unique(input.right);\n\tconst secondary = input?.secondary === undefined ? base.secondary : unique(input.secondary);\n\tconst seen = new Set<StatusSegmentId>();\n\tconst dedupe = (values: readonly StatusSegmentId[]) =>\n\t\tvalues.filter((value) => {\n\t\t\tif (seen.has(value)) return false;\n\t\t\tseen.add(value);\n\t\t\treturn true;\n\t\t});\n\treturn Object.freeze({ left: dedupe(left), right: dedupe(right), secondary: dedupe(secondary) });\n}\n","import { boundedDiagnostics, type ConfigDiagnostic } from \"./config-diagnostics.js\";\nimport { presetConfig } from \"./config-presets.js\";\nimport {\n\ttype ConfigSources,\n\ttype NormalizedPiStyleConfig,\n\tPI_STYLE_SCHEMA_VERSION,\n\ttype PiStyleConfig,\n} from \"./config-types.js\";\nimport { normalizeStatusLayout } from \"./status-presets.js\";\n\nexport const DEFAULT_CONFIG: NormalizedPiStyleConfig = Object.freeze({\n\tschemaVersion: PI_STYLE_SCHEMA_VERSION,\n\tenabled: true,\n\tpreset: \"default\",\n\tplacement: \"below\",\n\tstartup: Object.freeze({ mode: \"compact\", showResources: false, alwaysExpanded: false }),\n\tstatusLine: Object.freeze({\n\t\tenabled: true,\n\t\tseparator: \"powerline-thin\",\n\t\tlayout: Object.freeze({\n\t\t\tleft: [\"path\", \"git\", \"context_bar\", \"cost\"],\n\t\t\tright: [\"model_effort\"],\n\t\t\tsecondary: [],\n\t\t}),\n\t\tdisabledSegments: [],\n\t\tcustomItems: [],\n\t\tbottomMargin: 1,\n\t\tcontextBarWidth: 10,\n\t}),\n\teditor: Object.freeze({ enabled: true, style: \"compact\", frame: \"auto\", showMetadata: false }),\n\tmessages: Object.freeze({ enabled: true, assistantPrefix: true, specialBlocks: true, hideThinkingLabel: true }),\n\ttools: Object.freeze({\n\t\tenabled: true,\n\t\tstyle: \"compact-box\",\n\t\tmaxCollapsedLines: 10,\n\t\tmaxExpandedLines: 50,\n\t\tdimOutput: false,\n\t\tshowElapsed: true,\n\t}),\n\ttheme: Object.freeze({ nerdFonts: \"auto\", terminalBackgroundSync: \"auto\", colors: {}, glyphs: {} }),\n\tcompatibility: Object.freeze({\n\t\tallowSafePatches: true,\n\t\tallowCorePatches: false,\n\t\tpreferExistingEditor: true,\n\t\tpreferExistingFooter: true,\n\t}),\n\tdebug: false,\n});\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction merge(base: Record<string, unknown>, source: unknown): Record<string, unknown> {\n\tif (!isRecord(source)) return base;\n\tconst result: Record<string, unknown> = { ...base };\n\tfor (const [key, value] of Object.entries(source))\n\t\tresult[key] =\n\t\t\tisRecord(value) && isRecord(result[key]) ? merge(result[key] as Record<string, unknown>, value) : value;\n\treturn result;\n}\nfunction bool(value: unknown, fallback: boolean): boolean {\n\treturn typeof value === \"boolean\" ? value : fallback;\n}\nfunction boundedInt(value: unknown, fallback: number, min: number, max: number): number {\n\treturn typeof value === \"number\" && Number.isFinite(value)\n\t\t? Math.min(max, Math.max(min, Math.floor(value)))\n\t\t: fallback;\n}\nfunction stringEnum<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {\n\treturn typeof value === \"string\" && (allowed as readonly string[]).includes(value) ? (value as T) : fallback;\n}\nfunction strings(value: unknown, fallback: readonly string[]): readonly string[] {\n\treturn Array.isArray(value) && value.every((item) => typeof item === \"string\") ? [...value] : fallback;\n}\nfunction stringMap(value: unknown): Readonly<Record<string, string>> {\n\treturn isRecord(value)\n\t\t? Object.fromEntries(\n\t\t\t\tObject.entries(value).filter((entry): entry is [string, string] => typeof entry[1] === \"string\"),\n\t\t\t)\n\t\t: {};\n}\nfunction customItems(value: unknown): readonly import(\"./config-types.js\").StatusCustomItemConfig[] {\n\tif (!Array.isArray(value)) return [];\n\treturn value.filter((item): item is import(\"./config-types.js\").StatusCustomItemConfig => {\n\t\tif (!isRecord(item) || typeof item.id !== \"string\" || typeof item.statusKey !== \"string\") return false;\n\t\treturn item.placement === undefined || [\"left\", \"right\", \"secondary\"].includes(item.placement as string);\n\t});\n}\n\nexport function normalizeConfig(\n\tinput: unknown,\n\tdefaults: NormalizedPiStyleConfig = DEFAULT_CONFIG,\n): NormalizedPiStyleConfig {\n\tconst value = merge(defaults as unknown as Record<string, unknown>, acceptedInput(input));\n\tconst inputRecord = isRecord(input) ? input : {};\n\tconst inputStatus = isRecord(inputRecord.statusLine) ? inputRecord.statusLine : {};\n\tconst inputLayout = isRecord(inputStatus.layout) ? inputStatus.layout : undefined;\n\tconst startup = isRecord(value.startup) ? value.startup : {};\n\tconst status = isRecord(value.statusLine) ? value.statusLine : {};\n\tconst editor = isRecord(value.editor) ? value.editor : {};\n\tconst messages = isRecord(value.messages) ? value.messages : {};\n\tconst tools = isRecord(value.tools) ? value.tools : {};\n\tconst theme = isRecord(value.theme) ? value.theme : {};\n\tconst compatibility = isRecord(value.compatibility) ? value.compatibility : {};\n\tconst max =\n\t\ttypeof tools.maxCollapsedLines === \"number\" &&\n\t\tNumber.isFinite(tools.maxCollapsedLines) &&\n\t\ttools.maxCollapsedLines >= 0\n\t\t\t? Math.floor(tools.maxCollapsedLines)\n\t\t\t: defaults.tools.maxCollapsedLines;\n\tconst maxExpanded =\n\t\ttypeof tools.maxExpandedLines === \"number\" && Number.isFinite(tools.maxExpandedLines) && tools.maxExpandedLines >= 0\n\t\t\t? Math.min(Math.floor(tools.maxExpandedLines), 1000)\n\t\t\t: defaults.tools.maxExpandedLines;\n\treturn Object.freeze({\n\t\tschemaVersion: PI_STYLE_SCHEMA_VERSION,\n\t\tenabled: bool(value.enabled, defaults.enabled),\n\t\tpreset: stringEnum(value.preset, [\"default\", \"minimal\", \"compact\", \"full\", \"ascii\", \"native\"], defaults.preset),\n\t\tplacement: stringEnum(value.placement, [\"above\", \"below\"], defaults.placement),\n\t\tstartup: Object.freeze({\n\t\t\tmode: stringEnum(startup.mode, [\"off\", \"compact\", \"overlay\"], defaults.startup.mode),\n\t\t\tshowResources: bool(startup.showResources, defaults.startup.showResources),\n\t\t\talwaysExpanded: bool(startup.alwaysExpanded, defaults.startup.alwaysExpanded),\n\t\t}),\n\t\tstatusLine: Object.freeze({\n\t\t\tenabled: bool(status.enabled, defaults.statusLine.enabled),\n\t\t\tseparator: typeof status.separator === \"string\" ? status.separator : defaults.statusLine.separator,\n\t\t\tlayout: normalizeStatusLayout(\n\t\t\t\tstringEnum(value.preset, [\"default\", \"minimal\", \"compact\", \"full\", \"ascii\", \"native\"], defaults.preset),\n\t\t\t\tinputLayout\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tleft:\n\t\t\t\t\t\t\t\tinputLayout.left === undefined ? undefined : strings(inputLayout.left, defaults.statusLine.layout.left),\n\t\t\t\t\t\t\tright:\n\t\t\t\t\t\t\t\tinputLayout.right === undefined\n\t\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t\t: strings(inputLayout.right, defaults.statusLine.layout.right),\n\t\t\t\t\t\t\tsecondary:\n\t\t\t\t\t\t\t\tinputLayout.secondary === undefined\n\t\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t\t: strings(inputLayout.secondary, defaults.statusLine.layout.secondary),\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\t),\n\t\t\tdisabledSegments: strings(status.disabledSegments, defaults.statusLine.disabledSegments),\n\t\t\tcustomItems: customItems(status.customItems),\n\t\t\tbottomMargin: boundedInt(status.bottomMargin, defaults.statusLine.bottomMargin, 0, 4),\n\t\t\tcontextBarWidth: boundedInt(status.contextBarWidth, defaults.statusLine.contextBarWidth, 4, 40),\n\t\t}),\n\t\teditor: Object.freeze({\n\t\t\tenabled: bool(editor.enabled, defaults.editor.enabled),\n\t\t\tstyle: stringEnum(editor.style, [\"compact\", \"boxed\", \"dock\", \"native\"], defaults.editor.style),\n\t\t\tframe: stringEnum(\n\t\t\t\teditor.frame,\n\t\t\t\t[\"auto\", \"halfblock\", \"line\", \"solid\", \"outline\", \"native\"],\n\t\t\t\tdefaults.editor.frame,\n\t\t\t),\n\t\t\tshowMetadata: bool(editor.showMetadata, defaults.editor.showMetadata),\n\t\t}),\n\t\tmessages: Object.freeze({\n\t\t\tenabled: bool(messages.enabled, defaults.messages.enabled),\n\t\t\tassistantPrefix: bool(messages.assistantPrefix, defaults.messages.assistantPrefix),\n\t\t\tspecialBlocks: bool(messages.specialBlocks, defaults.messages.specialBlocks),\n\t\t\thideThinkingLabel: bool(messages.hideThinkingLabel, defaults.messages.hideThinkingLabel),\n\t\t}),\n\t\ttools: Object.freeze({\n\t\t\tenabled: bool(tools.enabled, defaults.tools.enabled),\n\t\t\tstyle: typeof tools.style === \"string\" ? tools.style : defaults.tools.style,\n\t\t\tmaxCollapsedLines: max,\n\t\t\tmaxExpandedLines: maxExpanded,\n\t\t\tdimOutput: bool(tools.dimOutput, defaults.tools.dimOutput),\n\t\t\tshowElapsed: bool(tools.showElapsed, defaults.tools.showElapsed),\n\t\t}),\n\t\ttheme: Object.freeze({\n\t\t\tnerdFonts: stringEnum(theme.nerdFonts, [\"auto\", \"on\", \"off\"], defaults.theme.nerdFonts),\n\t\t\tterminalBackgroundSync: stringEnum(\n\t\t\t\ttheme.terminalBackgroundSync,\n\t\t\t\t[\"auto\", \"on\", \"off\"],\n\t\t\t\tdefaults.theme.terminalBackgroundSync,\n\t\t\t),\n\t\t\tcolors: stringMap(theme.colors),\n\t\t\tglyphs: stringMap(theme.glyphs),\n\t\t}),\n\t\tcompatibility: Object.freeze({\n\t\t\tallowSafePatches: bool(compatibility.allowSafePatches, defaults.compatibility.allowSafePatches),\n\t\t\tallowCorePatches: bool(compatibility.allowCorePatches, defaults.compatibility.allowCorePatches),\n\t\t\tpreferExistingEditor: bool(compatibility.preferExistingEditor, defaults.compatibility.preferExistingEditor),\n\t\t\tpreferExistingFooter: bool(compatibility.preferExistingFooter, defaults.compatibility.preferExistingFooter),\n\t\t}),\n\t\tdebug: bool(value.debug, defaults.debug),\n\t});\n}\n\nexport function resolveConfig(sources: ConfigSources): NormalizedPiStyleConfig {\n\treturn resolveConfigDetailed(sources).config;\n}\n\nconst PRESET_NAMES = [\"default\", \"minimal\", \"compact\", \"full\", \"ascii\", \"native\"] as const;\nconst ENUMS: Readonly<Record<string, readonly string[]>> = {\n\tpreset: PRESET_NAMES,\n\tplacement: [\"above\", \"below\"],\n\t\"startup.mode\": [\"off\", \"compact\", \"overlay\"],\n\t\"editor.style\": [\"compact\", \"boxed\", \"dock\", \"native\"],\n\t\"editor.frame\": [\"auto\", \"halfblock\", \"line\", \"solid\", \"outline\", \"native\"],\n\t\"theme.nerdFonts\": [\"auto\", \"on\", \"off\"],\n\t\"theme.terminalBackgroundSync\": [\"auto\", \"on\", \"off\"],\n};\nconst BOOL_PATHS = new Set([\n\t\"enabled\",\n\t\"startup.showResources\",\n\t\"startup.alwaysExpanded\",\n\t\"statusLine.enabled\",\n\t\"editor.enabled\",\n\t\"editor.showMetadata\",\n\t\"messages.enabled\",\n\t\"messages.assistantPrefix\",\n\t\"messages.specialBlocks\",\n\t\"messages.hideThinkingLabel\",\n\t\"tools.enabled\",\n\t\"tools.showElapsed\",\n\t\"tools.dimOutput\",\n\t\"compatibility.allowSafePatches\",\n\t\"compatibility.allowCorePatches\",\n\t\"compatibility.preferExistingEditor\",\n\t\"compatibility.preferExistingFooter\",\n\t\"debug\",\n]);\nconst STRING_ARRAY_PATHS = new Set([\n\t\"statusLine.layout.left\",\n\t\"statusLine.layout.right\",\n\t\"statusLine.layout.secondary\",\n\t\"statusLine.disabledSegments\",\n]);\nconst MAP_PATHS = new Set([\"theme.colors\", \"theme.glyphs\"]);\nconst CONTAINER_PATHS = new Set([\n\t\"startup\",\n\t\"statusLine\",\n\t\"statusLine.layout\",\n\t\"editor\",\n\t\"messages\",\n\t\"tools\",\n\t\"theme\",\n\t\"compatibility\",\n]);\nfunction validCustomItem(item: unknown): boolean {\n\tif (!isRecord(item) || typeof item.id !== \"string\" || typeof item.statusKey !== \"string\") return false;\n\tif (Object.keys(item).some((key) => ![\"id\", \"statusKey\", \"label\", \"priority\", \"placement\"].includes(key)))\n\t\treturn false;\n\tif (item.label !== undefined && typeof item.label !== \"string\") return false;\n\tif (item.priority !== undefined && (typeof item.priority !== \"number\" || !Number.isFinite(item.priority)))\n\t\treturn false;\n\treturn (\n\t\titem.placement === undefined ||\n\t\titem.placement === \"left\" ||\n\t\titem.placement === \"right\" ||\n\t\titem.placement === \"secondary\"\n\t);\n}\nfunction validLeaf(path: string, value: unknown): boolean {\n\tif (BOOL_PATHS.has(path)) return typeof value === \"boolean\";\n\tif (ENUMS[path]) return typeof value === \"string\" && ENUMS[path].includes(value);\n\tif (path === \"statusLine.separator\" || path === \"tools.style\") return typeof value === \"string\";\n\tif (path === \"tools.maxCollapsedLines\" || path === \"tools.maxExpandedLines\")\n\t\treturn typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\tif (path === \"statusLine.bottomMargin\" || path === \"statusLine.contextBarWidth\")\n\t\treturn typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\tif (STRING_ARRAY_PATHS.has(path)) return Array.isArray(value) && value.every((item) => typeof item === \"string\");\n\tif (MAP_PATHS.has(path)) return isRecord(value) && Object.values(value).every((item) => typeof item === \"string\");\n\tif (path === \"statusLine.customItems\") return Array.isArray(value) && value.every(validCustomItem);\n\treturn false;\n}\nexport interface ConfigLayerResult {\n\treadonly accepted: unknown;\n\treadonly diagnostics: readonly ConfigDiagnostic[];\n\treadonly paths: ReadonlySet<string>;\n}\nfunction cloneLeaf(value: unknown): unknown {\n\treturn Array.isArray(value)\n\t\t? value.map((item) => (isRecord(item) ? { ...item } : item))\n\t\t: isRecord(value)\n\t\t\t? { ...value }\n\t\t\t: value;\n}\nexport function validateConfigLayer(input: unknown): ConfigLayerResult {\n\tconst diagnostics: ConfigDiagnostic[] = [];\n\tconst paths = new Set<string>();\n\tconst walk = (value: unknown, prefix: string): unknown => {\n\t\tif (!isRecord(value)) return value;\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const [key, nestedValue] of Object.entries(value)) {\n\t\t\tconst path = prefix ? `${prefix}.${key}` : key;\n\t\t\tif (path === \"schemaVersion\") {\n\t\t\t\tif (nestedValue === undefined || nestedValue === PI_STYLE_SCHEMA_VERSION) result[key] = nestedValue;\n\t\t\t\telse\n\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\tcode: \"CFG-SCHEMA\",\n\t\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tmessage: \"unsupported schema version ignored\",\n\t\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (path === \"statusLine.customItems\" && Array.isArray(nestedValue)) {\n\t\t\t\tconst acceptedItems: Record<string, unknown>[] = [];\n\t\t\t\tfor (const [index, item] of nestedValue.entries()) {\n\t\t\t\t\tif (!isRecord(item)) {\n\t\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\t\tcode: \"CFG-VALUE\",\n\t\t\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\t\t\tpath: `${path}[${index}]`,\n\t\t\t\t\t\t\tmessage: \"custom item must be an object\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst allowed = [\"id\", \"statusKey\", \"label\", \"priority\", \"placement\"];\n\t\t\t\t\tlet valid = typeof item.id === \"string\" && typeof item.statusKey === \"string\";\n\t\t\t\t\tif (typeof item.id !== \"string\")\n\t\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\t\tcode: \"CFG-VALUE\",\n\t\t\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\t\t\tpath: `${path}[${index}].id`,\n\t\t\t\t\t\t\tmessage: \"required custom item field is invalid or missing\",\n\t\t\t\t\t\t});\n\t\t\t\t\tif (typeof item.statusKey !== \"string\")\n\t\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\t\tcode: \"CFG-VALUE\",\n\t\t\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\t\t\tpath: `${path}[${index}].statusKey`,\n\t\t\t\t\t\t\tmessage: \"required custom item field is invalid or missing\",\n\t\t\t\t\t\t});\n\t\t\t\t\tfor (const field of Object.keys(item)) {\n\t\t\t\t\t\tif (!allowed.includes(field)) {\n\t\t\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\t\t\tcode: \"CFG-VALUE\",\n\t\t\t\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\t\t\t\tpath: `${path}[${index}].${field}`,\n\t\t\t\t\t\t\t\tmessage: \"unknown custom item field ignored\",\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tvalid = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (item.label !== undefined && typeof item.label !== \"string\") {\n\t\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\t\tcode: \"CFG-VALUE\",\n\t\t\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\t\t\tpath: `${path}[${index}].label`,\n\t\t\t\t\t\t\tmessage: \"invalid custom item field ignored\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tvalid = false;\n\t\t\t\t\t}\n\t\t\t\t\tif (item.priority !== undefined && (typeof item.priority !== \"number\" || !Number.isFinite(item.priority))) {\n\t\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\t\tcode: \"CFG-VALUE\",\n\t\t\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\t\t\tpath: `${path}[${index}].priority`,\n\t\t\t\t\t\t\tmessage: \"invalid custom item field ignored\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tvalid = false;\n\t\t\t\t\t}\n\t\t\t\t\tif (item.placement !== undefined && ![\"left\", \"right\", \"secondary\"].includes(item.placement as string)) {\n\t\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\t\tcode: \"CFG-VALUE\",\n\t\t\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\t\t\tpath: `${path}[${index}].placement`,\n\t\t\t\t\t\t\tmessage: \"invalid custom item field ignored\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tvalid = false;\n\t\t\t\t\t}\n\t\t\t\t\tif (valid) {\n\t\t\t\t\t\tacceptedItems.push({ ...item });\n\t\t\t\t\t\tpaths.add(`${path}[${index}].id`);\n\t\t\t\t\t\tpaths.add(`${path}[${index}].statusKey`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tresult[key] = acceptedItems;\n\t\t\t\tpaths.add(path);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (validLeaf(path, nestedValue)) {\n\t\t\t\tresult[key] = cloneLeaf(nestedValue);\n\t\t\t\tpaths.add(path);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tisRecord(nestedValue) &&\n\t\t\t\tCONTAINER_PATHS.has(path) &&\n\t\t\t\t!MAP_PATHS.has(path) &&\n\t\t\t\tpath !== \"statusLine.customItems\"\n\t\t\t) {\n\t\t\t\tconst child = walk(nestedValue, path);\n\t\t\t\tif (isRecord(child) && Object.keys(child).length > 0) result[key] = child;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (path !== \"statusLine.customItems\" || !Array.isArray(nestedValue))\n\t\t\t\tdiagnostics.push({ code: \"CFG-VALUE\", level: \"warning\", path, message: \"invalid or unknown field ignored\" });\n\t\t\tif (path === \"statusLine.customItems\" && Array.isArray(nestedValue))\n\t\t\t\tfor (const [index, item] of nestedValue.entries()) {\n\t\t\t\t\tif (!isRecord(item)) continue;\n\t\t\t\t\tfor (const field of [\"id\", \"statusKey\", \"label\", \"priority\", \"placement\"]) {\n\t\t\t\t\t\tif (Object.hasOwn(item, field)) {\n\t\t\t\t\t\t\tconst fieldValue = item[field];\n\t\t\t\t\t\t\tconst valid =\n\t\t\t\t\t\t\t\tfield === \"id\" || field === \"statusKey\" || field === \"label\"\n\t\t\t\t\t\t\t\t\t? typeof fieldValue === \"string\"\n\t\t\t\t\t\t\t\t\t: field === \"priority\"\n\t\t\t\t\t\t\t\t\t\t? typeof fieldValue === \"number\" && Number.isFinite(fieldValue)\n\t\t\t\t\t\t\t\t\t\t: fieldValue === \"left\" || fieldValue === \"right\" || fieldValue === \"secondary\";\n\t\t\t\t\t\t\tif (!valid)\n\t\t\t\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\t\t\t\tcode: \"CFG-VALUE\",\n\t\t\t\t\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\t\t\t\t\tpath: `${path}[${index}].${field}`,\n\t\t\t\t\t\t\t\t\tmessage: \"invalid custom item field ignored\",\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfor (const field of Object.keys(item))\n\t\t\t\t\t\tif (![\"id\", \"statusKey\", \"label\", \"priority\", \"placement\"].includes(field))\n\t\t\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\t\t\tcode: \"CFG-VALUE\",\n\t\t\t\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\t\t\t\tpath: `${path}[${index}].${field}`,\n\t\t\t\t\t\t\t\tmessage: \"unknown custom item field ignored\",\n\t\t\t\t\t\t\t});\n\t\t\t\t}\n\t\t}\n\t\treturn result;\n\t};\n\treturn { accepted: walk(input, \"\"), diagnostics: boundedDiagnostics(diagnostics), paths };\n}\nfunction acceptedInput(input: unknown): unknown {\n\treturn validateConfigLayer(input).accepted;\n}\n\nexport function resolveConfigDetailed(sources: ConfigSources): {\n\treadonly config: NormalizedPiStyleConfig;\n\treadonly diagnostics: readonly ConfigDiagnostic[];\n\treadonly sources: Readonly<Record<string, string>>;\n} {\n\tconst diagnostics: ConfigDiagnostic[] = [];\n\tconst layerResults = new Map<string, ConfigLayerResult>();\n\tconst layers: readonly [string, unknown][] = [\n\t\t[\"global\", sources.global],\n\t\t[\"project\", sources.projectTrusted === false ? undefined : sources.project],\n\t\t[\"session\", sources.session],\n\t];\n\tfor (const [name, value] of layers) {\n\t\tconst result = validateConfigLayer(value);\n\t\tlayerResults.set(name, result);\n\t\tdiagnostics.push(...result.diagnostics);\n\t}\n\tconst defaults = sources.defaults ?? DEFAULT_CONFIG;\n\tlet merged: unknown = defaults;\n\tconst presetCandidates = [\n\t\t[\"session\", sources.session],\n\t\t[\"project\", sources.projectTrusted === false ? undefined : sources.project],\n\t\t[\"global\", sources.global],\n\t\t[\"default\", defaults],\n\t] as const;\n\tlet selectedPreset: unknown;\n\tfor (const [, source] of presetCandidates) {\n\t\tconst candidate = isRecord(source) ? source.preset : undefined;\n\t\tif (candidate === undefined) continue;\n\t\tif (typeof candidate === \"string\" && (PRESET_NAMES as readonly string[]).includes(candidate)) {\n\t\t\tselectedPreset = candidate;\n\t\t\tbreak;\n\t\t}\n\t\tdiagnostics.push({\n\t\t\tcode: \"CFG-ENUM\",\n\t\t\tlevel: \"warning\",\n\t\t\tpath: \"preset\",\n\t\t\tmessage: \"unsupported value; lower-precedence preset used\",\n\t\t});\n\t}\n\tmerged = merge(isRecord(merged) ? merged : {}, presetConfig(selectedPreset));\n\tfor (const name of [\"global\", \"project\"] as const)\n\t\tmerged = merge(isRecord(merged) ? merged : {}, layerResults.get(name)?.accepted);\n\tconst env = sources.environment ?? {};\n\tconst envPatch: PiStyleConfig = {};\n\tif (env.PI_STYLE_DISABLED === \"1\") envPatch.enabled = false;\n\tif (env.PI_STYLE_NERD_FONTS === \"1\" || env.PI_STYLE_NERD_FONTS === \"0\")\n\t\tenvPatch.theme = { nerdFonts: env.PI_STYLE_NERD_FONTS === \"1\" ? \"on\" : \"off\" };\n\tif (env.PI_STYLE_EDITOR && [\"native\", \"compact\", \"boxed\", \"dock\"].includes(env.PI_STYLE_EDITOR))\n\t\tenvPatch.editor = { style: env.PI_STYLE_EDITOR };\n\tif (env.PI_STYLE_OSC11 === \"1\" || env.PI_STYLE_OSC11 === \"0\")\n\t\tenvPatch.theme = { ...(envPatch.theme ?? {}), terminalBackgroundSync: env.PI_STYLE_OSC11 === \"1\" ? \"on\" : \"off\" };\n\tif (env.PI_STYLE_DEBUG === \"1\") envPatch.debug = true;\n\tif (env.PI_STYLE_STATUS === \"above\" || env.PI_STYLE_STATUS === \"below\") envPatch.placement = env.PI_STYLE_STATUS;\n\tif (env.PI_STYLE_STATUS === \"off\") envPatch.statusLine = { enabled: false };\n\tif (env.PI_STYLE_DISABLED !== undefined && env.PI_STYLE_DISABLED !== \"1\")\n\t\tdiagnostics.push({\n\t\t\tcode: \"CFG-ENV\",\n\t\t\tlevel: \"warning\",\n\t\t\tpath: \"PI_STYLE_DISABLED\",\n\t\t\tmessage: \"expected 1; override ignored\",\n\t\t});\n\tif (env.PI_STYLE_NERD_FONTS !== undefined && ![\"0\", \"1\"].includes(env.PI_STYLE_NERD_FONTS))\n\t\tdiagnostics.push({\n\t\t\tcode: \"CFG-ENV\",\n\t\t\tlevel: \"warning\",\n\t\t\tpath: \"PI_STYLE_NERD_FONTS\",\n\t\t\tmessage: \"expected 0 or 1; override ignored\",\n\t\t});\n\tif (env.PI_STYLE_STATUS !== undefined && ![\"above\", \"below\", \"off\"].includes(env.PI_STYLE_STATUS))\n\t\tdiagnostics.push({\n\t\t\tcode: \"CFG-ENV\",\n\t\t\tlevel: \"warning\",\n\t\t\tpath: \"PI_STYLE_STATUS\",\n\t\t\tmessage: \"expected above, below, or off; override ignored\",\n\t\t});\n\tif (env.PI_STYLE_EDITOR !== undefined && ![\"native\", \"compact\", \"boxed\", \"dock\"].includes(env.PI_STYLE_EDITOR))\n\t\tdiagnostics.push({\n\t\t\tcode: \"CFG-ENV\",\n\t\t\tlevel: \"warning\",\n\t\t\tpath: \"PI_STYLE_EDITOR\",\n\t\t\tmessage: \"unknown editor style; override ignored\",\n\t\t});\n\tfor (const [key, value] of Object.entries(env))\n\t\tif (\n\t\t\tvalue !== undefined &&\n\t\t\tkey.startsWith(\"PI_STYLE_\") &&\n\t\t\t![\n\t\t\t\t\"PI_STYLE_DISABLED\",\n\t\t\t\t\"PI_STYLE_NERD_FONTS\",\n\t\t\t\t\"PI_STYLE_EDITOR\",\n\t\t\t\t\"PI_STYLE_OSC11\",\n\t\t\t\t\"PI_STYLE_DEBUG\",\n\t\t\t\t\"PI_STYLE_STATUS\",\n\t\t\t].includes(key)\n\t\t)\n\t\t\tdiagnostics.push({\n\t\t\t\tcode: \"CFG-ENV\",\n\t\t\t\tlevel: \"warning\",\n\t\t\t\tpath: key,\n\t\t\t\tmessage: \"unsupported environment override ignored\",\n\t\t\t});\n\tmerged = merge(isRecord(merged) ? merged : {}, envPatch);\n\tmerged = merge(isRecord(merged) ? merged : {}, layerResults.get(\"session\")?.accepted);\n\tconst sourceMap: Record<string, string> = {};\n\tconst sourcePath = (value: unknown, prefix: string, sourceName: string) => {\n\t\tif (!isRecord(value)) return;\n\t\tfor (const [key, nested] of Object.entries(value)) {\n\t\t\tconst path = prefix ? `${prefix}.${key}` : key;\n\t\t\tif (validLeaf(path, nested)) {\n\t\t\t\tsourceMap[path] = sourceName;\n\t\t\t\tif (path === \"statusLine.customItems\" && Array.isArray(nested))\n\t\t\t\t\tfor (const [index, item] of nested.entries())\n\t\t\t\t\t\tif (isRecord(item))\n\t\t\t\t\t\t\tfor (const field of [\"id\", \"statusKey\", \"label\", \"priority\", \"placement\"])\n\t\t\t\t\t\t\t\tif (Object.hasOwn(item, field)) sourceMap[`${path}[${index}].${field}`] = sourceName;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (isRecord(nested)) sourcePath(nested, path, sourceName);\n\t\t}\n\t};\n\tsourcePath(defaults, \"\", \"default\");\n\tsourcePath(\n\t\tpresetConfig(selectedPreset),\n\t\t\"\",\n\t\t`preset:${typeof selectedPreset === \"string\" ? selectedPreset : \"default\"}`,\n\t);\n\tsourcePath(layerResults.get(\"global\")?.accepted, \"\", \"global\");\n\tif (sources.projectTrusted !== false) sourcePath(layerResults.get(\"project\")?.accepted, \"\", \"project\");\n\tsourcePath(envPatch, \"\", \"environment\");\n\tsourcePath(layerResults.get(\"session\")?.accepted, \"\", \"session\");\n\treturn { config: normalizeConfig(merged), diagnostics: boundedDiagnostics(diagnostics), sources: sourceMap };\n}\n","import { boundedDiagnostics, type ConfigDiagnostic } from \"./config-diagnostics.js\";\nimport { PI_STYLE_SCHEMA_VERSION } from \"./config-types.js\";\n\nfunction record(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport interface MigrationResult {\n\treadonly config: Record<string, unknown> | undefined;\n\treadonly diagnostics: readonly ConfigDiagnostic[];\n\treadonly readOnly: boolean;\n}\n\n/** Purely validates the durable envelope; v1 is identity and future data is read-only. */\nexport function migrateConfig(input: unknown, source = \"config\"): MigrationResult {\n\tif (!record(input))\n\t\treturn {\n\t\t\tconfig: undefined,\n\t\t\treadOnly: false,\n\t\t\tdiagnostics: boundedDiagnostics([\n\t\t\t\t{ code: \"CFG-001\", level: \"warning\", path: source, message: \"configuration must be an object; defaults used\" },\n\t\t\t]),\n\t\t};\n\tconst version = input.schemaVersion;\n\tif (version === undefined)\n\t\treturn {\n\t\t\tconfig: { ...input, schemaVersion: PI_STYLE_SCHEMA_VERSION },\n\t\t\treadOnly: false,\n\t\t\tdiagnostics: boundedDiagnostics([\n\t\t\t\t{\n\t\t\t\t\tcode: \"CFG-002\",\n\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\tpath: `${source}.schemaVersion`,\n\t\t\t\t\tmessage: \"missing schemaVersion accepted as v1-shaped input\",\n\t\t\t\t},\n\t\t\t]),\n\t\t};\n\tif (version !== PI_STYLE_SCHEMA_VERSION)\n\t\treturn {\n\t\t\tconfig: undefined,\n\t\t\treadOnly: true,\n\t\t\tdiagnostics: boundedDiagnostics([\n\t\t\t\t{\n\t\t\t\t\tcode: \"CFG-003\",\n\t\t\t\t\tlevel: \"error\",\n\t\t\t\t\tpath: `${source}.schemaVersion`,\n\t\t\t\t\tmessage: `unsupported schemaVersion ${String(version)}; ignored without rewrite`,\n\t\t\t\t},\n\t\t\t]),\n\t\t};\n\treturn { config: { ...input }, readOnly: false, diagnostics: [] };\n}\n","import type { ConfigDiagnostic } from \"../domain/config-diagnostics.js\";\nimport { migrateConfig } from \"../domain/config-migrations.js\";\n\nexport interface ConfigStoragePaths {\n\treadonly globalPath: string;\n\treadonly projectPath: string;\n}\nexport interface ConfigFilePort {\n\tread(path: string): Promise<string>;\n\twriteAtomic(path: string, content: string): Promise<void>;\n}\nexport interface ConfigRead {\n\treadonly value: unknown;\n\treadonly diagnostics: readonly ConfigDiagnostic[];\n\treadonly readOnly: boolean;\n}\n\nexport async function readScopedConfig(\n\tport: ConfigFilePort,\n\tpath: string,\n\tselectedNamespace = \"piStyle\",\n): Promise<ConfigRead> {\n\ttry {\n\t\tconst parsed = JSON.parse(await port.read(path)) as unknown;\n\t\tif (!record(parsed))\n\t\t\treturn {\n\t\t\t\tvalue: undefined,\n\t\t\t\treadOnly: true,\n\t\t\t\tdiagnostics: [{ code: \"CFG-001\", level: \"warning\", path, message: \"settings root must be an object\" }],\n\t\t\t};\n\t\tif (!Object.hasOwn(parsed, selectedNamespace)) return { value: undefined, readOnly: false, diagnostics: [] };\n\t\tconst result = migrateConfig(parsed[selectedNamespace], `${path}.${selectedNamespace}`);\n\t\treturn { value: result.config, diagnostics: result.diagnostics, readOnly: result.readOnly };\n\t} catch (error) {\n\t\tconst code =\n\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error ? (error as { code?: unknown }).code : undefined;\n\t\tif (code === \"ENOENT\") return { value: undefined, readOnly: false, diagnostics: [] };\n\t\treturn {\n\t\t\tvalue: undefined,\n\t\t\treadOnly: true,\n\t\t\tdiagnostics: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"CFG-IO\",\n\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\tpath,\n\t\t\t\t\tmessage: `settings unreadable; preserved without rewrite (${error instanceof Error ? error.message : \"invalid JSON\"})`,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction mergePatch(base: unknown, patch: unknown): unknown {\n\tif (!record(base) || !record(patch)) return patch;\n\tconst result: Record<string, unknown> = { ...base };\n\tfor (const [key, value] of Object.entries(patch)) result[key] = mergePatch(result[key], value);\n\treturn result;\n}\n\nconst writeLocks = new Map<string, Promise<void>>();\n\nexport async function writeScopedConfig(\n\tport: ConfigFilePort,\n\tpath: string,\n\tvalue: unknown,\n\tselectedNamespace = \"piStyle\",\n): Promise<void> {\n\tconst previous = writeLocks.get(path) ?? Promise.resolve();\n\tconst operation = previous.then(async () => {\n\t\tlet document: Record<string, unknown> = {};\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(await port.read(path)) as unknown;\n\t\t\tif (!record(parsed)) throw new Error(\"settings root must be an object\");\n\t\t\tdocument = parsed;\n\t\t} catch (error) {\n\t\t\tconst code =\n\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error ? (error as { code?: unknown }).code : undefined;\n\t\t\tif (code !== \"ENOENT\") throw new Error(`refusing to rewrite unreadable settings: ${path}`);\n\t\t}\n\t\tif (Object.hasOwn(document, selectedNamespace)) {\n\t\t\tconst existing = migrateConfig(document[selectedNamespace], `${path}.${selectedNamespace}`);\n\t\t\tif (existing.readOnly || !record(document[selectedNamespace]))\n\t\t\t\tthrow new Error(`refusing to rewrite protected ${selectedNamespace} namespace: ${path}`);\n\t\t}\n\t\tconst nextNamespace = mergePatch(document[selectedNamespace], value);\n\t\tawait port.writeAtomic(path, `${JSON.stringify({ ...document, [selectedNamespace]: nextNamespace }, null, 2)}\\n`);\n\t});\n\twriteLocks.set(path, operation);\n\ttry {\n\t\tawait operation;\n\t} finally {\n\t\tif (writeLocks.get(path) === operation) writeLocks.delete(path);\n\t}\n}\n","import { validateConfigLayer } from \"../domain/config-normalization.js\";\nimport type { NormalizedPiStyleConfig } from \"../domain/config-types.js\";\nimport { type ConfigFilePort, type ConfigStoragePaths, writeScopedConfig } from \"./config-storage.js\";\n\nexport type Mutation = Record<string, unknown>;\nexport interface CommandUi {\n\tselect(title: string, options: string[]): Promise<string | undefined>;\n\tnotify(message: string, type?: \"info\" | \"warning\" | \"error\"): void;\n}\nexport interface CommandHost {\n\treadonly ui: CommandUi;\n\treadonly cwd: string;\n\tisProjectTrusted(): boolean;\n}\nexport interface CommandApp {\n\treadonly config: NormalizedPiStyleConfig;\n\tapplySession(patch: Mutation): void;\n\tsetProjectTrusted?(trusted: boolean): void;\n\treload(): Promise<void>;\n\tdoctor(): Readonly<Record<string, unknown>>;\n}\n\nconst surfaces = new Set([\"status\", \"editor\", \"startup\", \"messages\", \"tools\"]);\nconst presets = [\"default\", \"minimal\", \"compact\", \"full\", \"ascii\", \"native\"];\nconst styles = [\"compact\", \"boxed\", \"dock\", \"native\"];\nconst frames = [\"auto\", \"halfblock\", \"line\", \"solid\", \"outline\", \"native\"];\nconst startupModes = [\"off\", \"compact\", \"overlay\"];\nconst allowedPaths = new Set([\n\t\"enabled\",\n\t\"preset\",\n\t\"placement\",\n\t\"startup.mode\",\n\t\"startup.showResources\",\n\t\"statusLine.enabled\",\n\t\"statusLine.separator\",\n\t\"statusLine.layout.left\",\n\t\"statusLine.layout.right\",\n\t\"statusLine.layout.secondary\",\n\t\"statusLine.disabledSegments\",\n\t\"statusLine.customItems\",\n\t\"statusLine.bottomMargin\",\n\t\"statusLine.contextBarWidth\",\n\t\"editor.enabled\",\n\t\"editor.style\",\n\t\"editor.frame\",\n\t\"editor.showMetadata\",\n\t\"messages.enabled\",\n\t\"messages.assistantPrefix\",\n\t\"messages.specialBlocks\",\n\t\"messages.hideThinkingLabel\",\n\t\"tools.enabled\",\n\t\"tools.style\",\n\t\"tools.maxCollapsedLines\",\n\t\"tools.maxExpandedLines\",\n\t\"tools.dimOutput\",\n\t\"tools.showElapsed\",\n\t\"theme.nerdFonts\",\n\t\"theme.terminalBackgroundSync\",\n\t\"theme.colors\",\n\t\"theme.glyphs\",\n\t\"compatibility.allowSafePatches\",\n\t\"compatibility.allowCorePatches\",\n\t\"compatibility.preferExistingEditor\",\n\t\"compatibility.preferExistingFooter\",\n\t\"debug\",\n]);\nfunction validatePathValue(path: string, value: unknown): boolean {\n\tif (!allowedPaths.has(path)) return false;\n\tif (\n\t\t[\n\t\t\t\"enabled\",\n\t\t\t\"startup.showResources\",\n\t\t\t\"statusLine.enabled\",\n\t\t\t\"editor.enabled\",\n\t\t\t\"editor.showMetadata\",\n\t\t\t\"messages.enabled\",\n\t\t\t\"messages.assistantPrefix\",\n\t\t\t\"messages.specialBlocks\",\n\t\t\t\"messages.hideThinkingLabel\",\n\t\t\t\"tools.enabled\",\n\t\t\t\"tools.showElapsed\",\n\t\t\t\"tools.dimOutput\",\n\t\t\t\"compatibility.allowSafePatches\",\n\t\t\t\"compatibility.allowCorePatches\",\n\t\t\t\"compatibility.preferExistingEditor\",\n\t\t\t\"compatibility.preferExistingFooter\",\n\t\t\t\"debug\",\n\t\t].includes(path)\n\t)\n\t\treturn typeof value === \"boolean\";\n\tif (path === \"preset\") return typeof value === \"string\" && presets.includes(value);\n\tif (path === \"placement\") return value === \"above\" || value === \"below\";\n\tif (path === \"startup.mode\") return typeof value === \"string\" && startupModes.includes(value);\n\tif (path === \"editor.style\") return typeof value === \"string\" && styles.includes(value);\n\tif (path === \"editor.frame\") return typeof value === \"string\" && frames.includes(value);\n\tif ([\"theme.nerdFonts\", \"theme.terminalBackgroundSync\", \"statusLine.separator\", \"tools.style\"].includes(path))\n\t\treturn typeof value === \"string\";\n\tif (path === \"tools.maxCollapsedLines\" || path === \"tools.maxExpandedLines\")\n\t\treturn typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\tif (path === \"statusLine.bottomMargin\" || path === \"statusLine.contextBarWidth\")\n\t\treturn typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\tif (path.endsWith(\".colors\") || path.endsWith(\".glyphs\"))\n\t\treturn (\n\t\t\ttypeof value === \"object\" &&\n\t\t\tvalue !== null &&\n\t\t\t!Array.isArray(value) &&\n\t\t\tObject.values(value).every((item) => typeof item === \"string\")\n\t\t);\n\tif (path.includes(\"layout.\") || path === \"statusLine.disabledSegments\")\n\t\treturn Array.isArray(value) && value.every((item) => typeof item === \"string\");\n\treturn (\n\t\tpath === \"statusLine.customItems\" &&\n\t\tvalidateConfigLayer({ statusLine: { customItems: value } }).diagnostics.length === 0\n\t);\n}\nfunction validateMutation(patch: Mutation, prefix = \"\"): boolean {\n\treturn Object.entries(patch).every(([key, value]) => {\n\t\tconst path = prefix ? `${prefix}.${key}` : key;\n\t\tif (\n\t\t\t[\n\t\t\t\t\"theme.colors\",\n\t\t\t\t\"theme.glyphs\",\n\t\t\t\t\"statusLine.layout.left\",\n\t\t\t\t\"statusLine.layout.right\",\n\t\t\t\t\"statusLine.layout.secondary\",\n\t\t\t\t\"statusLine.disabledSegments\",\n\t\t\t\t\"statusLine.customItems\",\n\t\t\t].includes(path)\n\t\t)\n\t\t\treturn validatePathValue(path, value);\n\t\tif (typeof value === \"object\" && value !== null && !Array.isArray(value))\n\t\t\treturn Object.keys(value).length > 0 && validateMutation(value as Mutation, path);\n\t\treturn validatePathValue(path, value);\n\t});\n}\nfunction sanitizeMutation(patch: Mutation): Mutation | undefined {\n\treturn validateMutation(patch) ? patch : undefined;\n}\n\nfunction mutation(parts: readonly string[]): Mutation | undefined {\n\tif (parts[0] === \"set\" && parts[1] && parts[2]) {\n\t\ttry {\n\t\t\tconst value = JSON.parse(parts.slice(2).join(\" \")) as unknown;\n\t\t\tconst patch: Mutation = {};\n\t\t\tlet cursor = patch;\n\t\t\tconst keys = parts[1].split(\".\");\n\t\t\tfor (const key of keys.slice(0, -1)) {\n\t\t\t\tconst next = cursor[key];\n\t\t\t\tif (typeof next === \"object\" && next !== null && !Array.isArray(next)) cursor = next as Mutation;\n\t\t\t\telse {\n\t\t\t\t\tcursor[key] = {};\n\t\t\t\t\tcursor = cursor[key] as Mutation;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcursor[keys.at(-1) as string] = value;\n\t\t\treturn sanitizeMutation(patch);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\tconst [action, value, extra] = parts;\n\tif (action === \"on\" || action === \"off\") return { enabled: action === \"on\" };\n\tif (action === \"preset\" && value && presets.includes(value)) return { preset: value };\n\tif (action === \"placement\" && (value === \"above\" || value === \"below\")) return { placement: value };\n\tif (action === \"editor\" && value && styles.includes(value) && (!extra || frames.includes(extra)))\n\t\treturn { editor: { style: value, ...(extra ? { frame: extra } : {}) } };\n\tif (action === \"startup\" && value && startupModes.includes(value)) return { startup: { mode: value } };\n\tif (action === \"surface\" && value && surfaces.has(value) && (extra === \"on\" || extra === \"off\")) {\n\t\tif (value === \"startup\") return { startup: { mode: extra === \"on\" ? \"compact\" : \"off\" } };\n\t\treturn { [value === \"status\" ? \"statusLine\" : value]: { enabled: extra === \"on\" } };\n\t}\n\treturn undefined;\n}\n\nexport async function executePiStyleCommand(\n\targs: string,\n\thost: CommandHost,\n\tapp: CommandApp,\n\tstorage: { readonly port: ConfigFilePort; readonly paths: ConfigStoragePaths },\n): Promise<void> {\n\tconst parts = args.trim().split(/\\s+/).filter(Boolean);\n\tconst [action, scope, ...rest] = parts;\n\tif (!action) {\n\t\thost.ui.notify(\n\t\t\t`pi-style preset ${app.config.preset}; status ${app.config.statusLine.enabled ? \"on\" : \"off\"}`,\n\t\t\t\"info\",\n\t\t);\n\t\treturn;\n\t}\n\tif (action === \"reload\") {\n\t\tawait app.reload();\n\t\treturn;\n\t}\n\tif (action === \"doctor\") {\n\t\thost.ui.notify(JSON.stringify(app.doctor()), \"info\");\n\t\treturn;\n\t}\n\tif (action === \"persist\") {\n\t\tif (scope !== \"global\" && scope !== \"project\") {\n\t\t\thost.ui.notify(\"persistence requires explicit global or project scope\", \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tif (scope === \"project\" && !host.isProjectTrusted()) {\n\t\t\thost.ui.notify(\"pi-style project persistence requires a trusted project\", \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tconst patch = mutation(rest);\n\t\tif (!patch) {\n\t\t\thost.ui.notify(\"invalid pi-style mutation or value\", \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tconst sanitized = sanitizeMutation(patch);\n\t\tif (!sanitized) {\n\t\t\thost.ui.notify(\"mutation contains fields that cannot be persisted\", \"warning\");\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tawait writeScopedConfig(\n\t\t\t\tstorage.port,\n\t\t\t\tscope === \"global\" ? storage.paths.globalPath : storage.paths.projectPath,\n\t\t\t\tsanitized,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\thost.ui.notify(\n\t\t\t\t`pi-style settings write failed: ${error instanceof Error ? error.message : \"unknown error\"}`,\n\t\t\t\t\"error\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tapp.applySession(patch);\n\t\tif (\n\t\t\t(patch.messages as Record<string, unknown> | undefined)?.enabled === true ||\n\t\t\t(patch.tools as Record<string, unknown> | undefined)?.enabled === true\n\t\t)\n\t\t\thost.ui.notify(\"desired Tier C state stored; awaiting session authorization\", \"info\");\n\t\treturn;\n\t}\n\tconst patch = mutation(parts);\n\tif (patch) app.applySession(patch);\n\telse if (action === \"preset\" && !scope) {\n\t\tconst selected = await host.ui.select(\"pi-style preset\", presets);\n\t\tif (selected) app.applySession({ preset: selected });\n\t} else host.ui.notify(\"invalid pi-style command or value\", \"warning\");\n}\n","import type { CommandApp, CommandHost } from \"./command-service.js\";\nimport { executePiStyleCommand } from \"./command-service.js\";\nimport type { ConfigFilePort, ConfigStoragePaths } from \"./config-storage.js\";\n\nexport function runCommand(\n\targs: string,\n\thost: CommandHost,\n\tapp: CommandApp,\n\tstorage: { readonly port: ConfigFilePort; readonly paths: ConfigStoragePaths },\n): Promise<void> {\n\treturn executePiStyleCommand(args, host, app, storage);\n}\n","import { mkdir, readFile, rename, unlink, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"@earendil-works/pi-coding-agent\";\nimport type { ConfigFilePort, ConfigStoragePaths } from \"../app/config-storage.js\";\n\nconst locks = new Map<string, Promise<void>>();\n\nfunction serialize(path: string, operation: () => Promise<void>): Promise<void> {\n\tconst previous = locks.get(path) ?? Promise.resolve();\n\tconst current = previous.catch(() => undefined).then(operation);\n\tlocks.set(path, current);\n\treturn current.finally(() => {\n\t\tif (locks.get(path) === current) locks.delete(path);\n\t});\n}\n\nexport interface ConfigHostFs {\n\treadonly mkdir?: typeof mkdir;\n\treadonly readFile?: typeof readFile;\n\treadonly rename?: typeof rename;\n\treadonly unlink?: typeof unlink;\n\treadonly writeFile?: typeof writeFile;\n}\n\nexport function createPiConfigFilePort(fs: ConfigHostFs = {}): ConfigFilePort {\n\tconst fsMkdir = fs.mkdir ?? mkdir;\n\tconst fsReadFile = fs.readFile ?? readFile;\n\tconst fsRename = fs.rename ?? rename;\n\tconst fsUnlink = fs.unlink ?? unlink;\n\tconst fsWriteFile = fs.writeFile ?? writeFile;\n\treturn {\n\t\tread: (path) => fsReadFile(path, \"utf8\"),\n\t\twriteAtomic: async (path, content) =>\n\t\t\tserialize(path, async () => {\n\t\t\t\tawait fsMkdir(dirname(path), { recursive: true });\n\t\t\t\tconst temporary = `${path}.pi-style-${process.pid}-${Date.now()}.tmp`;\n\t\t\t\ttry {\n\t\t\t\t\tawait fsWriteFile(temporary, content, { mode: 0o600 });\n\t\t\t\t\tawait fsRename(temporary, path);\n\t\t\t\t} finally {\n\t\t\t\t\tawait fsUnlink(temporary).catch(() => undefined);\n\t\t\t\t}\n\t\t\t}),\n\t};\n}\n\nexport function defaultStoragePaths(cwd: string, overrides: Partial<ConfigStoragePaths> = {}): ConfigStoragePaths {\n\treturn {\n\t\tglobalPath: overrides.globalPath ?? join(getAgentDir(), \"settings.json\"),\n\t\tprojectPath: overrides.projectPath ?? join(cwd, CONFIG_DIR_NAME, \"settings.json\"),\n\t};\n}\n","import type { ExtensionAPI, ExtensionCommandContext } from \"@earendil-works/pi-coding-agent\";\nimport type { CommandApp } from \"../app/command-service.js\";\nimport { runCommand } from \"../app/commands.js\";\nimport { createPiConfigFilePort, defaultStoragePaths } from \"./config-host.js\";\n\nexport function registerPiStyleCommand(pi: ExtensionAPI, app: CommandApp): void {\n\tpi.registerCommand(\"pi-style\", {\n\t\tdescription: \"Configure pi-style for this session\",\n\t\thandler: async (args: string, ctx: ExtensionCommandContext) => {\n\t\t\tconst cwd = ctx.cwd ?? process.cwd();\n\t\t\tawait runCommand(args, { ui: ctx.ui, cwd, isProjectTrusted: ctx.isProjectTrusted }, app, {\n\t\t\t\tport: createPiConfigFilePort(),\n\t\t\t\tpaths: defaultStoragePaths(cwd),\n\t\t\t});\n\t\t},\n\t});\n}\n","import type { ExtensionAPI, ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { type KeyId, matchesKey } from \"@earendil-works/pi-tui\";\nimport type { ConfigFilePort } from \"../app/config-storage.js\";\nimport { createPiStyleApp, type PiStyleApp } from \"../app/index.js\";\nimport { resolveTheme } from \"../domain/theme.js\";\nimport { setSpecialBlockTheme } from \"../features/messages/special-blocks.js\";\nimport { resetBashTreeRegistry } from \"../features/tools/boxed/bash.js\";\nimport { resetBatchRegistry } from \"../features/tools/boxed/batch.js\";\nimport { resetGrepRegistry } from \"../features/tools/boxed/grep.js\";\nimport {\n\tsetToolsRenderConfig,\n\tstopAllElapsedTickers,\n\ttype ToolsRenderConfig,\n} from \"../features/tools/boxed/session-config.js\";\nimport { createCompatibilityCoordinator } from \"./compatibility-coordinator.js\";\nimport {\n\ttype CompatibilityCleanupResult,\n\ttype CompatibilityProbeReport,\n\tdisposePiCompatibilityProbe,\n} from \"./compatibility-probe.js\";\nimport { createPiConfigFilePort, defaultStoragePaths } from \"./config-host.js\";\nimport { createConfigSourceAdapter, readSessionAuthorization } from \"./config-session.js\";\nimport { buildOperationalState } from \"./operational-state.js\";\nimport { collectToolDetails } from \"./startup-resources.js\";\n\nexport type CompatibilityTestHooks = {\n\tdispose?: (report: CompatibilityProbeReport) => CompatibilityCleanupResult;\n\tfilePort?: ConfigFilePort;\n\tpaths?: (cwd: string) => { globalPath: string; projectPath: string };\n\t/** Test-only capability seam; Pi's ExtensionContext does not provide a Git runner. */\n\tgitRunner?: import(\"../domain/providers.js\").GitCommandRunner;\n\t/** Override the thinking-cycle key binding consumed to suppress Pi's status toast. */\n\tthinkingCycleKey?: string;\n};\n\nconst THINKING_CYCLE = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\n\nexport function createPiStyleSessionCoordinator(pi: ExtensionAPI, hooks: CompatibilityTestHooks = {}) {\n\tconst filePort = hooks.filePort ?? createPiConfigFilePort();\n\tconst gitRunner =\n\t\thooks.gitRunner ??\n\t\t({\n\t\t\trun: async (args, commandCwd, timeoutMs, signal) => {\n\t\t\t\tconst result = await pi.exec(\"git\", [...args], {\n\t\t\t\t\tcwd: commandCwd,\n\t\t\t\t\ttimeout: timeoutMs,\n\t\t\t\t\t...(signal ? { signal } : {}),\n\t\t\t\t});\n\t\t\t\treturn { stdout: result.stdout, stderr: result.stderr, code: result.code };\n\t\t\t},\n\t\t} satisfies import(\"../domain/providers.js\").GitCommandRunner);\n\tlet cwd = process.cwd();\n\tlet active = false;\n\tlet tuiSession = false;\n\tlet terminalInputUnsubscribe: (() => void) | undefined;\n\tlet sessionTheme: unknown;\n\tlet sessionUi: import(\"@earendil-works/pi-coding-agent\").ExtensionUIContext | undefined;\n\tconst source = createConfigSourceAdapter(\n\t\tpi,\n\t\tfilePort,\n\t\thooks.paths ?? ((sessionCwd) => defaultStoragePaths(sessionCwd)),\n\t);\n\tconst compatibility = createCompatibilityCoordinator(\n\t\t(report) => hooks.dispose?.(report) ?? disposePiCompatibilityProbe(report),\n\t);\n\t// Initial read may be empty in real Pi (flag values apply after extension load);\n\t// start() re-reads and re-captures at every session_start.\n\tlet authorization = readSessionAuthorization(pi);\n\tlet productGate: \"omitted\" | \"allow\" | \"deny\" = \"omitted\";\n\tconst syncOperational = (config: import(\"../domain/config-types.js\").NormalizedPiStyleConfig) => {\n\t\tapp.setOperationalState(\n\t\t\tbuildOperationalState(\n\t\t\t\tconfig,\n\t\t\t\tauthorization,\n\t\t\t\tcompatibility,\n\t\t\t\tapp.runtime.current?.installationState,\n\t\t\t\tapp.productPolicy.corePatchGate,\n\t\t\t),\n\t\t);\n\t};\n\t/** Render-scoped tool config: line budgets + the resolved open-tree glyph. */\n\tconst applyToolsRenderConfig = (config: import(\"../domain/config-types.js\").NormalizedPiStyleConfig) => {\n\t\tsetToolsRenderConfig({\n\t\t\t...config.tools,\n\t\t\tbatchOpenGlyph: resolveTheme(sessionTheme as never, config, process.env).glyph(\"batchOpen\"),\n\t\t\tnerdFonts: resolveTheme(sessionTheme as never, config, process.env).mode === \"nerd\",\n\t\t} satisfies ToolsRenderConfig);\n\t};\n\t/**\n\t * Hide Pi's \"Thinking...\" placeholder label: an empty label renders zero\n\t * lines, so the thinking block leaves no trace while content stays hidden.\n\t * Passing undefined restores the default label.\n\t */\n\tconst applyMessagesConfig = (config: import(\"../domain/config-types.js\").NormalizedPiStyleConfig) => {\n\t\tsessionUi?.setHiddenThinkingLabel?.(config.messages.hideThinkingLabel ? \"\" : undefined);\n\t};\n\tconst app: PiStyleApp = createPiStyleApp(\n\t\tundefined,\n\t\t{\n\t\t\tload: async (trusted) => {\n\t\t\t\tsource.setSession(cwd, trusted);\n\t\t\t\treturn source.load();\n\t\t\t},\n\t\t},\n\t\t(config) => {\n\t\t\tproductGate = app.productPolicy.corePatchGate;\n\t\t\tif (!active) return;\n\t\t\t// Apply render-scoped tool config live so `/pi-style set tools.*` takes\n\t\t\t// effect immediately (line budgets, dimOutput, open-tree glyph, …).\n\t\t\tapplyToolsRenderConfig(config);\n\t\t\tapplyMessagesConfig(config);\n\t\t\tif (compatibility.report) {\n\t\t\t\tconst cleanup = compatibility.dispose();\n\t\t\t\tif (!cleanup.complete) {\n\t\t\t\t\tsyncOperational(config);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcompatibility.install(config, tuiSession, productGate);\n\t\t\tsyncOperational(config);\n\t\t},\n\t);\n\n\treturn {\n\t\tapp,\n\t\tasync start(event: { reason: string }, ctx: ExtensionContext): Promise<void> {\n\t\t\t// Authorization is session-bound: Pi applies extension flag values only after\n\t\t\t// extension modules finish loading, so flags must be read here (session_start),\n\t\t\t// never at coordinator creation time.\n\t\t\tauthorization = readSessionAuthorization(pi);\n\t\t\tcompatibility.captureAuthorization(\n\t\t\t\tauthorization.core,\n\t\t\t\tauthorization.assistant,\n\t\t\t\tauthorization.specialBlocks,\n\t\t\t\tauthorization.tools,\n\t\t\t\tauthorization.ascii,\n\t\t\t);\n\t\t\t// Replacement is failure-atomic: retain the current runtime until\n\t\t\t// compatibility ownership has been restored successfully.\n\t\t\tif (compatibility.report) {\n\t\t\t\tconst cleanup = compatibility.dispose();\n\t\t\t\tif (!cleanup.complete) {\n\t\t\t\t\tsyncOperational(app.config);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (app.runtime.current) app.sessionShutdown();\n\t\t\tcwd = ctx.cwd ?? process.cwd();\n\t\t\ttuiSession = ctx.mode === \"tui\";\n\t\t\tapp.setProjectTrusted(ctx.isProjectTrusted());\n\t\t\tsource.setSession(cwd, ctx.isProjectTrusted());\n\t\t\t// Drop any batch state carried over from the previous session (Pi renders\n\t\t\t// the restored chat between session_shutdown and the next session_start).\n\t\t\tresetBatchRegistry();\n\t\t\tresetGrepRegistry();\n\t\t\tresetBashTreeRegistry();\n\t\t\t// Stop any 1s elapsed re-render ticker left by a tool that was still\n\t\t\t// running when the session ended.\n\t\t\tstopAllElapsedTickers();\n\t\t\tactive = false;\n\t\t\tawait app.reload();\n\t\t\tproductGate = app.productPolicy.corePatchGate;\n\t\t\tactive = true;\n\t\t\tcompatibility.install(app.config, ctx.mode === \"tui\", productGate);\n\t\t\t// Session-scoped render configuration for the boxed tool/message surfaces.\n\t\t\t// Populated once per session (never inside render).\n\t\t\tsessionTheme = ctx.ui?.theme as never;\n\t\t\tsessionUi = ctx.ui as import(\"@earendil-works/pi-coding-agent\").ExtensionUIContext | undefined;\n\t\t\tapplyToolsRenderConfig(app.config);\n\t\t\tapplyMessagesConfig(app.config);\n\t\t\tif (ctx.ui?.theme) setSpecialBlockTheme(ctx.ui.theme as never);\n\t\t\tconst toolDetails = collectToolDetails(pi.getActiveTools?.(), pi.getAllTools?.());\n\t\t\tapp.sessionStart(\n\t\t\t\t{\n\t\t\t\t\tmode: ctx.mode,\n\t\t\t\t\thasUI: ctx.hasUI,\n\t\t\t\t\t...(ctx.ui ? { ui: ctx.ui } : {}),\n\t\t\t\t\t...(ctx.cwd ? { cwd: ctx.cwd } : {}),\n\t\t\t\t\t...(ctx.model\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tmodel: {\n\t\t\t\t\t\t\t\t\tid: ctx.model.id,\n\t\t\t\t\t\t\t\t\tname: ctx.model.name,\n\t\t\t\t\t\t\t\t\tprovider: ctx.model.provider,\n\t\t\t\t\t\t\t\t\treasoning: ctx.model.reasoning,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(ctx.thinkingLevel ? { thinkingLevel: ctx.thinkingLevel } : {}),\n\t\t\t\t\tgetContextUsage: ctx.getContextUsage,\n\t\t\t\t\tprojectTrusted: ctx.isProjectTrusted(),\n\t\t\t\t\tgitRunner,\n\t\t\t\t},\n\t\t\t\tevent.reason as \"startup\" | \"reload\" | \"new\" | \"resume\" | \"fork\",\n\t\t\t\t{\n\t\t\t\t\t...(typeof ctx.getSystemPrompt === \"function\" ? { systemPrompt: ctx.getSystemPrompt() } : {}),\n\t\t\t\t\t...(toolDetails ? { toolDetails } : {}),\n\t\t\t\t\t...(ctx.scopedModels && ctx.scopedModels.length > 0 ? { models: ctx.scopedModels.length } : {}),\n\t\t\t\t},\n\t\t\t);\n\t\t\tterminalInputUnsubscribe?.();\n\t\t\tterminalInputUnsubscribe = undefined;\n\t\t\t// Consume Pi's default thinking-cycle key and re-issue it through the public API so\n\t\t\t// the footer shows the level without Pi's transient \"Thinking level: X\" status toast.\n\t\t\tconst cycleKey = hooks.thinkingCycleKey ?? \"shift+tab\";\n\t\t\tif (ctx.mode === \"tui\" && ctx.ui?.onTerminalInput) {\n\t\t\t\tterminalInputUnsubscribe = ctx.ui.onTerminalInput((data) => {\n\t\t\t\t\tif (!matchesKey(data, cycleKey as KeyId)) return undefined;\n\t\t\t\t\tconst current = pi.getThinkingLevel?.();\n\t\t\t\t\tconst index = Math.max(0, THINKING_CYCLE.indexOf(current as (typeof THINKING_CYCLE)[number]));\n\t\t\t\t\tconst next = THINKING_CYCLE[(index + 1) % THINKING_CYCLE.length];\n\t\t\t\t\tpi.setThinkingLevel?.(next as never);\n\t\t\t\t\treturn { consume: true };\n\t\t\t\t});\n\t\t\t}\n\t\t\tsyncOperational(app.config);\n\t\t},\n\t\tshutdown(): void {\n\t\t\tactive = false;\n\t\t\ttuiSession = false;\n\t\t\tterminalInputUnsubscribe?.();\n\t\t\tterminalInputUnsubscribe = undefined;\n\t\t\tresetBatchRegistry();\n\t\t\tresetGrepRegistry();\n\t\t\tresetBashTreeRegistry();\n\t\t\tstopAllElapsedTickers();\n\t\t\tapp.sessionShutdown();\n\t\t\t// Tier C prototype patches stay installed across session switches. Pi renders\n\t\t\t// the restored chat (renderBeforeBind) AFTER session_shutdown but BEFORE the\n\t\t\t// next session_start, so disposing here would rebuild the resumed tool and\n\t\t\t// special-block surfaces with native prototypes and they would never be\n\t\t\t// re-decorated (their boxed output is derived once at updateDisplay time and\n\t\t\t// cached; a later frame render does not re-invoke the renderer selectors).\n\t\t\t// The next start() disposes this report (restoring the native identities)\n\t\t\t// and reinstalls before any new render. On process exit (reason \"quit\") the\n\t\t\t// terminal is torn down immediately after, so retained patches are harmless.\n\t\t},\n\t};\n}\n","import type { ConfigDiagnostic } from \"../domain/config-diagnostics.js\";\nimport type { NormalizedPiStyleConfig } from \"../domain/config-types.js\";\n\nexport interface DoctorOperationalState {\n\treadonly compatibility?: Readonly<Record<string, unknown>>;\n\treadonly provider?: Readonly<Record<string, unknown>>;\n\treadonly installations?: Readonly<Record<string, unknown>>;\n\treadonly authorization?: Readonly<Record<string, unknown>>;\n}\n\nexport interface DoctorState {\n\treadonly config: NormalizedPiStyleConfig;\n\treadonly diagnostics: readonly ConfigDiagnostic[];\n\treadonly sources?: Readonly<Record<string, string>>;\n\treadonly surfaces: Readonly<Record<string, unknown>>;\n\treadonly piVersion?: string;\n\treadonly compatibility?: string;\n\treadonly operational?: DoctorOperationalState;\n}\n\nexport function createDoctor(state: DoctorState): Readonly<Record<string, unknown>> {\n\treturn Object.freeze({\n\t\tconfig: Object.freeze({\n\t\t\tpreset: state.config.preset,\n\t\t\tenabled: state.config.enabled,\n\t\t\tplacement: state.config.placement,\n\t\t\tstatusLine: state.config.statusLine.enabled ? \"enabled\" : \"disabled\",\n\t\t\teditor: state.config.editor.enabled ? \"enabled\" : \"disabled\",\n\t\t\tstartup: state.config.startup.mode,\n\t\t}),\n\t\tdiagnostics: state.diagnostics,\n\t\tsources: state.sources ?? {},\n\t\tsurfaces: state.surfaces,\n\t\t...(state.piVersion ? { piVersion: state.piVersion } : {}),\n\t\t...(state.operational?.compatibility && typeof state.operational.compatibility.piVersion === \"string\"\n\t\t\t? { piVersion: state.operational.compatibility.piVersion }\n\t\t\t: {}),\n\t\t...(state.operational?.compatibility && typeof state.operational.compatibility.versionRange === \"string\"\n\t\t\t? { piVersionRange: state.operational.compatibility.versionRange }\n\t\t\t: {}),\n\t\t...(state.compatibility ? { compatibility: state.compatibility } : {}),\n\t\t...(state.operational\n\t\t\t? {\n\t\t\t\t\toperational: Object.freeze({\n\t\t\t\t\t\t...(state.operational.compatibility ? { compatibility: state.operational.compatibility } : {}),\n\t\t\t\t\t\t...(state.operational.provider ? { provider: state.operational.provider } : {}),\n\t\t\t\t\t\t...(state.operational.installations ? { installations: state.operational.installations } : {}),\n\t\t\t\t\t\t...(state.operational.authorization ? { authorization: state.operational.authorization } : {}),\n\t\t\t\t\t}),\n\t\t\t\t}\n\t\t\t: {}),\n\t});\n}\n","import type { NormalizedPiStyleConfig } from \"./config-types.js\";\n\nexport type ConfigImpact = \"none\" | \"status\" | \"editor\" | \"startup\" | \"compatibility\" | \"all\";\n\nexport interface ConfigDiff {\n\treadonly changed: readonly string[];\n\treadonly impacts: readonly ConfigImpact[];\n}\n\nexport function diffConfig(previous: NormalizedPiStyleConfig, next: NormalizedPiStyleConfig): ConfigDiff {\n\tconst changed: string[] = [];\n\tconst impacts = new Set<ConfigImpact>();\n\tconst compare = (key: string, before: unknown, after: unknown, impact: ConfigImpact) => {\n\t\tif (JSON.stringify(before) === JSON.stringify(after)) return;\n\t\tchanged.push(key);\n\t\timpacts.add(impact);\n\t};\n\tcompare(\"enabled\", previous.enabled, next.enabled, \"all\");\n\tcompare(\"statusLine\", previous.statusLine, next.statusLine, \"status\");\n\tcompare(\"placement\", previous.placement, next.placement, \"status\");\n\tcompare(\"editor\", previous.editor, next.editor, \"editor\");\n\tcompare(\"startup\", previous.startup, next.startup, \"startup\");\n\tcompare(\"messages\", previous.messages, next.messages, \"compatibility\");\n\tcompare(\"tools\", previous.tools, next.tools, \"compatibility\");\n\tcompare(\"theme\", previous.theme, next.theme, \"all\");\n\tcompare(\"compatibility\", previous.compatibility, next.compatibility, \"compatibility\");\n\tif (impacts.has(\"all\"))\n\t\treturn Object.freeze({ changed: Object.freeze(changed), impacts: Object.freeze([\"all\"] as const) });\n\treturn Object.freeze({ changed: Object.freeze(changed), impacts: Object.freeze([...impacts]) });\n}\n","import type { ResolvedTheme, SemanticToken } from \"./theme.js\";\n\nexport const STATUS_SEGMENT_IDS = [\n\t\"pi\",\n\t\"model\",\n\t\"thinking\",\n\t\"model_effort\",\n\t\"path\",\n\t\"git\",\n\t\"context_pct\",\n\t\"context_bar\",\n\t\"context_total\",\n\t\"auto_compact\",\n\t\"token_in\",\n\t\"token_out\",\n\t\"cache_read\",\n\t\"cache_write\",\n\t\"cost\",\n\t\"time_spent\",\n\t\"time\",\n\t\"hostname\",\n\t\"session\",\n\t\"extension_statuses\",\n] as const;\nexport type StatusSegmentId = (typeof STATUS_SEGMENT_IDS)[number] | (string & {});\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\nexport type ContextState = \"low\" | \"medium\" | \"high\" | \"critical\";\n\nexport interface GitSnapshot {\n\treadonly available: boolean;\n\treadonly branch: string | null;\n\treadonly staged: number;\n\treadonly unstaged: number;\n\treadonly untracked: number;\n\treadonly ahead?: number;\n\treadonly behind?: number;\n\treadonly refreshing: boolean;\n\treadonly error?: string;\n}\n\nexport interface ContextSnapshot {\n\treadonly currentTokens?: number;\n\treadonly windowTokens?: number;\n\treadonly percent?: number;\n\treadonly state?: ContextState;\n\treadonly autoCompacting?: boolean;\n\treadonly customCompaction?: string;\n}\n\nexport interface UsageSnapshot {\n\treadonly inputTokens: number;\n\treadonly outputTokens: number;\n\treadonly cacheReadTokens: number;\n\treadonly cacheWriteTokens: number;\n\treadonly cost?: number;\n\treadonly currency?: string;\n\treadonly subscriptionMode?: \"api\" | \"subscription\" | \"unknown\";\n\treadonly streaming: boolean;\n}\n\nexport interface ExtensionStatus {\n\treadonly key: string;\n\treadonly value: string;\n}\n\nexport interface StatusSnapshot {\n\treadonly model?: string;\n\t/** Provider name for the active model (e.g. `deepseek`), when known. */\n\treadonly provider?: string;\n\t/** Whether the active model supports reasoning/thinking levels, when known. */\n\treadonly reasoning?: boolean;\n\treadonly thinkingLevel?: ThinkingLevel;\n\treadonly cwd?: string;\n\treadonly git?: GitSnapshot;\n\treadonly context?: ContextSnapshot;\n\treadonly usage?: UsageSnapshot;\n\treadonly hostname?: string;\n\treadonly sessionName?: string | undefined;\n\treadonly sessionId?: string | undefined;\n\treadonly sessionStartedAt?: number;\n\treadonly extensionStatuses?: readonly ExtensionStatus[];\n}\n\nexport interface StatusSegmentOptions {\n\treadonly disabled?: boolean;\n\treadonly label?: string;\n\treadonly [key: string]: unknown;\n}\n\nexport interface StatusCustomItem {\n\treadonly id: string;\n\treadonly statusKey: string;\n\treadonly label?: string;\n\treadonly priority?: number;\n\treadonly placement?: \"left\" | \"right\" | \"secondary\";\n}\n\nexport interface SegmentContext {\n\treadonly snapshot: StatusSnapshot;\n\treadonly theme: ResolvedTheme;\n\treadonly options: Readonly<Record<string, StatusSegmentOptions | undefined>>;\n\treadonly width: number;\n}\n\nexport interface SegmentRenderResult {\n\treadonly visible: boolean;\n\treadonly content: string;\n\treadonly compactContent?: string;\n\treadonly minWidth?: number;\n\treadonly truncatable?: boolean;\n}\n\nexport interface StatusSegment {\n\treadonly id: StatusSegmentId;\n\treadonly defaultPriority: number;\n\treadonly essential?: boolean;\n\treadonly overflow?: \"primary\" | \"secondary\" | \"drop\";\n\trender(context: SegmentContext): SegmentRenderResult;\n}\n\nexport interface StatusLayout {\n\treadonly left: readonly StatusSegmentId[];\n\treadonly right: readonly StatusSegmentId[];\n\treadonly secondary: readonly StatusSegmentId[];\n}\n\nexport interface StatusRenderResult {\n\treadonly primary: string;\n\treadonly secondary?: string;\n\treadonly lines: readonly string[];\n\treadonly visibleSegments: readonly StatusSegmentId[];\n}\n\nfunction segment(\n\tid: StatusSegmentId,\n\tpriority: number,\n\trender: StatusSegment[\"render\"],\n\tessential = false,\n): StatusSegment {\n\treturn { id, defaultPriority: priority, essential, overflow: essential ? \"primary\" : \"secondary\", render };\n}\n\nexport function createBuiltinSegments(): ReadonlyMap<StatusSegmentId, StatusSegment> {\n\tconst segments: StatusSegment[] = [\n\t\tsegment(\"pi\", 10, ({ theme }) => ({\n\t\t\tvisible: true,\n\t\t\tcontent: theme.apply(\"accent\", `${theme.glyph(\"pi\")} pi`),\n\t\t\tcompactContent: theme.apply(\"accent\", theme.glyph(\"pi\")),\n\t\t})),\n\t\tsegment(\n\t\t\t\"model\",\n\t\t\t100,\n\t\t\t({ snapshot, theme }) => ({\n\t\t\t\tvisible: Boolean(snapshot.model),\n\t\t\t\tcontent: theme.apply(\"model\", snapshot.model ?? \"\"),\n\t\t\t\tcompactContent: theme.apply(\"model\", snapshot.model ?? \"\"),\n\t\t\t\ttruncatable: true,\n\t\t\t}),\n\t\t\ttrue,\n\t\t),\n\t\tsegment(\n\t\t\t\"model_effort\",\n\t\t\t40,\n\t\t\t({ snapshot, theme }) => {\n\t\t\t\tconst model = snapshot.model;\n\t\t\t\tif (!model) return { visible: false, content: \"\" };\n\t\t\t\tconst label = snapshot.provider ? `(${snapshot.provider}) ${model}` : model;\n\t\t\t\tconst styledLabel = theme.apply(\"model\", label);\n\t\t\t\tconst effort = effortLevel(snapshot);\n\t\t\t\tif (!effort) {\n\t\t\t\t\treturn { visible: true, content: styledLabel, compactContent: theme.apply(\"model\", model) };\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tvisible: true,\n\t\t\t\t\tcontent: `${styledLabel} ${theme.apply(\"separator\", \"•\")} ${styleEffort(theme, effort)}`,\n\t\t\t\t\tcompactContent: theme.apply(\"model\", model),\n\t\t\t\t};\n\t\t\t},\n\t\t\tfalse,\n\t\t),\n\t\tsegment(\n\t\t\t\"thinking\",\n\t\t\t95,\n\t\t\t({ snapshot, theme }) => {\n\t\t\t\tconst level = snapshot.thinkingLevel;\n\t\t\t\tif (!level) return { visible: false, content: \"\" };\n\t\t\t\tconst label = thinkingLabel(level);\n\t\t\t\tconst text = `think:${label}`;\n\t\t\t\tconst compactText = `t:${label}`;\n\t\t\t\tif (level === \"high\" || level === \"xhigh\" || level === \"max\") {\n\t\t\t\t\treturn { visible: true, content: theme.rainbow(text), compactContent: theme.rainbow(compactText) };\n\t\t\t\t}\n\t\t\t\tconst token =\n\t\t\t\t\tlevel === \"minimal\"\n\t\t\t\t\t\t? \"thinkingMinimal\"\n\t\t\t\t\t\t: level === \"low\"\n\t\t\t\t\t\t\t? \"thinkingLow\"\n\t\t\t\t\t\t\t: level === \"medium\"\n\t\t\t\t\t\t\t\t? \"thinkingMedium\"\n\t\t\t\t\t\t\t\t: \"thinking\";\n\t\t\t\treturn {\n\t\t\t\t\tvisible: true,\n\t\t\t\t\tcontent: theme.apply(token, text),\n\t\t\t\t\tcompactContent: theme.apply(token, compactText),\n\t\t\t\t};\n\t\t\t},\n\t\t\ttrue,\n\t\t),\n\t\tsegment(\"path\", 80, ({ snapshot, theme }) => {\n\t\t\tconst name = snapshot.cwd?.split(/[\\\\/]/).filter(Boolean).at(-1) ?? snapshot.cwd;\n\t\t\treturn {\n\t\t\t\tvisible: Boolean(snapshot.cwd),\n\t\t\t\tcontent: theme.apply(\"path\", name ?? \"\"),\n\t\t\t\tcompactContent: theme.apply(\"path\", name ?? \"\"),\n\t\t\t\ttruncatable: true,\n\t\t\t};\n\t\t}),\n\t\tsegment(\"git\", 75, ({ snapshot, theme }) => {\n\t\t\tconst git = snapshot.git;\n\t\t\tif (!git?.available || !git.branch) return { visible: false, content: \"\" };\n\t\t\tconst counts = `${git.staged ? ` +${git.staged}` : \"\"}${git.unstaged ? ` *${git.unstaged}` : \"\"}${git.untracked ? ` ?${git.untracked}` : \"\"}`;\n\t\t\tconst token = git.staged || git.unstaged || git.untracked ? \"gitDirty\" : \"gitClean\";\n\t\t\treturn {\n\t\t\t\tvisible: true,\n\t\t\t\tcontent: theme.apply(token, `${theme.glyph(\"git\")} ${git.branch}${counts}`),\n\t\t\t\tcompactContent: theme.apply(token, `${theme.glyph(\"git\")} ${git.branch}`),\n\t\t\t};\n\t\t}),\n\t\tsegment(\n\t\t\t\"context_pct\",\n\t\t\t90,\n\t\t\t({ snapshot, theme }) => {\n\t\t\t\tconst percent = contextPercent(snapshot.context ?? {});\n\t\t\t\tconst state = contextState(percent);\n\t\t\t\tconst token =\n\t\t\t\t\tstate === \"critical\"\n\t\t\t\t\t\t? \"contextCritical\"\n\t\t\t\t\t\t: state === \"high\"\n\t\t\t\t\t\t\t? \"contextHigh\"\n\t\t\t\t\t\t\t: state === \"medium\"\n\t\t\t\t\t\t\t\t? \"contextMedium\"\n\t\t\t\t\t\t\t\t: \"contextLow\";\n\t\t\t\treturn {\n\t\t\t\t\tvisible: percent !== undefined,\n\t\t\t\t\tcontent: percent === undefined ? \"\" : theme.apply(token, `ctx:${Math.round(percent)}%`),\n\t\t\t\t\tcompactContent: percent === undefined ? \"\" : theme.apply(token, `${Math.round(percent)}%`),\n\t\t\t\t};\n\t\t\t},\n\t\t\ttrue,\n\t\t),\n\t\tsegment(\"context_bar\", 70, ({ snapshot, theme, options }) => {\n\t\t\tconst percent = contextPercent(snapshot.context ?? {});\n\t\t\tif (percent === undefined) return { visible: false, content: \"\" };\n\t\t\tconst token = contextBarToken(percent);\n\t\t\tconst window = snapshot.context?.windowTokens;\n\t\t\tconst label = `ctx${window !== undefined ? ` (${formatTokens(window)})` : \"\"}:`;\n\t\t\tconst width = (options.context_bar?.width as number | undefined) ?? CONTEXT_BAR_WIDTH;\n\t\t\treturn {\n\t\t\t\tvisible: true,\n\t\t\t\tcontent: `${theme.apply(\"muted\", label)} ${theme.apply(token, contextBar(percent, width))} ${theme.apply(token, `${Math.round(percent)}%`)}`,\n\t\t\t\tcompactContent: theme.apply(token, `${Math.round(percent)}%`),\n\t\t\t};\n\t\t}),\n\t\tsegment(\"context_total\", 60, ({ snapshot, theme }) => ({\n\t\t\tvisible: snapshot.context?.currentTokens !== undefined && snapshot.context.windowTokens !== undefined,\n\t\t\tcontent:\n\t\t\t\tsnapshot.context?.currentTokens !== undefined && snapshot.context.windowTokens !== undefined\n\t\t\t\t\t? theme.apply(\"contextLow\", `${snapshot.context.currentTokens}/${snapshot.context.windowTokens}`)\n\t\t\t\t\t: \"\",\n\t\t})),\n\t\tsegment(\"auto_compact\", 55, ({ snapshot, theme }) => ({\n\t\t\tvisible: Boolean(snapshot.context?.autoCompacting || snapshot.context?.customCompaction),\n\t\t\tcontent: theme.apply(\"warning\", snapshot.context?.customCompaction ?? \"compacting\"),\n\t\t\tcompactContent: theme.apply(\"warning\", \"compact\"),\n\t\t})),\n\t\tsegment(\"token_in\", 50, ({ snapshot, theme }) => ({\n\t\t\tvisible: snapshot.usage?.inputTokens !== undefined,\n\t\t\tcontent: theme.apply(\"tokens\", `in:${snapshot.usage?.inputTokens ?? 0}`),\n\t\t\tcompactContent: theme.apply(\"tokens\", `i:${snapshot.usage?.inputTokens ?? 0}`),\n\t\t})),\n\t\tsegment(\"token_out\", 50, ({ snapshot, theme }) => ({\n\t\t\tvisible: snapshot.usage?.outputTokens !== undefined,\n\t\t\tcontent: theme.apply(\"tokens\", `out:${snapshot.usage?.outputTokens ?? 0}`),\n\t\t\tcompactContent: theme.apply(\"tokens\", `o:${snapshot.usage?.outputTokens ?? 0}`),\n\t\t})),\n\t\tsegment(\"cache_read\", 40, ({ snapshot, theme }) => ({\n\t\t\tvisible: Boolean(snapshot.usage?.cacheReadTokens),\n\t\t\tcontent: theme.apply(\"cache\", `cache:${snapshot.usage?.cacheReadTokens ?? 0}`),\n\t\t\tcompactContent: theme.apply(\"cache\", `cr:${snapshot.usage?.cacheReadTokens ?? 0}`),\n\t\t})),\n\t\tsegment(\"cache_write\", 35, ({ snapshot, theme }) => ({\n\t\t\tvisible: Boolean(snapshot.usage?.cacheWriteTokens),\n\t\t\tcontent: theme.apply(\"cache\", `cw:${snapshot.usage?.cacheWriteTokens ?? 0}`),\n\t\t})),\n\t\tsegment(\"cost\", 65, ({ snapshot, theme }) => {\n\t\t\tconst cost = snapshot.usage?.cost;\n\t\t\tconst content = cost === undefined || cost <= 0 ? \"\" : theme.apply(\"cost\", `$${cost.toFixed(3)}`);\n\t\t\treturn { visible: Boolean(content), content, compactContent: content };\n\t\t}),\n\t\tsegment(\"time_spent\", 25, ({ snapshot, theme }) => ({\n\t\t\tvisible: snapshot.sessionStartedAt !== undefined,\n\t\t\tcontent:\n\t\t\t\tsnapshot.sessionStartedAt === undefined\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: theme.apply(\"time\", formatElapsed(Date.now() - snapshot.sessionStartedAt)),\n\t\t\tcompactContent:\n\t\t\t\tsnapshot.sessionStartedAt === undefined\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: theme.apply(\"time\", formatElapsed(Date.now() - snapshot.sessionStartedAt)),\n\t\t})),\n\t\tsegment(\"time\", 20, ({ theme }) => ({\n\t\t\tvisible: true,\n\t\t\tcontent: theme.apply(\"time\", new Date().toLocaleTimeString([], { hour: \"2-digit\", minute: \"2-digit\" })),\n\t\t\tcompactContent: theme.apply(\"time\", new Date().toLocaleTimeString([], { hour: \"2-digit\", minute: \"2-digit\" })),\n\t\t})),\n\t\tsegment(\"hostname\", 20, ({ snapshot, theme }) => ({\n\t\t\tvisible: Boolean(snapshot.hostname),\n\t\t\tcontent: theme.apply(\"muted\", snapshot.hostname ?? \"\"),\n\t\t})),\n\t\tsegment(\"session\", 20, ({ snapshot, theme }) => ({\n\t\t\tvisible: Boolean(snapshot.sessionName || snapshot.sessionId),\n\t\t\tcontent: theme.apply(\"muted\", snapshot.sessionName ?? snapshot.sessionId ?? \"\"),\n\t\t})),\n\t\tsegment(\"extension_statuses\", 30, ({ snapshot, theme }) => {\n\t\t\tconst statuses = snapshot.extensionStatuses;\n\t\t\tif (!statuses || statuses.length === 0) return { visible: false, content: \"\" };\n\t\t\t// Values already carry their display label (extensions publish via\n\t\t\t// `ctx.ui.setStatus(key, text)` where text is the visible string).\n\t\t\t// Mirror Pi's native footer: sort by key, join the values only.\n\t\t\tconst text = [...statuses]\n\t\t\t\t.sort((a, b) => a.key.localeCompare(b.key))\n\t\t\t\t.map((item) => item.value)\n\t\t\t\t.join(\" \");\n\t\t\treturn { visible: true, content: theme.apply(\"muted\", text) };\n\t\t}),\n\t];\n\treturn new Map(segments.map((item) => [item.id, item]));\n}\n\nconst CONTEXT_BAR_WIDTH = 10;\n\nfunction contextBar(percent: number, width = CONTEXT_BAR_WIDTH): string {\n\tconst filled = Math.max(0, Math.min(width, Math.round((percent / 100) * width)));\n\treturn \"█\".repeat(filled) + \"░\".repeat(width - filled);\n}\n\n/** Bar colors: green under 50%, yellow from 50% to 70%, red above 70%. */\nfunction contextBarToken(percent: number): SemanticToken {\n\tif (percent > 70) return \"error\";\n\tif (percent >= 50) return \"warning\";\n\treturn \"success\";\n}\n\nfunction formatTokens(value: number): string {\n\tif (value >= 1_000_000) {\n\t\tconst millions = value / 1_000_000;\n\t\treturn `${Number.isInteger(millions) ? millions : millions.toFixed(1)}M`;\n\t}\n\tif (value >= 1_000) {\n\t\tconst thousands = value / 1_000;\n\t\treturn `${Number.isInteger(thousands) ? thousands : thousands.toFixed(1)}K`;\n\t}\n\treturn String(value);\n}\n\nfunction effortLevel(snapshot: StatusSnapshot): ThinkingLevel | undefined {\n\tconst level = snapshot.thinkingLevel;\n\tif (!level) return undefined;\n\t// Reasoning models always surface an effort level (defaulting to off); other\n\t// models only show a level when one is actively set.\n\tif (snapshot.reasoning === true) return level;\n\treturn level === \"off\" ? undefined : level;\n}\n\nfunction styleEffort(theme: ResolvedTheme, level: ThinkingLevel): string {\n\tif (level === \"high\" || level === \"xhigh\" || level === \"max\") return theme.rainbow(level);\n\tconst token =\n\t\tlevel === \"minimal\"\n\t\t\t? \"thinkingMinimal\"\n\t\t\t: level === \"low\"\n\t\t\t\t? \"thinkingLow\"\n\t\t\t\t: level === \"medium\"\n\t\t\t\t\t? \"thinkingMedium\"\n\t\t\t\t\t: \"thinking\";\n\treturn theme.apply(token, level);\n}\n\nfunction formatElapsed(ms: number): string {\n\tconst seconds = Math.max(0, Math.floor(ms / 1000));\n\treturn `${Math.floor(seconds / 3600)}:${String(Math.floor((seconds % 3600) / 60)).padStart(2, \"0\")}:${String(seconds % 60).padStart(2, \"0\")}`;\n}\n\nfunction thinkingLabel(level: ThinkingLevel): string {\n\treturn level === \"minimal\" ? \"min\" : level === \"medium\" ? \"med\" : level;\n}\n\nexport function contextState(percent: number | undefined): ContextState | undefined {\n\tif (percent === undefined || !Number.isFinite(percent)) return undefined;\n\tif (percent >= 90) return \"critical\";\n\tif (percent >= 75) return \"high\";\n\tif (percent >= 50) return \"medium\";\n\treturn \"low\";\n}\n\nexport function normalizeThinkingLevel(value: unknown): ThinkingLevel {\n\treturn [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"].includes(value as string)\n\t\t? (value as ThinkingLevel)\n\t\t: \"off\";\n}\n\nexport function contextPercent(\n\tvalue: Pick<ContextSnapshot, \"currentTokens\" | \"windowTokens\" | \"percent\">,\n): number | undefined {\n\tconst percent =\n\t\tvalue.percent ??\n\t\t(value.currentTokens !== undefined && value.windowTokens\n\t\t\t? (value.currentTokens / value.windowTokens) * 100\n\t\t\t: undefined);\n\treturn percent === undefined ? undefined : Math.max(0, Math.min(100, percent));\n}\n\nexport function contextSemanticToken(state: ContextState): SemanticToken {\n\treturn state === \"critical\"\n\t\t? \"contextCritical\"\n\t\t: state === \"high\"\n\t\t\t? \"contextHigh\"\n\t\t\t: state === \"medium\"\n\t\t\t\t? \"contextMedium\"\n\t\t\t\t: \"contextLow\";\n}\n","import type { ExtensionUIContext } from \"@earendil-works/pi-coding-agent\";\nimport { CustomEditor } from \"@earendil-works/pi-coding-agent\";\nimport { type EditorComponent, visibleWidth } from \"@earendil-works/pi-tui\";\nimport type { NormalizedPiStyleConfig } from \"../../domain/config-types.js\";\nimport { contextPercent, type StatusSnapshot, type ThinkingLevel } from \"../../domain/status.js\";\nimport type { ResolvedTheme } from \"../../domain/theme.js\";\nimport { resolveTheme } from \"../../domain/theme.js\";\nimport { stripAnsi, truncateAnsi } from \"../../shared/ansi.js\";\n\nexport const EDITOR_DIAGNOSTIC_KEY = \"pi-style.editor\";\ntype SetEditorComponent = NonNullable<ExtensionUIContext[\"setEditorComponent\"]>;\ntype EditorFactory = NonNullable<Parameters<SetEditorComponent>[0]>;\ntype Tui = Parameters<EditorFactory>[0];\ntype PiEditorTheme = Parameters<EditorFactory>[1];\ntype Keybindings = Parameters<EditorFactory>[2];\ntype EditorHost = Pick<ExtensionUIContext, \"setEditorComponent\"> & {\n\tgetEditorComponent?: () => EditorFactory | undefined;\n\tnotify?: (message: string, type?: \"info\" | \"warning\" | \"error\") => void;\n\t/** Full Pi theme; provides thinking-level border colors when available. */\n\treadonly theme?: { getThinkingBorderColor?: (level: ThinkingLevel) => (str: string) => string };\n};\n\nexport interface EditorInstallation {\n\treadonly generation: number;\n\treadonly installedFactory: EditorFactory;\n\treadonly previousFactory: EditorFactory | undefined;\n\treadonly preservedPrevious: boolean;\n\tupdate(snapshot: StatusSnapshot): void;\n\tconfigure(config: NormalizedPiStyleConfig): void;\n\tdispose(): void;\n}\n\ninterface EditorOptions {\n\tconfig: NormalizedPiStyleConfig;\n\tsnapshot: StatusSnapshot;\n\ttheme: PiEditorTheme;\n\t/** Full Pi theme for thinking-level border colors (optional; falls back to borderColor). */\n\tfullTheme?: { getThinkingBorderColor?: (level: ThinkingLevel) => (str: string) => string };\n\tonSnapshot: (snapshot: StatusSnapshot) => void;\n}\n\nconst widthOf = visibleWidth;\n\nfunction widthSafe(value: string, width: number): string {\n\tif (width <= 0) return \"\";\n\tconst fitted = widthOf(value) > width ? truncateAnsi(value, width, \"\") : value;\n\tconst current = widthOf(fitted);\n\treturn current < width ? fitted + \" \".repeat(width - current) : fitted;\n}\n\nfunction isNativeBorderLine(line: string): boolean {\n\tconst stripped = stripAnsi(line);\n\treturn /^─{2,}$/.test(stripped) || /^─── [↑↓] \\d+ more /.test(stripped);\n}\n\nfunction semanticTheme(theme: PiEditorTheme, config: NormalizedPiStyleConfig): ResolvedTheme {\n\tconst editorTheme = theme;\n\treturn resolveTheme(\n\t\t{\n\t\t\tfg: (token) => {\n\t\t\t\tif (token === \"borderActive\" || token.startsWith(\"thinking\")) return editorTheme.borderColor(\"\");\n\t\t\t\treturn \"\";\n\t\t\t},\n\t\t},\n\t\tconfig,\n\t);\n}\n\n/**\n * A thin CustomEditor treatment: all text, cursor, paste, autocomplete, history,\n * and keybinding state remains owned by Pi's editor implementation.\n */\nexport class StyledEditor extends CustomEditor implements EditorComponent {\n\tprivate config: NormalizedPiStyleConfig;\n\tprivate snapshot: StatusSnapshot;\n\tprivate readonly piTheme: PiEditorTheme;\n\tprivate readonly fullTheme: EditorOptions[\"fullTheme\"];\n\tprivate readonly onSnapshot: (snapshot: StatusSnapshot) => void;\n\tprivate semantic: ResolvedTheme;\n\tprivate disposed = false;\n\n\tconstructor(tui: Tui, theme: PiEditorTheme, keybindings: Keybindings, options: EditorOptions) {\n\t\tsuper(tui, theme, keybindings);\n\t\tthis.config = options.config;\n\t\tthis.snapshot = options.snapshot;\n\t\tthis.piTheme = theme;\n\t\tthis.fullTheme = options.fullTheme;\n\t\tthis.onSnapshot = options.onSnapshot;\n\t\tthis.semantic = semanticTheme(theme, options.config);\n\t\tthis.setPaddingX(0);\n\t}\n\n\tupdate(snapshot: StatusSnapshot): void {\n\t\tif (this.disposed) return;\n\t\tthis.snapshot = snapshot;\n\t\tthis.invalidate();\n\t}\n\n\tconfigure(config: NormalizedPiStyleConfig): void {\n\t\tif (this.disposed) return;\n\t\tthis.config = config;\n\t\tthis.semantic = semanticTheme(this.piTheme, config);\n\t\tthis.invalidate();\n\t}\n\n\toverride handleInput(data: string): void {\n\t\tif (this.disposed) return;\n\t\tsuper.handleInput(data);\n\t\tthis.onSnapshot({ ...this.snapshot });\n\t}\n\n\toverride invalidate(): void {\n\t\tsuper.invalidate();\n\t\tthis.semantic = semanticTheme(this.piTheme, this.config);\n\t\tthis.tui.requestRender();\n\t}\n\n\toverride render(width: number): string[] {\n\t\tif (width <= 0) return [];\n\t\tconst nativeLines = super.render(width);\n\t\t// Autocomplete (slash menu / @-mentions) restructure: Pi draws the\n\t\t// suggestions after its own bottom border, which pushes the below-editor\n\t\t// widgets (status line) down. Re-frame the native output so the dropdown\n\t\t// lives INSIDE the input box, keeping the footer directly below the input.\n\t\t// Native layout: [top border, text lines, bottom border, dropdown lines...].\n\t\tif ((this as unknown as { autocompleteState?: unknown }).autocompleteState) {\n\t\t\tconst prompt = this.prompt();\n\t\t\tconst padding = this.paddingFor(width, this.styleFor(width));\n\t\t\tconst promptWidth = widthOf(prompt) + 1;\n\t\t\tconst prefix = `${\" \".repeat(padding)}${prompt} `;\n\t\t\tconst continuation = \" \".repeat(padding + promptWidth);\n\t\t\tconst borderIndex = nativeLines.slice(1).findIndex((line) => isNativeBorderLine(line));\n\t\t\tconst split = borderIndex >= 0 ? borderIndex + 1 : nativeLines.length;\n\t\t\tconst body = nativeLines.slice(1, split);\n\t\t\tconst dropdown = nativeLines.slice(split);\n\t\t\tconst border = this.borderFor(width);\n\t\t\tconst renderedBody = body.map((line, index) => widthSafe(`${index === 0 ? prefix : continuation}${line}`, width));\n\t\t\treturn [\n\t\t\t\tborder(\"─\".repeat(width)),\n\t\t\t\t...renderedBody,\n\t\t\t\t...dropdown.map((line) => widthSafe(line, width)),\n\t\t\t\tborder(\"─\".repeat(width)),\n\t\t\t];\n\t\t}\n\t\tconst style = this.styleFor(width);\n\t\tif (style === \"native\") return nativeLines.map((line) => widthSafe(line, width));\n\n\t\tconst prompt = this.prompt();\n\t\tconst promptWidth = widthOf(prompt) + 1;\n\t\tconst padding = this.paddingFor(width, style);\n\t\tconst innerWidth = Math.max(1, width - promptWidth - padding * 2);\n\t\tconst innerLines = super.render(innerWidth);\n\t\tif (innerLines.length === 0) return [];\n\n\t\tconst body = innerLines.slice(1, -1);\n\t\tconst prefix = `${\" \".repeat(padding)}${prompt} `;\n\t\tconst continuation = \" \".repeat(padding + promptWidth);\n\t\tconst renderedBody = body.map((line, index) => {\n\t\t\tconst lead = index === 0 ? prefix : continuation;\n\t\t\treturn widthSafe(`${lead}${line}`, width);\n\t\t});\n\t\tconst metadata = this.metadata(width, style);\n\t\tconst framed = this.frame(width, style, renderedBody, metadata);\n\t\treturn framed.map((line) => widthSafe(line, width));\n\t}\n\n\tdispose(): void {\n\t\tif (this.disposed) return;\n\t\tthis.disposed = true;\n\t\tthis.invalidate();\n\t}\n\n\tprivate prompt(): string {\n\t\tconst configured = this.config.theme.glyphs.prompt;\n\t\tif (configured) return configured;\n\t\treturn this.semantic.mode === \"ascii\" ? \">\" : \"❯\";\n\t}\n\n\tprivate styleFor(width: number): \"compact\" | \"boxed\" | \"dock\" | \"native\" {\n\t\tif (width < 20) return \"native\";\n\t\tif ([\"compact\", \"boxed\", \"dock\", \"native\"].includes(this.config.editor.style)) {\n\t\t\tif (this.config.editor.style === \"native\") return \"native\";\n\t\t\tif (width < 40 && this.config.editor.style !== \"compact\") return \"compact\";\n\t\t\treturn this.config.editor.style as \"compact\" | \"boxed\" | \"dock\";\n\t\t}\n\t\treturn \"compact\";\n\t}\n\n\tprivate paddingFor(width: number, style: \"compact\" | \"boxed\" | \"dock\" | \"native\"): number {\n\t\tif (width < 50) return 0;\n\t\treturn style === \"boxed\" ? 2 : style === \"dock\" ? 1 : 1;\n\t}\n\n\tprivate borderFor(width: number): (line: string) => string {\n\t\t// Sync the frame color with the active thinking level, matching Pi's native editor.\n\t\tconst level = this.snapshot.thinkingLevel;\n\t\tconst thinking = this.fullTheme?.getThinkingBorderColor?.(level ?? \"off\");\n\t\tconst border = thinking ?? this.piTheme.borderColor;\n\t\treturn (line: string) => border(widthSafe(line, width));\n\t}\n\n\tprivate frame(\n\t\twidth: number,\n\t\tstyle: \"compact\" | \"boxed\" | \"dock\" | \"native\",\n\t\tbody: string[],\n\t\tmetadata: string[],\n\t): string[] {\n\t\tconst border = this.borderFor(width);\n\t\tconst lineMode = this.config.editor.frame === \"line\" || this.config.editor.frame === \"solid\";\n\t\tif (style === \"compact\" || lineMode) {\n\t\t\t// Match Pi's native editor: a horizontal border above and below the input.\n\t\t\treturn [border(\"─\".repeat(width)), ...body, border(\"─\".repeat(width)), ...metadata];\n\t\t}\n\t\tif (style === \"boxed\") {\n\t\t\tconst glyph = this.config.editor.frame === \"halfblock\" ? \"▀\" : \"━\";\n\t\t\treturn [border(glyph.repeat(width)), ...body, border(glyph.repeat(width)), ...metadata];\n\t\t}\n\t\tif (this.config.editor.frame === \"native\") return body;\n\t\treturn [\n\t\t\tborder(`┌${\"─\".repeat(Math.max(0, width - 2))}┐`),\n\t\t\t...body,\n\t\t\tborder(`└${\"─\".repeat(Math.max(0, width - 2))}┘`),\n\t\t\t...metadata,\n\t\t];\n\t}\n\n\tprivate metadata(width: number, style: \"compact\" | \"boxed\" | \"dock\" | \"native\"): string[] {\n\t\tif (!this.config.editor.showMetadata || width < 60) return [];\n\t\tconst percent = contextPercent(this.snapshot.context ?? {});\n\t\tif (percent === undefined) return [];\n\t\tconst label = `ctx ${Math.round(percent)}%`;\n\t\treturn [this.piTheme.borderColor(` ${style === \"boxed\" ? \"· \" : \"\"}${label}`)];\n\t}\n}\n\nexport function installEditor(options: {\n\thost: EditorHost;\n\tconfig: NormalizedPiStyleConfig;\n\tgeneration: number;\n\tinitialSnapshot: StatusSnapshot;\n\tisCurrent?: () => boolean;\n}): EditorInstallation | undefined {\n\tif (!options.host.setEditorComponent) return undefined;\n\tconst previous = options.host.getEditorComponent?.();\n\tif (previous && options.config.compatibility.preferExistingEditor) {\n\t\treturn {\n\t\t\tgeneration: options.generation,\n\t\t\tinstalledFactory: previous,\n\t\t\tpreviousFactory: previous,\n\t\t\tpreservedPrevious: true,\n\t\t\tupdate() {},\n\t\t\tconfigure() {},\n\t\t\tdispose() {},\n\t\t};\n\t}\n\tlet config = options.config;\n\tlet snapshot = options.initialSnapshot;\n\tlet disposed = false;\n\tconst components = new Set<StyledEditor>();\n\tconst factory = ((tui: Tui, theme: PiEditorTheme, keybindings: Keybindings) => {\n\t\tconst editor = new StyledEditor(tui, theme, keybindings, {\n\t\t\tconfig,\n\t\t\tsnapshot,\n\t\t\ttheme,\n\t\t\t...(options.host.theme ? { fullTheme: options.host.theme } : {}),\n\t\t\tonSnapshot: (next) => {\n\t\t\t\tif (!disposed && options.isCurrent?.() !== false) snapshot = next;\n\t\t\t},\n\t\t});\n\t\tcomponents.add(editor);\n\t\treturn editor;\n\t}) as EditorFactory;\n\ttry {\n\t\toptions.host.setEditorComponent(factory);\n\t} catch {\n\t\toptions.host.notify?.(\"pi-style editor unavailable; keeping the native editor\", \"warning\");\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tgeneration: options.generation,\n\t\tinstalledFactory: factory,\n\t\tpreviousFactory: previous,\n\t\tpreservedPrevious: false,\n\t\tupdate(next) {\n\t\t\tif (disposed || options.isCurrent?.() === false) return;\n\t\t\tsnapshot = next;\n\t\t\tfor (const component of components) component.update(next);\n\t\t},\n\t\tconfigure(next) {\n\t\t\tif (disposed || options.isCurrent?.() === false) return;\n\t\t\tconfig = next;\n\t\t\tfor (const component of components) component.configure(next);\n\t\t},\n\t\tdispose() {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\tfor (const component of components) component.dispose();\n\t\t\tcomponents.clear();\n\t\t\tif (options.host.getEditorComponent?.() === factory) {\n\t\t\t\toptions.host.setEditorComponent(previous);\n\t\t\t}\n\t\t},\n\t};\n}\n","import type { NormalizedPiStyleConfig } from \"./config-types.js\";\n\nexport type GlyphMode = \"nerd\" | \"unicode\" | \"ascii\";\nexport type SemanticToken =\n\t| \"surface\"\n\t| \"surfaceRaised\"\n\t| \"surfaceMuted\"\n\t| \"text\"\n\t| \"muted\"\n\t| \"dim\"\n\t| \"accent\"\n\t| \"accentStrong\"\n\t| \"border\"\n\t| \"borderMuted\"\n\t| \"borderActive\"\n\t| \"success\"\n\t| \"warning\"\n\t| \"error\"\n\t| \"model\"\n\t| \"thinking\"\n\t| \"thinkingMinimal\"\n\t| \"thinkingLow\"\n\t| \"thinkingMedium\"\n\t| \"thinkingHigh\"\n\t| \"thinkingXhigh\"\n\t| \"thinkingMax\"\n\t| \"path\"\n\t| \"gitClean\"\n\t| \"gitDirty\"\n\t| \"contextLow\"\n\t| \"contextMedium\"\n\t| \"contextHigh\"\n\t| \"contextCritical\"\n\t| \"tokens\"\n\t| \"cache\"\n\t| \"cost\"\n\t| \"time\"\n\t| \"separator\";\n\n/** Structural view of Pi's theme. fg/bg follow Pi's `(color, text) => string` shape. */\nexport interface ActiveTheme {\n\tfg?: (color: string, text: string) => string;\n\tbg?: (color: string, text: string) => string;\n\tcolors?: Record<string, string>;\n}\n\nexport interface ResolvedTheme {\n\t/** ANSI color prefix for a semantic token, or \"\" when uncolored. */\n\treadonly color: (token: SemanticToken) => string;\n\t/** Prefix + text + reset; returns plain text when the token is uncolored. */\n\treadonly apply: (token: SemanticToken, text: string) => string;\n\t/** Rainbow gradient text (used for high thinking levels); plain when uncolored. */\n\treadonly rainbow: (text: string) => string;\n\treadonly glyph: (name: keyof typeof GLYPHS.unicode) => string;\n\treadonly mode: GlyphMode;\n\treadonly noColor: boolean;\n}\n\n/**\n * Default semantic colors — hex values render without any Pi theme; theme names resolve through Pi's theme.\n */\nconst SEMANTIC_COLORS: Record<SemanticToken, string> = {\n\tsurface: \"\",\n\tsurfaceRaised: \"\",\n\tsurfaceMuted: \"\",\n\ttext: \"text\",\n\tmuted: \"muted\",\n\tdim: \"dim\",\n\taccent: \"accent\",\n\taccentStrong: \"accent\",\n\tborder: \"border\",\n\tborderMuted: \"borderMuted\",\n\tborderActive: \"borderAccent\",\n\tsuccess: \"success\",\n\twarning: \"warning\",\n\terror: \"error\",\n\tmodel: \"#d787af\",\n\tthinking: \"thinkingOff\",\n\tthinkingMinimal: \"thinkingMinimal\",\n\tthinkingLow: \"thinkingLow\",\n\tthinkingMedium: \"thinkingMedium\",\n\tthinkingHigh: \"thinkingHigh\",\n\tthinkingXhigh: \"thinkingXhigh\",\n\tthinkingMax: \"thinkingMax\",\n\tpath: \"#00afaf\",\n\tgitClean: \"success\",\n\tgitDirty: \"warning\",\n\tcontextLow: \"dim\",\n\tcontextMedium: \"warning\",\n\tcontextHigh: \"error\",\n\tcontextCritical: \"error\",\n\ttokens: \"muted\",\n\tcache: \"muted\",\n\tcost: \"text\",\n\ttime: \"muted\",\n\tseparator: \"dim\",\n};\n\nconst GLYPHS = {\n\tnerd: {\n\t\tpi: \"π\",\n\t\tgit: \"\\uE0A0\",\n\t\tpath: \"\\uF07B\",\n\t\tcontext: \"\\u{F035B}\",\n\t\tseparator: \"\\uE0B0\",\n\t\tpowerlineLeft: \"\\uE0B0\",\n\t\tpowerlineRight: \"\\uE0B2\",\n\t\tpowerlineThinLeft: \"\\uE0B1\",\n\t\tpowerlineThinRight: \"\\uE0B3\",\n\t\tbatchOpen: \"\\u{F111}\",\n\t},\n\tunicode: {\n\t\tpi: \"π\",\n\t\tgit: \"⎇\",\n\t\tpath: \"⌂\",\n\t\tcontext: \"◫\",\n\t\tseparator: \"│\",\n\t\tpowerlineLeft: \"›\",\n\t\tpowerlineRight: \"‹\",\n\t\tpowerlineThinLeft: \"│\",\n\t\tpowerlineThinRight: \"│\",\n\t\tbatchOpen: \"●\",\n\t},\n\tascii: {\n\t\tpi: \"pi\",\n\t\tgit: \"git\",\n\t\tpath: \"path\",\n\t\tcontext: \"ctx\",\n\t\tseparator: \"|\",\n\t\tpowerlineLeft: \">\",\n\t\tpowerlineRight: \"<\",\n\t\tpowerlineThinLeft: \"|\",\n\t\tpowerlineThinRight: \"|\",\n\t\tbatchOpen: \"v\",\n\t},\n} as const;\n\nfunction isHex(color: string): color is `#${string}` {\n\treturn /^#[0-9a-fA-F]{6}$/.test(color);\n}\n\nexport function hexToAnsiPrefix(hex: string): string {\n\tconst value = hex.replace(\"#\", \"\");\n\tconst r = Number.parseInt(value.slice(0, 2), 16);\n\tconst g = Number.parseInt(value.slice(2, 4), 16);\n\tconst b = Number.parseInt(value.slice(4, 6), 16);\n\treturn `\\x1b[38;2;${r};${g};${b}m`;\n}\n\n/** Rainbow gradient for high thinking levels. */\nconst RAINBOW_COLORS = [\n\t\"#b281d6\",\n\t\"#d787af\",\n\t\"#febc38\",\n\t\"#e4c00f\",\n\t\"#89d281\",\n\t\"#00afaf\",\n\t\"#178fb9\",\n\t\"#b281d6\",\n] as const;\n\nfunction rainbowAnsi(text: string): string {\n\tlet result = \"\";\n\tlet colorIndex = 0;\n\tfor (const char of text) {\n\t\tif (char === \" \" || char === \":\") {\n\t\t\tresult += char;\n\t\t} else {\n\t\t\tresult += hexToAnsiPrefix(RAINBOW_COLORS[colorIndex % RAINBOW_COLORS.length] ?? \"#b281d6\") + char;\n\t\t\tcolorIndex++;\n\t\t}\n\t}\n\treturn `${result}\\x1b[0m`;\n}\n\nfunction colorPrefixFor(\n\tactive: ActiveTheme | undefined,\n\tconfig: NormalizedPiStyleConfig,\n\tnoColor: boolean,\n\ttoken: SemanticToken,\n): string {\n\tif (noColor) return \"\";\n\tconst raw = config.theme.colors[token] ?? SEMANTIC_COLORS[token];\n\tif (!raw) return \"\";\n\tif (isHex(raw)) return hexToAnsiPrefix(raw);\n\tif (active?.fg) {\n\t\ttry {\n\t\t\t// Pi's fg returns `\\x1b[38;5;Nm` + text + `\\x1b[39m`; keep only the prefix.\n\t\t\tconst styled = active.fg(raw, \"\");\n\t\t\treturn styled.endsWith(\"\\x1b[39m\") ? styled.slice(0, -5) : styled;\n\t\t} catch {\n\t\t\treturn \"\";\n\t\t}\n\t}\n\treturn \"\";\n}\n\nexport function detectGlyphMode(\n\tconfig: NormalizedPiStyleConfig,\n\tenv: Record<string, string | undefined> = {},\n): GlyphMode {\n\tif (env.PI_STYLE_NERD_FONTS === \"1\") return \"nerd\";\n\tif (env.PI_STYLE_NERD_FONTS === \"0\") return \"unicode\";\n\tif (config.theme.nerdFonts === \"on\") return \"nerd\";\n\tif (config.theme.nerdFonts === \"off\") return \"unicode\";\n\tif (env.GHOSTTY_RESOURCES_DIR) return \"nerd\";\n\t// Conservative heuristic: known terminals commonly ship with a Nerd Font. An explicit override stays authoritative.\n\tconst term = (env.TERM_PROGRAM ?? \"\").toLowerCase();\n\tif ([\"iterm\", \"wezterm\", \"kitty\", \"ghostty\", \"alacritty\", \"warp\"].some((name) => term.includes(name))) {\n\t\treturn \"nerd\";\n\t}\n\treturn config.preset === \"ascii\" ? \"ascii\" : \"unicode\";\n}\n\nexport function resolveTheme(\n\tactive: ActiveTheme | undefined,\n\tconfig: NormalizedPiStyleConfig,\n\tenv: Record<string, string | undefined> = {},\n): ResolvedTheme {\n\tconst noColor = Object.hasOwn(env, \"NO_COLOR\") && env.NO_COLOR !== \"\" && config.theme.colors.colorOverride !== \"on\";\n\tconst mode = config.preset === \"ascii\" ? \"ascii\" : detectGlyphMode(config, env);\n\tconst color = (token: SemanticToken) => colorPrefixFor(active, config, noColor, token);\n\treturn {\n\t\tmode,\n\t\tnoColor,\n\t\tcolor,\n\t\tapply: (token, text) => {\n\t\t\tconst prefix = color(token);\n\t\t\treturn prefix ? `${prefix}${text}\\x1b[0m` : text;\n\t\t},\n\t\trainbow: (text) => (noColor ? text : rainbowAnsi(text)),\n\t\tglyph: (name) => config.theme.glyphs[name] ?? GLYPHS[mode][name],\n\t};\n}\nexport { GLYPHS };\n","import { hexToAnsiPrefix, type ResolvedTheme } from \"../../domain/theme.js\";\nimport { fitAnsiWidth, parseAnsiFgToRgb, visibleWidth } from \"../../shared/ansi.js\";\n\n/**\n * Compact startup logo header. Renders the block-art Pi logo with a\n * per-character accent gradient plus side details, with stacked/truncated\n * fallbacks for narrow widths. Pure render: color comes only from the\n * resolved theme.\n */\n\nexport const PI_LOGO_LINES = [\n\t\"████████████╗\",\n\t\"████████████║\",\n\t\"████╔═══████║\",\n\t\"████║ ████║\",\n\t\"████████╬═══████╗\",\n\t\"████████║ ████║ \",\n\t\"████╔═══╝ ████║\",\n\t\"████║ ████║\",\n\t\"╚═══╝ ╚═══╝\",\n] as const;\n\nconst LOGO_PALETTE_STEPS = 24;\nconst LOGO_MAX_DARKEN = 0.18;\nconst LOGO_MAX_LIGHTEN = 0.18;\nconst LOGO_ROW_PHASE_STEP = 0.12;\nconst LOGO_GAP = \" \";\n/** Minimum side-detail width before the logo collapses to stacked lines. */\nconst LOGO_SIDE_DETAIL_MIN_WIDTH = 12;\n\ntype Rgb = { r: number; g: number; b: number };\n\nfunction clampChannel(value: number): number {\n\treturn Math.max(0, Math.min(255, Math.round(value)));\n}\n\nfunction interpolateRgb(start: Rgb, end: Rgb, factor: number): Rgb {\n\treturn {\n\t\tr: clampChannel(start.r + (end.r - start.r) * factor),\n\t\tg: clampChannel(start.g + (end.g - start.g) * factor),\n\t\tb: clampChannel(start.b + (end.b - start.b) * factor),\n\t};\n}\n\nfunction darkenRgb(rgb: Rgb, amount: number): Rgb {\n\treturn {\n\t\tr: clampChannel(rgb.r * (1 - amount)),\n\t\tg: clampChannel(rgb.g * (1 - amount)),\n\t\tb: clampChannel(rgb.b * (1 - amount)),\n\t};\n}\n\nfunction lightenRgb(rgb: Rgb, amount: number): Rgb {\n\treturn {\n\t\tr: clampChannel(rgb.r + (255 - rgb.r) * amount),\n\t\tg: clampChannel(rgb.g + (255 - rgb.g) * amount),\n\t\tb: clampChannel(rgb.b + (255 - rgb.b) * amount),\n\t};\n}\n\nfunction buildLogoPalette(accent: Rgb): Rgb[] {\n\treturn Array.from({ length: LOGO_PALETTE_STEPS }, (_, index) => {\n\t\tconst progress = index / LOGO_PALETTE_STEPS;\n\t\tconst wave = -Math.cos(progress * Math.PI * 2);\n\t\treturn wave < 0 ? darkenRgb(accent, LOGO_MAX_DARKEN * -wave) : lightenRgb(accent, LOGO_MAX_LIGHTEN * wave);\n\t});\n}\n\nfunction sampleLogoGradient(palette: Rgb[], position: number): Rgb {\n\tconst wrapped = ((position % 1) + 1) % 1;\n\tconst scaled = wrapped * palette.length;\n\tconst baseIndex = Math.floor(scaled) % palette.length;\n\tconst nextIndex = (baseIndex + 1) % palette.length;\n\tconst base = palette[baseIndex];\n\tconst next = palette[nextIndex];\n\tif (!base || !next) return { r: 0, g: 0, b: 0 };\n\treturn interpolateRgb(base, next, scaled - Math.floor(scaled));\n}\n\nfunction renderLogoGradientLine(line: string, palette: Rgb[], phase: number): string {\n\tconst characters = [...line];\n\tconst span = Math.max(characters.length - 1, 1);\n\treturn characters\n\t\t.map((character, index) => {\n\t\t\tif (character === \" \") return character;\n\t\t\tconst color = sampleLogoGradient(palette, index / span + phase);\n\t\t\treturn `${hexToAnsiPrefix(rgbToHex(color))}${character}`;\n\t\t})\n\t\t.join(\"\");\n}\n\nfunction rgbToHex(rgb: Rgb): string {\n\treturn `#${[rgb.r, rgb.g, rgb.b].map((channel) => channel.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\nlet logoGradientCacheKey: string | undefined;\nlet logoGradientCacheLines: string[] | undefined;\n\n/** Accent RGB resolved from the active theme, or undefined when uncolored. */\nexport function resolveAccentRgb(resolved: ResolvedTheme): Rgb | undefined {\n\tconst accentAnsi = resolved.color(\"accent\");\n\tif (!accentAnsi) return undefined;\n\treturn parseAnsiFgToRgb(accentAnsi);\n}\n\n/** The block-art logo lines, gradient-styled when an accent color is resolvable. */\nexport function styledLogoLines(resolved: ResolvedTheme): string[] {\n\tconst accent = resolveAccentRgb(resolved);\n\tif (!accent) return [...PI_LOGO_LINES];\n\tconst cacheKey = `${resolved.color(\"accent\")}|${resolved.mode}`;\n\tif (cacheKey === logoGradientCacheKey && logoGradientCacheLines) return logoGradientCacheLines;\n\tconst palette = buildLogoPalette(accent);\n\tlogoGradientCacheLines = PI_LOGO_LINES.map((line, rowIndex) =>\n\t\trenderLogoGradientLine(line, palette, rowIndex * LOGO_ROW_PHASE_STEP),\n\t);\n\tlogoGradientCacheKey = cacheKey;\n\treturn logoGradientCacheLines;\n}\n\n/**\n * Assemble the compact startup header: gradient logo with side details when\n * wide enough, stacked logo + details next, and a minimal title/status pair\n * for very narrow terminals. Every returned line fits within `width`.\n */\nexport function compactLogoHeader(\n\tresolved: ResolvedTheme,\n\tdetails: readonly [title: string, hints: string, status: string],\n\twidth: number,\n): string[] {\n\tconst logoLines = styledLogoLines(resolved);\n\tconst logoWidth = Math.max(...PI_LOGO_LINES.map((line) => visibleWidth(line)));\n\tconst safeWidth = Math.max(1, width);\n\tconst detailWidth = safeWidth - logoWidth - visibleWidth(LOGO_GAP);\n\n\tif (detailWidth >= LOGO_SIDE_DETAIL_MIN_WIDTH) {\n\t\tconst detailStartRow = Math.max(0, Math.floor((PI_LOGO_LINES.length - details.length) / 2));\n\t\treturn PI_LOGO_LINES.map((plainLine, index) => {\n\t\t\tconst logoPadding = \" \".repeat(Math.max(0, logoWidth - visibleWidth(plainLine)));\n\t\t\tconst detailIndex = index - detailStartRow;\n\t\t\tconst detailText = details[detailIndex];\n\t\t\tconst detail = detailText ? fitAnsiWidth(detailText, detailWidth) : \"\";\n\t\t\treturn `${logoLines[index]}${logoPadding}${detail ? `${LOGO_GAP}${detail}` : \"\"}`;\n\t\t});\n\t}\n\n\tif (safeWidth >= logoWidth) {\n\t\treturn [...logoLines, ...details.map((detail) => fitAnsiWidth(detail, safeWidth))];\n\t}\n\n\treturn [details[0], details[2]].map((detail) => fitAnsiWidth(detail, safeWidth));\n}\n","import type { Component, OverlayHandle, OverlayOptions } from \"@earendil-works/pi-tui\";\nimport type { NormalizedPiStyleConfig } from \"../../domain/config-types.js\";\nimport type { StatusSnapshot } from \"../../domain/status.js\";\nimport { type ActiveTheme, type ResolvedTheme, resolveTheme } from \"../../domain/theme.js\";\nimport { fitAnsiWidth, truncateAnsi, visibleWidth } from \"../../shared/ansi.js\";\nimport { compactLogoHeader } from \"./logo.js\";\n\nexport type StartupReason = \"startup\" | \"reload\" | \"new\" | \"resume\" | \"fork\";\n\nexport interface StartupDetailItem {\n\treadonly kind: \"system\" | \"append\" | \"context\";\n\treadonly path: string;\n\treadonly words: number;\n\treadonly lines: number;\n}\n\nexport interface StartupToolItem {\n\treadonly source: string;\n\treadonly name: string;\n}\n\nexport interface StartupResources {\n\treadonly contextFiles?: number;\n\treadonly extensions?: number;\n\treadonly skills?: number;\n\treadonly prompts?: number;\n\treadonly tools?: number;\n\treadonly models?: number;\n\treadonly details?: readonly StartupDetailItem[];\n\treadonly toolDetails?: readonly StartupToolItem[];\n\treadonly error?: string;\n}\n\nexport interface StartupSnapshot extends StatusSnapshot {\n\treadonly reason: StartupReason;\n\treadonly project?: string | undefined;\n\treadonly startupProvider?: string | undefined;\n\treadonly resources?: StartupResources | undefined;\n\treadonly preset?: string | undefined;\n\treadonly compatibility?: string | undefined;\n}\n\nexport type StartupTheme = ActiveTheme;\n\nfunction activeThemeFromPi(theme: unknown): ActiveTheme {\n\tif (!theme || typeof theme !== \"object\") return {};\n\tconst candidate = theme as { fg?: (token: string, text?: string) => string; colors?: Record<string, string> };\n\treturn {\n\t\t...(candidate.colors ? { colors: candidate.colors } : {}),\n\t\t...(candidate.fg ? { fg: (color: string, text: string) => candidate.fg?.(color, text) ?? text } : {}),\n\t};\n}\n\nexport interface StartupHost {\n\tsetHeader?: (factory: ((tui: unknown, theme: unknown) => Component & { dispose?(): void }) | undefined) => void;\n\tsetWidget?: (key: string, content: unknown, options?: unknown) => void;\n\tcustom?: <T>(\n\t\tfactory: (\n\t\t\ttui: unknown,\n\t\t\ttheme: unknown,\n\t\t\tkeybindings: unknown,\n\t\t\tdone: (value: T) => void,\n\t\t) => Component & { dispose?(): void },\n\t\toptions?: { overlay?: boolean; overlayOptions?: OverlayOptions; onHandle?: (handle: OverlayHandle) => void },\n\t) => Promise<T>;\n\tonTerminalInput?: (handler: (...args: readonly unknown[]) => unknown) => () => void;\n\treadonly mode?: string;\n\treadonly hasUI?: boolean;\n\t/** Optional public-adapter capability used to avoid overwriting a later header owner. */\n\tgetHeaderFactory?: () => unknown;\n}\n\nexport interface StartupInstallation {\n\treadonly generation: number;\n\tupdate(snapshot: StartupSnapshot): void;\n\tdismiss(): void;\n\tconfigure(config: NormalizedPiStyleConfig): void;\n\tdispose(): void;\n}\n\nexport interface StartupInstallOptions {\n\thost: StartupHost;\n\tconfig: NormalizedPiStyleConfig;\n\tsnapshot: StartupSnapshot;\n\tgeneration: number;\n\trequestRender?: () => void;\n\ttimeoutMs?: number;\n\tisCurrent?: () => boolean;\n}\n\nexport const STARTUP_WIDGET_KEY = \"pi-style.startup\";\nconst owners = new WeakMap<object, Map<string, symbol>>();\n\nfunction ownerMap(host: object): Map<string, symbol> {\n\tlet map = owners.get(host);\n\tif (!map) {\n\t\tmap = new Map();\n\t\towners.set(host, map);\n\t}\n\treturn map;\n}\n\nfunction safeCall(fn: () => void): boolean {\n\ttry {\n\t\tfn();\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction shouldShow(reason: StartupReason, mode: \"off\" | \"compact\" | \"overlay\"): boolean {\n\tif (mode === \"off\") return false;\n\treturn reason === \"startup\" || reason === \"reload\" || reason === \"new\" || reason === \"resume\" || reason === \"fork\";\n}\n\nfunction overlayAllowed(reason: StartupReason): boolean {\n\treturn reason === \"startup\";\n}\n\nfunction resourceChipRows(resources: StartupResources | undefined): { label: string; count: number }[] {\n\tif (!resources) return [];\n\tconst rows: { label: string; count: number }[] = [];\n\tif (resources.contextFiles !== undefined) rows.push({ label: \"context\", count: resources.contextFiles });\n\tif (resources.extensions !== undefined) rows.push({ label: \"extensions\", count: resources.extensions });\n\tif (resources.skills !== undefined) rows.push({ label: \"skills\", count: resources.skills });\n\tif (resources.prompts !== undefined) rows.push({ label: \"prompts\", count: resources.prompts });\n\tif (resources.tools !== undefined) rows.push({ label: \"tools\", count: resources.tools });\n\tif (resources.models !== undefined) rows.push({ label: \"models\", count: resources.models });\n\treturn rows;\n}\n\nconst PANEL_SIDE_PADDING = 2;\nconst PANEL_MIN_WIDTH = 64;\nconst PANEL_OUTER_WIDTH = PANEL_SIDE_PADDING * 2 + 2;\n/** Panels render only when the surface is wide enough to keep the box intact. */\nconst MIN_PANELS_WIDTH = PANEL_MIN_WIDTH + PANEL_OUTER_WIDTH;\nconst RESOURCE_ROW_GAP = \" · \";\nconst CONTEXT_KIND_RANK: Record<StartupDetailItem[\"kind\"], number> = { system: 0, append: 1, context: 2 };\n\n/** `◆ Resources` summary chips. */\nfunction renderResourceChips(resolved: ResolvedTheme, resources: StartupResources | undefined): string {\n\tconst rows = resourceChipRows(resources);\n\tif (rows.length === 0) return \"\";\n\tconst marker = resolved.apply(\"accent\", \"◆ Resources\");\n\tconst chips = rows.map((row, index) => {\n\t\tconst label = resolved.apply(index === 0 ? \"text\" : \"muted\", row.label);\n\t\tconst count = resolved.apply(\"success\", String(row.count));\n\t\treturn `${label} ${count}`;\n\t});\n\treturn [marker, ...chips].join(resolved.apply(\"dim\", RESOURCE_ROW_GAP));\n}\n\nfunction sortedContextItems(items: readonly StartupDetailItem[]): StartupDetailItem[] {\n\treturn [...items].sort((a, b) => (CONTEXT_KIND_RANK[a.kind] ?? 9) - (CONTEXT_KIND_RANK[b.kind] ?? 9));\n}\n\nfunction renderPanelBorder(resolved: ResolvedTheme, left: string, right: string, panelWidth: number): string {\n\treturn resolved.apply(\"dim\", `${left}${\"─\".repeat(panelWidth + PANEL_SIDE_PADDING * 2)}${right}`);\n}\n\nfunction renderPanelLine(resolved: ResolvedTheme, content: string, panelWidth: number): string {\n\tconst sidePadding = \" \".repeat(PANEL_SIDE_PADDING);\n\tconst padding = \" \".repeat(Math.max(0, panelWidth - visibleWidth(content)));\n\treturn `${resolved.apply(\"dim\", \"│\")}${sidePadding}${content}${padding}${sidePadding}${resolved.apply(\"dim\", \"│\")}`;\n}\n\n/** Boxed System & Context table. */\nfunction renderSystemContextPanel(\n\tresolved: ResolvedTheme,\n\titems: readonly StartupDetailItem[],\n\tminTotalWidth: number,\n): string[] {\n\tconst sorted = sortedContextItems(items);\n\tconst titleLine = resolved.apply(\"accent\", \"System & Context\");\n\tif (sorted.length === 0) return [];\n\tconst typeHeader = \"Type\";\n\tconst pathHeader = \"Path\";\n\tconst metricLabel = \"Words/Lines\";\n\tconst typeWidth = Math.max(typeHeader.length, ...sorted.map((item) => visibleWidth(item.kind)));\n\tconst divider = resolved.apply(\"muted\", \" | \");\n\tconst dividerWidth = visibleWidth(divider);\n\tconst metricWidth = Math.max(metricLabel.length, ...sorted.map((item) => `${item.words}/${item.lines}`.length));\n\tconst fixedColumnsWidth = typeWidth + dividerWidth + dividerWidth + metricWidth;\n\tconst panelWidth = Math.max(PANEL_MIN_WIDTH, minTotalWidth - PANEL_OUTER_WIDTH, visibleWidth(titleLine));\n\tconst pathWidth = Math.max(pathHeader.length, panelWidth - fixedColumnsWidth);\n\tconst header = `${resolved.apply(\"text\", typeHeader.padEnd(typeWidth))}${divider}${resolved.apply(\n\t\t\"text\",\n\t\tpathHeader.padEnd(pathWidth),\n\t)}${divider}${resolved.apply(\"text\", metricLabel.padStart(metricWidth))}`;\n\tconst separator = `${resolved.apply(\"dim\", \"─\".repeat(typeWidth))}${divider}${resolved.apply(\n\t\t\"dim\",\n\t\t\"─\".repeat(pathWidth),\n\t)}${divider}${resolved.apply(\"dim\", \"─\".repeat(metricWidth))}`;\n\tconst lines = [\n\t\trenderPanelBorder(resolved, \"╭\", \"╮\", panelWidth),\n\t\trenderPanelLine(resolved, titleLine, panelWidth),\n\t\trenderPanelLine(resolved, header, panelWidth),\n\t\trenderPanelLine(resolved, separator, panelWidth),\n\t];\n\tfor (const item of sorted) {\n\t\tconst metric = `${item.words}/${item.lines}`;\n\t\tconst typePadding = \" \".repeat(Math.max(0, typeWidth - visibleWidth(item.kind)));\n\t\tconst path = fitAnsiWidth(item.path, pathWidth);\n\t\tconst pathPadding = \" \".repeat(Math.max(0, pathWidth - visibleWidth(path)));\n\t\tconst metricPadding = \" \".repeat(Math.max(0, metricWidth - visibleWidth(metric)));\n\t\tlines.push(\n\t\t\trenderPanelLine(\n\t\t\t\tresolved,\n\t\t\t\t`${resolved.apply(\"text\", item.kind)}${typePadding}${divider}${resolved.apply(\n\t\t\t\t\t\"text\",\n\t\t\t\t\tpath,\n\t\t\t\t)}${pathPadding}${divider}${metricPadding}${resolved.apply(\"text\", metric)}`,\n\t\t\t\tpanelWidth,\n\t\t\t),\n\t\t);\n\t}\n\tlines.push(renderPanelBorder(resolved, \"╰\", \"╯\", panelWidth));\n\treturn lines;\n}\n\nfunction groupToolDetails(tools: readonly StartupToolItem[]): { source: string; names: string[] }[] {\n\tconst groups = new Map<string, Set<string>>();\n\tfor (const tool of tools) {\n\t\tconst source = tool.source.trim() || \"extension\";\n\t\tconst name = tool.name.trim();\n\t\tif (!name) continue;\n\t\tlet names = groups.get(source);\n\t\tif (!names) {\n\t\t\tnames = new Set();\n\t\t\tgroups.set(source, names);\n\t\t}\n\t\tnames.add(name);\n\t}\n\treturn [...groups.entries()]\n\t\t.map(([source, names]) => ({ source, names: [...names].sort((a, b) => a.localeCompare(b)) }))\n\t\t.sort((a, b) => {\n\t\t\tif (a.source === \"core\") return -1;\n\t\t\tif (b.source === \"core\") return 1;\n\t\t\treturn a.source.localeCompare(b.source);\n\t\t});\n}\n\n/** Boxed Available Tools table. */\nfunction renderToolsPanel(resolved: ResolvedTheme, tools: readonly StartupToolItem[], minTotalWidth: number): string[] {\n\tconst groups = groupToolDetails(tools);\n\tif (groups.length === 0) return [];\n\tconst titleLine = resolved.apply(\"accent\", \"Available Tools\");\n\tconst sourceHeader = \"Source\";\n\tconst countHeader = \"Count\";\n\tconst toolsHeader = \"Tools\";\n\tconst countWidth = Math.max(countHeader.length, ...groups.map((group) => String(group.names.length).length));\n\tconst divider = resolved.apply(\"muted\", \" | \");\n\tconst dividerWidth = visibleWidth(divider);\n\tconst panelWidth = Math.max(PANEL_MIN_WIDTH, minTotalWidth - PANEL_OUTER_WIDTH, visibleWidth(titleLine));\n\tconst availableTextWidth = Math.max(\n\t\tsourceHeader.length + toolsHeader.length,\n\t\tpanelWidth - countWidth - dividerWidth * 2,\n\t);\n\tconst maxSourceWidth = Math.max(sourceHeader.length, ...groups.map((group) => visibleWidth(group.source)));\n\tconst sourceWidth = Math.min(maxSourceWidth, Math.max(sourceHeader.length, Math.floor(availableTextWidth * 0.28)));\n\tconst toolsWidth = Math.max(toolsHeader.length, availableTextWidth - sourceWidth);\n\tconst header = `${resolved.apply(\"text\", sourceHeader.padEnd(sourceWidth))}${divider}${resolved.apply(\n\t\t\"text\",\n\t\tcountHeader.padStart(countWidth),\n\t)}${divider}${resolved.apply(\"text\", toolsHeader.padEnd(toolsWidth))}`;\n\tconst separator = `${resolved.apply(\"dim\", \"─\".repeat(sourceWidth))}${divider}${resolved.apply(\n\t\t\"dim\",\n\t\t\"─\".repeat(countWidth),\n\t)}${divider}${resolved.apply(\"dim\", \"─\".repeat(toolsWidth))}`;\n\tconst lines = [\n\t\trenderPanelBorder(resolved, \"╭\", \"╮\", panelWidth),\n\t\trenderPanelLine(resolved, titleLine, panelWidth),\n\t\trenderPanelLine(resolved, header, panelWidth),\n\t\trenderPanelLine(resolved, separator, panelWidth),\n\t];\n\tfor (const group of groups) {\n\t\tconst count = String(group.names.length);\n\t\tconst toolList = fitAnsiWidth(group.names.join(\", \"), toolsWidth);\n\t\tconst source = fitAnsiWidth(group.source, sourceWidth);\n\t\tconst sourcePadding = \" \".repeat(Math.max(0, sourceWidth - visibleWidth(source)));\n\t\tconst countPadding = \" \".repeat(Math.max(0, countWidth - count.length));\n\t\tlines.push(\n\t\t\trenderPanelLine(\n\t\t\t\tresolved,\n\t\t\t\t`${resolved.apply(\"text\", source)}${sourcePadding}${divider}${countPadding}${resolved.apply(\n\t\t\t\t\t\"success\",\n\t\t\t\t\tcount,\n\t\t\t\t)}${divider}${resolved.apply(\"text\", toolList)}`,\n\t\t\t\tpanelWidth,\n\t\t\t),\n\t\t);\n\t}\n\tlines.push(renderPanelBorder(resolved, \"╰\", \"╯\", panelWidth));\n\treturn lines;\n}\n\n/** Left margin for the whole startup block so it does not touch the terminal edge. */\nconst STARTUP_INDENT = \" \";\n/** Blank rows above the block, separating it from the status line / terminal top. */\nconst STARTUP_PADDING_TOP = 2;\n/** Blank rows below the block, separating it from the editor / chat. */\nconst STARTUP_PADDING_BOTTOM = 2;\n\nfunction styledLines(\n\ttheme: ActiveTheme,\n\tconfig: NormalizedPiStyleConfig,\n\tsnapshot: StartupSnapshot,\n\toverlay: boolean,\n\twidth: number,\n): string[] {\n\tif (width <= 0 || config.startup.mode === \"off\") return [];\n\tconst resolved = resolveTheme(theme, config);\n\tconst lines: string[] = [];\n\tconst indentWidth = visibleWidth(STARTUP_INDENT);\n\tconst bodyWidth = Math.max(1, width - indentWidth);\n\tconst indent = (content: string): string => `${STARTUP_INDENT}${content}`;\n\n\t// Breathing room above the block (separates it from the status line / terminal top).\n\tlines.push(...Array.from({ length: STARTUP_PADDING_TOP }, () => \"\"));\n\n\tconst logoTitle = resolved.mode === \"ascii\" ? \"pi-style\" : `${resolved.glyph(\"pi\")} pi-style`;\n\tlines.push(\n\t\t...compactLogoHeader(\n\t\t\tresolved,\n\t\t\t[\n\t\t\t\tresolved.apply(\"accent\", logoTitle),\n\t\t\t\tresolved.apply(\"muted\", \"/ commands · ! bash\"),\n\t\t\t\tresolved.apply(\"success\", \"● ready\"),\n\t\t\t],\n\t\t\tbodyWidth,\n\t\t).map(indent),\n\t);\n\n\tconst info: string[] = [];\n\tif (config.startup.showResources) {\n\t\tconst chips = renderResourceChips(resolved, snapshot.resources);\n\t\tif (chips) info.push(chips);\n\t\tif (snapshot.resources?.error)\n\t\t\tinfo.push(resolved.apply(\"muted\", `resources unavailable · ${snapshot.resources.error}`));\n\t}\n\tif (info.length > 0) lines.push(\"\", ...info.map(indent));\n\n\tconst expanded = overlay || config.startup.alwaysExpanded;\n\tif (expanded && bodyWidth >= MIN_PANELS_WIDTH && config.startup.showResources) {\n\t\tconst contextItems = snapshot.resources?.details ?? [];\n\t\tconst toolItems = snapshot.resources?.toolDetails ?? [];\n\t\tif (contextItems.length > 0) {\n\t\t\tlines.push(\"\");\n\t\t\tlines.push(...renderSystemContextPanel(resolved, contextItems, bodyWidth).map(indent));\n\t\t}\n\t\tif (toolItems.length > 0) {\n\t\t\tlines.push(\"\");\n\t\t\tlines.push(...renderToolsPanel(resolved, toolItems, bodyWidth).map(indent));\n\t\t}\n\t}\n\n\t// Breathing room below the block (separates it from the editor / chat).\n\tlines.push(...Array.from({ length: STARTUP_PADDING_BOTTOM }, () => \"\"));\n\tif (overlay) lines.push(indent(resolved.apply(\"dim\", \"enter prompt to continue · esc dismiss\")));\n\n\treturn lines.map((line) => (visibleWidth(line) <= width ? line : truncateAnsi(line, width, \"\")));\n}\n\nclass StartupComponent implements Component {\n\tprivate snapshot: StartupSnapshot;\n\tprivate config: NormalizedPiStyleConfig;\n\tprivate readonly theme: ActiveTheme;\n\tprivate readonly overlay: boolean;\n\tprivate readonly requestRender: () => void;\n\n\tconstructor(\n\t\ttheme: ActiveTheme,\n\t\tconfig: NormalizedPiStyleConfig,\n\t\tsnapshot: StartupSnapshot,\n\t\toverlay: boolean,\n\t\trequestRender: () => void,\n\t) {\n\t\tthis.theme = theme;\n\t\tthis.config = config;\n\t\tthis.snapshot = snapshot;\n\t\tthis.overlay = overlay;\n\t\tthis.requestRender = requestRender;\n\t}\n\n\tsetSnapshot(snapshot: StartupSnapshot): void {\n\t\tthis.snapshot = snapshot;\n\t\tthis.invalidate();\n\t}\n\n\tsetConfig(config: NormalizedPiStyleConfig): void {\n\t\tthis.config = config;\n\t\tthis.invalidate();\n\t}\n\n\trender(width: number): string[] {\n\t\treturn styledLines(this.theme, this.config, this.snapshot, this.overlay, width);\n\t}\n\n\tinvalidate(): void {\n\t\tthis.requestRender();\n\t}\n}\n\nexport function renderStartup(\n\tsnapshot: StartupSnapshot,\n\tconfig: NormalizedPiStyleConfig,\n\ttheme: ActiveTheme,\n\twidth: number,\n\toverlay = false,\n): string[] {\n\treturn styledLines(theme, config, snapshot, overlay, width);\n}\n\nexport function installStartup(options: StartupInstallOptions): StartupInstallation | undefined {\n\tconst { host } = options;\n\tif (options.config.startup.mode === \"off\" || !shouldShow(options.snapshot.reason, options.config.startup.mode))\n\t\treturn undefined;\n\tif (!host.hasUI || host.mode !== \"tui\") return undefined;\n\tconst token = Symbol(\"pi-style.startup\");\n\tconst map = ownerMap(host as object);\n\tlet config = options.config;\n\tlet snapshot = options.snapshot;\n\tlet disposed = false;\n\tlet dismissed = false;\n\tlet headerInstalled = false;\n\tlet installedHeaderFactory: unknown;\n\tlet widgetInstalled = false;\n\tlet overlayHandle: OverlayHandle | undefined;\n\tlet removeInput: (() => void) | undefined;\n\tlet timeout: ReturnType<typeof setTimeout> | undefined;\n\tlet overlayDone: ((value: undefined) => void) | undefined;\n\tconst components: StartupComponent[] = [];\n\tconst timeoutMs = options.timeoutMs;\n\tconst component = (theme: unknown, isOverlay: boolean, tui: { requestRender?: () => void }) => {\n\t\tconst result = new StartupComponent(activeThemeFromPi(theme), config, snapshot, isOverlay, () => {\n\t\t\ttui.requestRender?.();\n\t\t\toptions.requestRender?.();\n\t\t});\n\t\tcomponents.push(result);\n\t\treturn result;\n\t};\n\tconst clearTimer = () => {\n\t\tif (timeout) clearTimeout(timeout);\n\t\ttimeout = undefined;\n\t};\n\tconst dismiss = () => {\n\t\tif (disposed || dismissed) return;\n\t\tdismissed = true;\n\t\tclearTimer();\n\t\toverlayHandle?.hide();\n\t\toverlayHandle = undefined;\n\t\toverlayDone?.(undefined);\n\t\toverlayDone = undefined;\n\t};\n\tconst clearHeader = () => {\n\t\tif (!headerInstalled || map.get(\"header\") !== token) return;\n\t\tconst current = host.getHeaderFactory?.();\n\t\tif (host.getHeaderFactory && current !== installedHeaderFactory) return;\n\t\tif (host.setHeader) safeCall(() => host.setHeader?.(undefined));\n\t\tmap.delete(\"header\");\n\t};\n\tconst clearWidget = () => {\n\t\tif (!widgetInstalled || map.get(STARTUP_WIDGET_KEY) !== token) return;\n\t\tif (host.setWidget) safeCall(() => host.setWidget?.(STARTUP_WIDGET_KEY, undefined));\n\t\tmap.delete(STARTUP_WIDGET_KEY);\n\t};\n\tconst mountCompact = (): boolean => {\n\t\tconst factory = (tui: unknown, theme: unknown) => component(theme, false, tui as { requestRender?: () => void });\n\t\t// Pi's public `setHeader` is the intended startup-header surface (\"shown at\n\t\t// startup, above chat\"). Prefer it so the startup renders at the top of the\n\t\t// terminal rather than inside the editor area. The injected ownership\n\t\t// adapter, when present, still guards against overwriting a later owner;\n\t\t// the widget remains the fallback when the header API is unavailable.\n\t\tlet currentHeader: unknown = Symbol(\"unreadable\");\n\t\tconst observable =\n\t\t\thost.getHeaderFactory &&\n\t\t\tsafeCall(() => {\n\t\t\t\tcurrentHeader = host.getHeaderFactory?.();\n\t\t\t});\n\t\tconst headerAvailable = host.setHeader !== undefined && (!observable || currentHeader === undefined);\n\t\tif (headerAvailable && safeCall(() => host.setHeader?.(factory))) {\n\t\t\tinstalledHeaderFactory = factory;\n\t\t\theaderInstalled = true;\n\t\t\tmap.set(\"header\", token);\n\t\t\treturn true;\n\t\t}\n\t\tif (host.setWidget && safeCall(() => host.setWidget?.(STARTUP_WIDGET_KEY, factory, { placement: \"aboveEditor\" }))) {\n\t\t\twidgetInstalled = true;\n\t\t\tmap.set(STARTUP_WIDGET_KEY, token);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t};\n\tconst mountOverlay = () => {\n\t\tif (!host.custom || !overlayAllowed(snapshot.reason)) {\n\t\t\tmountCompact();\n\t\t\treturn;\n\t\t}\n\t\tconst overlayOptions: OverlayOptions = {\n\t\t\tanchor: \"center\",\n\t\t\twidth: \"80%\",\n\t\t\tmaxHeight: \"60%\",\n\t\t\tminWidth: 40,\n\t\t\tvisible: (width, height) => width >= 40 && height >= 8,\n\t\t};\n\t\tvoid host\n\t\t\t.custom<undefined>(\n\t\t\t\t(tui, theme, _keybindings, done) => {\n\t\t\t\t\toverlayDone = done;\n\t\t\t\t\treturn component(theme, true, tui as { requestRender?: () => void });\n\t\t\t\t},\n\t\t\t\t{ overlay: true, overlayOptions, onHandle: (handle) => (overlayHandle = handle) },\n\t\t\t)\n\t\t\t.catch(() => {\n\t\t\t\tif (!disposed && !dismissed) {\n\t\t\t\t\tclearTimer();\n\t\t\t\t\tmountCompact();\n\t\t\t\t}\n\t\t\t});\n\t};\n\tconst installation: StartupInstallation = {\n\t\tgeneration: options.generation,\n\t\tupdate(next) {\n\t\t\tif (disposed || options.isCurrent?.() === false) return;\n\t\t\tsnapshot = next;\n\t\t\tfor (const item of components) item.setSnapshot(next);\n\t\t\toptions.requestRender?.();\n\t\t},\n\t\tdismiss,\n\t\tconfigure(next) {\n\t\t\tif (disposed || options.isCurrent?.() === false) return;\n\t\t\tconfig = next;\n\t\t\tfor (const item of components) item.setConfig(next);\n\t\t\tif (next.startup.mode === \"off\") {\n\t\t\t\tdismiss();\n\t\t\t\tclearHeader();\n\t\t\t\tclearWidget();\n\t\t\t}\n\t\t\toptions.requestRender?.();\n\t\t},\n\t\tdispose() {\n\t\t\tif (disposed) return;\n\t\t\tdismiss();\n\t\t\tdisposed = true;\n\t\t\tremoveInput?.();\n\t\t\tremoveInput = undefined;\n\t\t\tclearHeader();\n\t\t\tclearWidget();\n\t\t\tmap.delete(\"installation\");\n\t\t},\n\t};\n\tmap.set(\"installation\", token);\n\tremoveInput = host.onTerminalInput?.(() => dismiss());\n\tif (config.startup.mode === \"compact\" && !mountCompact()) {\n\t\tinstallation.dispose();\n\t\treturn undefined;\n\t}\n\tif (config.startup.mode === \"overlay\") mountOverlay();\n\tif (config.startup.mode === \"overlay\" && timeoutMs !== undefined && timeoutMs >= 0) {\n\t\ttimeout = setTimeout(() => dismiss(), timeoutMs);\n\t}\n\treturn installation;\n}\n","import type {\n\tSegmentContext,\n\tSegmentRenderResult,\n\tStatusLayout,\n\tStatusRenderResult,\n\tStatusSegment,\n\tStatusSegmentId,\n\tStatusSnapshot,\n} from \"../domain/status.js\";\nimport type { ResolvedTheme } from \"../domain/theme.js\";\nimport { truncateAnsi, visibleWidth } from \"../shared/ansi.js\";\n\nexport interface StatusRendererOptions {\n\treadonly separator?: string;\n\treadonly padding?: string;\n\treadonly segments: ReadonlyMap<StatusSegmentId, StatusSegment>;\n\treadonly theme: ResolvedTheme;\n\treadonly options?: Readonly<\n\t\tRecord<string, { readonly disabled?: boolean; readonly [key: string]: unknown } | undefined>\n\t>;\n}\n\ninterface Candidate {\n\treadonly id: StatusSegmentId;\n\treadonly segment: StatusSegment;\n\treadonly result: SegmentRenderResult;\n\tcontent: string;\n\tcompact: boolean;\n\tmoved: boolean;\n}\n\nfunction uniqueLayout(layout: StatusLayout): StatusLayout {\n\tconst seen = new Set<StatusSegmentId>();\n\tconst dedupe = (items: readonly StatusSegmentId[]) =>\n\t\titems.filter((id) => {\n\t\t\tif (seen.has(id)) return false;\n\t\t\tseen.add(id);\n\t\t\treturn true;\n\t\t});\n\treturn { left: dedupe(layout.left), right: dedupe(layout.right), secondary: dedupe(layout.secondary) };\n}\n\nfunction renderGroup(items: readonly Candidate[], separator: string, padding: string): string {\n\treturn items\n\t\t.map((item) => item.content)\n\t\t.filter(Boolean)\n\t\t.join(`${padding}${separator}${padding}`);\n}\n\nfunction widthOf(items: readonly Candidate[], separator: string, padding: string): number {\n\treturn visibleWidth(renderGroup(items, separator, padding));\n}\n\nexport function renderStatus(\n\tlayout: StatusLayout,\n\tsnapshot: StatusSnapshot,\n\twidth: number,\n\toptions: StatusRendererOptions,\n): StatusRenderResult {\n\tif (width <= 0) return { primary: \"\", lines: [], visibleSegments: [] };\n\tconst separator = options.separator ?? \"│\";\n\tconst padding = options.padding ?? \" \";\n\tconst normalized = uniqueLayout(layout);\n\tconst context: SegmentContext = { snapshot, theme: options.theme, options: options.options ?? {}, width };\n\tconst candidates = new Map<StatusSegmentId, Candidate>();\n\tfor (const id of [...normalized.left, ...normalized.right, ...normalized.secondary]) {\n\t\tif (candidates.has(id)) continue;\n\t\tconst segment = options.segments.get(id);\n\t\tif (!segment || options.options?.[id]?.disabled) continue;\n\t\ttry {\n\t\t\tconst result = segment.render(context);\n\t\t\tif (!result.visible || !result.content) continue;\n\t\t\tcandidates.set(id, { id, segment, result, content: result.content, compact: false, moved: false });\n\t\t} catch {\n\t\t\t// A broken optional segment must not break the status row.\n\t\t}\n\t}\n\tconst primary = [...normalized.left, ...normalized.right]\n\t\t.map((id) => candidates.get(id))\n\t\t.filter((candidate): candidate is Candidate => candidate !== undefined)\n\t\t.sort(\n\t\t\t(a, b) =>\n\t\t\t\t(b.segment.essential ? 1 : 0) - (a.segment.essential ? 1 : 0) ||\n\t\t\t\tb.segment.defaultPriority - a.segment.defaultPriority,\n\t\t);\n\tconst secondary = normalized.secondary\n\t\t.map((id) => candidates.get(id))\n\t\t.filter((candidate): candidate is Candidate => candidate !== undefined);\n\tconst visible: Candidate[] = [];\n\tconst overflow: Candidate[] = [];\n\tfor (const candidate of primary) {\n\t\tvisible.push(candidate);\n\t\tif (widthOf(visible, separator, padding) <= width) continue;\n\t\tif (candidate.result.compactContent && !candidate.compact) {\n\t\t\tcandidate.content = candidate.result.compactContent;\n\t\t\tcandidate.compact = true;\n\t\t\tif (widthOf(visible, separator, padding) <= width) continue;\n\t\t}\n\t\tvisible.pop();\n\t\tif (candidate.segment.overflow !== \"drop\" && candidate.segment.overflow !== \"primary\") {\n\t\t\tcandidate.moved = true;\n\t\t\toverflow.push(candidate);\n\t\t}\n\t}\n\tfor (const candidate of [...overflow].sort((a, b) => b.segment.defaultPriority - a.segment.defaultPriority))\n\t\tsecondary.push(candidate);\n\t// Right-aligned trailing group: layout.right candidates render flush to the\n\t// right edge, mirroring Pi's native footer (model • effort on the far right).\n\t// Group order follows the layout declaration; the priority sort above only\n\t// decides what drops on overflow.\n\tconst visibleIds = new Set(visible.map((candidate) => candidate.id));\n\tconst groupOf = (group: readonly StatusSegmentId[]) =>\n\t\tgroup\n\t\t\t.map((id) => candidates.get(id))\n\t\t\t.filter((candidate): candidate is Candidate => candidate !== undefined && visibleIds.has(candidate.id));\n\tconst leftVisible = groupOf(normalized.left);\n\tconst rightVisible = groupOf(normalized.right);\n\tconst leftText = renderGroup(leftVisible, separator, padding);\n\tconst rightText = renderGroup(rightVisible, separator, padding);\n\tlet primaryText: string;\n\tif (!rightText) {\n\t\tprimaryText = leftText;\n\t} else {\n\t\tconst core = leftText ? `${leftText}${padding}${separator}${padding}` : \"\";\n\t\tconst gap = Math.max(2, width - visibleWidth(core) - visibleWidth(rightText));\n\t\tprimaryText = `${core}${\" \".repeat(gap)}${rightText}`;\n\t}\n\tif (visibleWidth(primaryText) > width) primaryText = truncateAnsi(primaryText, width);\n\tconst secondaryVisible: Candidate[] = [];\n\tfor (const candidate of [...secondary].sort((a, b) => b.segment.defaultPriority - a.segment.defaultPriority)) {\n\t\tsecondaryVisible.push(candidate);\n\t\tif (widthOf(secondaryVisible, separator, padding) > width) secondaryVisible.pop();\n\t}\n\tconst secondaryText = renderGroup(secondaryVisible, separator, padding);\n\tconst lines = secondaryText ? [primaryText, secondaryText] : primaryText ? [primaryText] : [];\n\treturn {\n\t\tprimary: primaryText,\n\t\t...(secondaryText ? { secondary: secondaryText } : {}),\n\t\tlines,\n\t\tvisibleSegments: [...visible, ...secondaryVisible].map((candidate) => candidate.id),\n\t};\n}\n","import type { NormalizedPiStyleConfig } from \"../../domain/config-types.js\";\nimport { createBuiltinSegments, type SegmentContext, type StatusSnapshot } from \"../../domain/status.js\";\nimport { renderStatus } from \"../../domain/status-renderer.js\";\nimport { type ResolvedTheme, resolveTheme } from \"../../domain/theme.js\";\nimport { visibleWidth } from \"../../shared/ansi.js\";\n\nexport const PRIMARY_WIDGET_KEY = \"pi-style.status.primary\";\nexport const SECONDARY_WIDGET_KEY = \"pi-style.status.secondary\";\n\ntype WidgetPlacement = \"aboveEditor\" | \"belowEditor\";\ntype RenderComponent = { render(width: number): string[]; invalidate(): void; dispose?(): void };\ntype WidgetFactory = (tui: { requestRender?: () => void }, theme: ActivePiTheme) => RenderComponent;\n\n/** Read-only view of Pi's footer data provider, kept out of the domain layer. */\nexport interface FooterDataProviderView {\n\tgetGitBranch(): string | null;\n\tgetExtensionStatuses(): ReadonlyMap<string, string>;\n\tonBranchChange(callback: () => void): () => void;\n}\n\ntype FooterFactory = (\n\ttui: { requestRender?: (force?: boolean) => void },\n\t// The footer renders nothing, so the theme is intentionally untyped.\n\ttheme: unknown,\n\tfooterData: FooterDataProviderView,\n) => RenderComponent;\n\n/** Minimal structural view of Pi's theme, kept out of the domain layer. */\nexport interface ActivePiTheme {\n\tfg?: (token: string, text: string) => string;\n\tcolors?: Record<string, string>;\n}\n\nexport interface StatusLineWidgetHost {\n\tsetWidget(\n\t\tkey: string,\n\t\tcontent: string[] | WidgetFactory | undefined,\n\t\toptions?: { placement?: WidgetPlacement },\n\t): void;\n\t/** Replace the native Pi footer with a pi-style owned component; undefined restores it. */\n\tsetFooter(factory: FooterFactory | undefined): void;\n}\n\nexport interface StatusLineInstallation {\n\treadonly generation: number;\n\treadonly primaryKey: typeof PRIMARY_WIDGET_KEY;\n\treadonly secondaryKey: typeof SECONDARY_WIDGET_KEY;\n\tupdate(snapshot: StatusSnapshot): void;\n\tconfigure(config: NormalizedPiStyleConfig): void;\n\tdispose(): void;\n}\n\nexport interface StatusLineInstallOptions {\n\thost: StatusLineWidgetHost;\n\tconfig: NormalizedPiStyleConfig;\n\tgeneration: number;\n\tinitialSnapshot: StatusSnapshot;\n\tisCurrent?: () => boolean;\n\t/** Force a full terminal redraw (clear screen + scrollback) on the first footer mount. */\n\tclearOnStartup?: boolean;\n}\n\ninterface Ownership {\n\ttoken: symbol;\n\tgeneration: number;\n}\n\nconst ownership = new WeakMap<object, Map<string, Ownership>>();\nconst activeInstallations = new WeakMap<object, Map<number, StatusLineInstallation>>();\n\nfunction ownerMap(host: object): Map<string, Ownership> {\n\tlet map = ownership.get(host);\n\tif (!map) {\n\t\tmap = new Map();\n\t\townership.set(host, map);\n\t}\n\treturn map;\n}\nfunction installationMap(host: object): Map<number, StatusLineInstallation> {\n\tlet map = activeInstallations.get(host);\n\tif (!map) {\n\t\tmap = new Map();\n\t\tactiveInstallations.set(host, map);\n\t}\n\treturn map;\n}\nfunction safeWidget(\n\thost: StatusLineWidgetHost,\n\tkey: string,\n\tcontent: string[] | WidgetFactory | undefined,\n\tplacement?: WidgetPlacement,\n): boolean {\n\ttry {\n\t\thost.setWidget(key, content, placement ? { placement } : undefined);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\nfunction placementFor(config: NormalizedPiStyleConfig): WidgetPlacement {\n\treturn config.placement === \"below\" ? \"belowEditor\" : \"aboveEditor\";\n}\nfunction separatorsFor(config: NormalizedPiStyleConfig, theme: ResolvedTheme): string {\n\tconst style = config.statusLine.separator;\n\tif (style === \"powerline\") return theme.apply(\"separator\", theme.glyph(\"powerlineLeft\"));\n\tif (style === \"powerline-thin\" || style === \"\" || style === undefined) {\n\t\treturn theme.apply(\"separator\", theme.glyph(\"powerlineThinLeft\"));\n\t}\n\tif (style === \"none\") return \" \";\n\treturn theme.apply(\"separator\", style);\n}\n\nexport function installStatusLine(options: StatusLineInstallOptions): StatusLineInstallation {\n\tconst existing = installationMap(options.host).get(options.generation);\n\tif (existing) return existing;\n\tconst token = Symbol(\"pi-style.status-line\");\n\tconst owners = ownerMap(options.host);\n\tlet config = options.config;\n\tlet snapshot: StatusSnapshot = options.initialSnapshot;\n\tlet disposed = false;\n\tlet primaryComponent: RenderComponent | undefined;\n\tlet secondaryComponent: RenderComponent | undefined;\n\tlet footerData: FooterDataProviderView | undefined;\n\tlet footerOwner = false;\n\tlet footerUnsubscribe: (() => void) | undefined;\n\tlet clearedOnStartup = false;\n\tconst segments = new Map(createBuiltinSegments());\n\tfor (const item of config.statusLine.customItems) {\n\t\tif (!item.id || !item.statusKey) continue;\n\t\tsegments.set(item.id, {\n\t\t\tid: item.id,\n\t\t\tdefaultPriority: item.priority ?? 40,\n\t\t\toverflow: \"secondary\",\n\t\t\trender: ({ snapshot }: SegmentContext) => {\n\t\t\t\tconst status = snapshot.extensionStatuses?.find(\n\t\t\t\t\t(entry: { readonly key: string; readonly value: string }) => entry.key === item.statusKey,\n\t\t\t\t);\n\t\t\t\tif (!status) return { visible: false, content: \"\" };\n\t\t\t\treturn { visible: true, content: `${item.label ? `${item.label}:` : \"\"}${status.value}`, truncatable: true };\n\t\t\t},\n\t\t});\n\t}\n\n\tconst render = (activeTheme: ActivePiTheme, width: number, secondary: boolean): string[] => {\n\t\tif (width <= 0 || !config.enabled || !config.statusLine.enabled) return [];\n\t\tconst resolved = resolveTheme(\n\t\t\tactiveTheme.colors || activeTheme.fg\n\t\t\t\t? {\n\t\t\t\t\t\t...(activeTheme.colors ? { colors: activeTheme.colors } : {}),\n\t\t\t\t\t\t// Call through the theme instance so `this` binds correctly inside Pi's fg().\n\t\t\t\t\t\t...(activeTheme.fg ? { fg: (color: string, text: string) => activeTheme.fg?.(color, text) ?? text } : {}),\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\t\tconfig,\n\t\t);\n\t\tconst result = renderStatus(config.statusLine.layout, effectiveSnapshot(snapshot), width, {\n\t\t\tseparator: separatorsFor(config, resolved),\n\t\t\tsegments,\n\t\t\ttheme: resolved,\n\t\t\toptions: {\n\t\t\t\t...Object.fromEntries(config.statusLine.disabledSegments.map((id) => [id, { disabled: true }])),\n\t\t\t\tcontext_bar: { width: config.statusLine.contextBarWidth },\n\t\t\t},\n\t\t});\n\t\tconst lines = secondary ? result.lines.slice(1) : result.lines.slice(0, 1);\n\t\tconst rendered = lines.filter((line) => visibleWidth(line) <= width);\n\t\tif (!secondary && rendered.length > 0 && config.statusLine.bottomMargin > 0) {\n\t\t\t// Blank rows below the primary row keep the status line off the terminal edge.\n\t\t\treturn [...rendered, ...Array.from({ length: config.statusLine.bottomMargin }, () => \"\")];\n\t\t}\n\t\treturn rendered;\n\t};\n\t/** Merge authoritative native footer data (branch + extension statuses) into the snapshot. */\n\tconst effectiveSnapshot = (input: StatusSnapshot): StatusSnapshot => {\n\t\tif (!footerData) return input;\n\t\tconst statuses = footerData.getExtensionStatuses();\n\t\tconst extensionStatuses = statuses.size > 0 ? [...statuses].map(([key, value]) => ({ key, value })) : undefined;\n\t\tconst branch = footerData.getGitBranch();\n\t\tconst git = branch && input.git ? { ...input.git, branch } : input.git;\n\t\treturn {\n\t\t\t...input,\n\t\t\t...(extensionStatuses ? { extensionStatuses } : {}),\n\t\t\t...(git ? { git } : {}),\n\t\t};\n\t};\n\tconst releaseFooterData = (): void => {\n\t\tfooterUnsubscribe?.();\n\t\tfooterUnsubscribe = undefined;\n\t\tfooterData = undefined;\n\t};\n\tconst footerFactory: FooterFactory = (tui, _theme, data) => {\n\t\tfooterData = data;\n\t\tfooterUnsubscribe?.();\n\t\tfooterUnsubscribe = data.onBranchChange(() => {\n\t\t\tprimaryComponent?.invalidate();\n\t\t\tsecondaryComponent?.invalidate();\n\t\t\ttui.requestRender?.();\n\t\t});\n\t\tif (options.clearOnStartup && !clearedOnStartup) {\n\t\t\tclearedOnStartup = true;\n\t\t\t// Force a full redraw on the first frame: clears the screen and scrollback.\n\t\t\ttui.requestRender?.(true);\n\t\t}\n\t\treturn {\n\t\t\t// The native footer is replaced by an empty component; visible status lives in widgets.\n\t\t\trender() {\n\t\t\t\treturn [];\n\t\t\t},\n\t\t\tinvalidate() {\n\t\t\t\ttui.requestRender?.();\n\t\t\t},\n\t\t\tdispose() {\n\t\t\t\treleaseFooterData();\n\t\t\t},\n\t\t};\n\t};\n\tconst mountFooter = (): void => {\n\t\tif (disposed || options.isCurrent?.() === false) return;\n\t\tif (!config.enabled || !config.statusLine.enabled) {\n\t\t\tclearFooter();\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\toptions.host.setFooter(footerFactory);\n\t\t\tfooterOwner = true;\n\t\t} catch {\n\t\t\tfooterOwner = false;\n\t\t}\n\t};\n\tconst clearFooter = (): void => {\n\t\tif (!footerOwner) return;\n\t\tfooterOwner = false;\n\t\treleaseFooterData();\n\t\ttry {\n\t\t\toptions.host.setFooter(undefined);\n\t\t} catch {\n\t\t\t// Best-effort restore; cleanup must never throw.\n\t\t}\n\t};\n\tconst factory =\n\t\t(secondary: boolean): WidgetFactory =>\n\t\t(tui, theme) => {\n\t\t\tconst currentTheme = theme;\n\t\t\tconst component: RenderComponent = {\n\t\t\t\trender(width) {\n\t\t\t\t\tconst lines = render(currentTheme, width, secondary);\n\t\t\t\t\treturn lines;\n\t\t\t\t},\n\t\t\t\tinvalidate() {\n\t\t\t\t\t// Pi supplies a fresh theme to the factory on theme replacement. Do not retain\n\t\t\t\t\t// pre-rendered ANSI strings; the next render reads the current component theme.\n\t\t\t\t\tprimaryComponent = secondary ? primaryComponent : component;\n\t\t\t\t\tsecondaryComponent = secondary ? component : secondaryComponent;\n\t\t\t\t\tif (tui.requestRender) tui.requestRender();\n\t\t\t\t},\n\t\t\t\tdispose() {},\n\t\t\t};\n\t\t\tif (secondary) secondaryComponent = component;\n\t\t\telse primaryComponent = component;\n\t\t\treturn component;\n\t\t};\n\tconst claim = (key: string) => owners.set(key, { token, generation: options.generation });\n\tconst mount = () => {\n\t\tif (disposed || options.isCurrent?.() === false) return;\n\t\tif (!config.enabled || !config.statusLine.enabled) {\n\t\t\tclear(PRIMARY_WIDGET_KEY);\n\t\t\tclear(SECONDARY_WIDGET_KEY);\n\t\t\tclearFooter();\n\t\t\treturn;\n\t\t}\n\t\tif (safeWidget(options.host, PRIMARY_WIDGET_KEY, factory(false), placementFor(config))) claim(PRIMARY_WIDGET_KEY);\n\t\tif (safeWidget(options.host, SECONDARY_WIDGET_KEY, factory(true), \"belowEditor\")) claim(SECONDARY_WIDGET_KEY);\n\t\tmountFooter();\n\t};\n\tfunction clear(key: string): void {\n\t\tconst current = owners.get(key);\n\t\tif (current?.token !== token || current.generation !== options.generation) return;\n\t\tif (safeWidget(options.host, key, undefined)) owners.delete(key);\n\t}\n\tconst installation: StatusLineInstallation = {\n\t\tgeneration: options.generation,\n\t\tprimaryKey: PRIMARY_WIDGET_KEY,\n\t\tsecondaryKey: SECONDARY_WIDGET_KEY,\n\t\tupdate(next) {\n\t\t\tif (disposed || options.isCurrent?.() === false) return;\n\t\t\tsnapshot = next;\n\t\t\tprimaryComponent?.invalidate();\n\t\t\tsecondaryComponent?.invalidate();\n\t\t},\n\t\tconfigure(next) {\n\t\t\tif (disposed || options.isCurrent?.() === false) return;\n\t\t\tconst placementChanged = placementFor(next) !== placementFor(config);\n\t\t\tconst enabledChanged = next.enabled !== config.enabled || next.statusLine.enabled !== config.statusLine.enabled;\n\t\t\tconfig = next;\n\t\t\tif (placementChanged || enabledChanged) {\n\t\t\t\tclear(PRIMARY_WIDGET_KEY);\n\t\t\t\tclear(SECONDARY_WIDGET_KEY);\n\t\t\t\tclearFooter();\n\t\t\t\tprimaryComponent = undefined;\n\t\t\t\tsecondaryComponent = undefined;\n\t\t\t\tmount();\n\t\t\t} else {\n\t\t\t\tprimaryComponent?.invalidate();\n\t\t\t\tsecondaryComponent?.invalidate();\n\t\t\t}\n\t\t},\n\t\tdispose() {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\tclear(PRIMARY_WIDGET_KEY);\n\t\t\tclear(SECONDARY_WIDGET_KEY);\n\t\t\tclearFooter();\n\t\t\tinstallationMap(options.host).delete(options.generation);\n\t\t},\n\t};\n\tinstallationMap(options.host).set(options.generation, installation);\n\tmount();\n\treturn installation;\n}\n","export interface Disposable {\n\tdispose(): void | Promise<void>;\n}\n\nexport class DisposableStore implements Disposable {\n\tprivate readonly items: Disposable[] = [];\n\tprivate disposed = false;\n\tadd<T extends Disposable>(item: T): T {\n\t\tif (this.disposed) {\n\t\t\tvoid item.dispose();\n\t\t\treturn item;\n\t\t}\n\t\tthis.items.push(item);\n\t\treturn item;\n\t}\n\taddCallback(callback: () => void | Promise<void>): void {\n\t\tthis.add({ dispose: callback });\n\t}\n\tget size(): number {\n\t\treturn this.items.length;\n\t}\n\tasync dispose(): Promise<void> {\n\t\tif (this.disposed) return;\n\t\tthis.disposed = true;\n\t\tfor (let i = this.items.length - 1; i >= 0; i--) await this.items[i]?.dispose();\n\t\tthis.items.length = 0;\n\t}\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type {\n\tContextProvider,\n\tGitCommandResult,\n\tGitCommandRunner,\n\tGitProvider,\n\tUsageProvider,\n} from \"../domain/providers.js\";\nimport type { ContextSnapshot, GitSnapshot, UsageSnapshot } from \"../domain/status.js\";\n\nconst execFileAsync = promisify(execFile);\nconst EMPTY_USAGE: UsageSnapshot = Object.freeze({\n\tinputTokens: 0,\n\toutputTokens: 0,\n\tcacheReadTokens: 0,\n\tcacheWriteTokens: 0,\n\tstreaming: false,\n\tsubscriptionMode: \"unknown\",\n});\n\nexport class NodeGitCommandRunner implements GitCommandRunner {\n\tasync run(args: readonly string[], cwd: string, timeoutMs: number, signal?: AbortSignal): Promise<GitCommandResult> {\n\t\tif (signal?.aborted) return { stdout: \"\", stderr: \"git command aborted\", code: 1 };\n\t\ttry {\n\t\t\tconst result = await execFileAsync(\"git\", [...args], {\n\t\t\t\tcwd,\n\t\t\t\ttimeout: timeoutMs,\n\t\t\t\tmaxBuffer: 1024 * 1024,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t\treturn { stdout: result.stdout, stderr: result.stderr, code: 0 };\n\t\t} catch (error) {\n\t\t\tconst failure = error as { stdout?: string; stderr?: string; code?: number; signal?: string };\n\t\t\treturn {\n\t\t\t\tstdout: failure.stdout ?? \"\",\n\t\t\t\tstderr: failure.stderr ?? (failure.signal ? `git terminated by ${failure.signal}` : \"git command failed\"),\n\t\t\t\tcode: failure.code ?? 1,\n\t\t\t};\n\t\t}\n\t}\n}\n\ninterface GitEntry {\n\tvalue: GitSnapshot;\n\texpiresAt: number;\n\tretryAt: number;\n\tgeneration: number;\n\tpromise?: Promise<GitSnapshot>;\n\tcontroller?: AbortController;\n\tneedsRefresh?: boolean;\n\tresultReady: boolean;\n}\n\nexport interface GitProviderStats {\n\treadonly entries: number;\n\treadonly inFlight: number;\n\treadonly refreshes: number;\n\treadonly disposed: boolean;\n}\n\nexport interface GitProviderClock {\n\tnow(): number;\n}\n\nexport class CachedGitProvider implements GitProvider {\n\tprivate readonly cache = new Map<string, GitEntry>();\n\tprivate disposed = false;\n\tprivate refreshCount = 0;\n\tconstructor(\n\t\tprivate readonly runner: GitCommandRunner = new NodeGitCommandRunner(),\n\t\tprivate readonly ttlMs = 1000,\n\t\tprivate readonly timeoutMs = 800,\n\t\tprivate readonly maxBackoffMs = 5000,\n\t\tprivate readonly clock: GitProviderClock = { now: () => Date.now() },\n\t) {}\n\tget stats(): GitProviderStats {\n\t\treturn {\n\t\t\tentries: this.cache.size,\n\t\t\tinFlight: [...this.cache.values()].filter((entry) => entry.promise).length,\n\t\t\trefreshes: this.refreshCount,\n\t\t\tdisposed: this.disposed,\n\t\t};\n\t}\n\tasync get(cwd: string): Promise<GitSnapshot> {\n\t\tif (this.disposed) return unavailableGit(\"provider disposed\");\n\t\tconst now = this.clock.now();\n\t\tconst current = this.cache.get(cwd);\n\t\tif (current && current.expiresAt > now && !current.needsRefresh) return current.value;\n\t\tif (current?.promise) return current.resultReady ? current.value : current.promise;\n\t\tif (current && current.retryAt > now) return current.value;\n\t\tconst stale = current?.value;\n\t\tconst entry: GitEntry = current ?? {\n\t\t\tvalue: refreshingGit(),\n\t\t\texpiresAt: 0,\n\t\t\tretryAt: 0,\n\t\t\tgeneration: 0,\n\t\t\tresultReady: false,\n\t\t};\n\t\tentry.needsRefresh = false;\n\t\tentry.resultReady = Boolean(stale);\n\t\tentry.value = stale ? { ...stale, refreshing: true } : refreshingGit();\n\t\tentry.controller = new AbortController();\n\t\tentry.promise = this.refresh(cwd, entry, stale, entry.controller.signal);\n\t\tthis.cache.set(cwd, entry);\n\t\treturn stale ? entry.value : entry.promise;\n\t}\n\tinvalidate(cwd?: string): void {\n\t\tconst keys = cwd === undefined ? [...this.cache.keys()] : [cwd];\n\t\tfor (const key of keys) {\n\t\t\tconst entry = this.cache.get(key);\n\t\t\tif (!entry) continue;\n\t\t\tentry.generation++;\n\t\t\tentry.expiresAt = 0;\n\t\t\tif (entry.promise) entry.needsRefresh = true;\n\t\t\telse this.cache.delete(key);\n\t\t}\n\t}\n\tdispose(): void {\n\t\tif (this.disposed) return;\n\t\tthis.disposed = true;\n\t\tfor (const entry of this.cache.values()) entry.controller?.abort();\n\t\tthis.cache.clear();\n\t}\n\tprivate async refresh(\n\t\tcwd: string,\n\t\tentry: GitEntry,\n\t\tstale: GitSnapshot | undefined,\n\t\tsignal: AbortSignal,\n\t): Promise<GitSnapshot> {\n\t\tthis.refreshCount++;\n\t\tconst generation = entry.generation;\n\t\tlet value: GitSnapshot;\n\t\ttry {\n\t\t\tconst result = await this.runner.run([\"status\", \"--porcelain=v1\", \"--branch\"], cwd, this.timeoutMs, signal);\n\t\t\tif (result.code !== 0) {\n\t\t\t\tvalue = stale\n\t\t\t\t\t? { ...stale, refreshing: false, error: result.stderr.trim() || \"git status failed\" }\n\t\t\t\t\t: unavailableGit(result.stderr.trim() || \"git status failed\");\n\t\t\t} else value = parseGitStatus(result.stdout);\n\t\t} catch (error) {\n\t\t\tvalue = stale ? { ...stale, refreshing: false, error: String(error) } : unavailableGit(String(error));\n\t\t}\n\t\tif (this.disposed || this.cache.get(cwd) !== entry) return value;\n\t\tconst invalidated = entry.generation !== generation || entry.needsRefresh;\n\t\tdelete entry.promise;\n\t\tdelete entry.controller;\n\t\tentry.value = value;\n\t\tentry.resultReady = true;\n\t\tif (invalidated) {\n\t\t\tentry.needsRefresh = false;\n\t\t\tentry.expiresAt = 0;\n\t\t\tvoid this.get(cwd);\n\t\t\treturn value;\n\t\t}\n\t\tentry.retryAt = value.error ? this.clock.now() + Math.min(this.maxBackoffMs, Math.max(this.ttlMs, 100)) : 0;\n\t\tentry.expiresAt = this.clock.now() + this.ttlMs;\n\t\tif (entry.needsRefresh) {\n\t\t\tentry.needsRefresh = false;\n\t\t\tvoid this.get(cwd);\n\t\t}\n\t\treturn value;\n\t}\n}\n\nfunction refreshingGit(): GitSnapshot {\n\treturn Object.freeze({ available: false, branch: null, staged: 0, unstaged: 0, untracked: 0, refreshing: true });\n}\nfunction unavailableGit(error: string): GitSnapshot {\n\treturn Object.freeze({\n\t\tavailable: false,\n\t\tbranch: null,\n\t\tstaged: 0,\n\t\tunstaged: 0,\n\t\tuntracked: 0,\n\t\trefreshing: false,\n\t\terror,\n\t});\n}\nexport function parseGitStatus(output: string): GitSnapshot {\n\tconst lines = output.split(\"\\n\").filter(Boolean);\n\tconst header = lines.find((line) => line.startsWith(\"## \"))?.slice(3) ?? \"\";\n\tif (!header) return unavailableGit(\"not a git repository\");\n\tconst branch = header.split(\"...\")[0]?.replace(/^HEAD \\(no branch\\)$/, \"detached\") ?? null;\n\tlet staged = 0;\n\tlet unstaged = 0;\n\tlet untracked = 0;\n\tfor (const line of lines) {\n\t\tif (line.startsWith(\"## \")) continue;\n\t\tif (line.startsWith(\"??\")) {\n\t\t\tuntracked++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.length < 2) continue;\n\t\tif (line[0] !== \" \") staged++;\n\t\tif (line[1] !== \" \") unstaged++;\n\t}\n\tconst ahead = /\\[ahead (\\d+)\\]/.exec(header)?.[1];\n\tconst behind = /\\[behind (\\d+)\\]/.exec(header)?.[1];\n\treturn Object.freeze({\n\t\tavailable: true,\n\t\tbranch: branch || null,\n\t\tstaged,\n\t\tunstaged,\n\t\tuntracked,\n\t\t...(ahead ? { ahead: Number(ahead) } : {}),\n\t\t...(behind ? { behind: Number(behind) } : {}),\n\t\trefreshing: false,\n\t});\n}\n\nexport class InMemoryUsageProvider implements UsageProvider {\n\tprivate readonly values = new Map<string, UsageSnapshot>();\n\tprivate readonly events = new Map<string, Set<string>>();\n\tprivate readonly finalized = new Map<string, Set<string>>();\n\tget(sessionId: string): UsageSnapshot {\n\t\treturn this.values.get(sessionId) ?? EMPTY_USAGE;\n\t}\n\trecord(\n\t\tsessionId: string,\n\t\tusage: Partial<UsageSnapshot>,\n\t\toptions: { eventId?: string; finalized?: boolean } = {},\n\t): void {\n\t\tif (options.eventId) {\n\t\t\tconst ids = this.events.get(sessionId) ?? new Set<string>();\n\t\t\tconst finalized = this.finalized.get(sessionId) ?? new Set<string>();\n\t\t\tif (finalized.has(options.eventId) || (ids.has(options.eventId) && !options.finalized)) return;\n\t\t\tids.add(options.eventId);\n\t\t\tthis.events.set(sessionId, ids);\n\t\t\tif (options.finalized) {\n\t\t\t\tfinalized.add(options.eventId);\n\t\t\t\tthis.finalized.set(sessionId, finalized);\n\t\t\t}\n\t\t}\n\t\tconst current = this.get(sessionId);\n\t\tconst next = {\n\t\t\t...current,\n\t\t\t...usage,\n\t\t\tstreaming: options.finalized ? false : (usage.streaming ?? current.streaming),\n\t\t};\n\t\tthis.values.set(sessionId, Object.freeze(next));\n\t}\n\treset(sessionId?: string): void {\n\t\tif (sessionId === undefined) {\n\t\t\tthis.values.clear();\n\t\t\tthis.events.clear();\n\t\t\tthis.finalized.clear();\n\t\t\treturn;\n\t\t}\n\t\tthis.values.delete(sessionId);\n\t\tthis.events.delete(sessionId);\n\t\tthis.finalized.delete(sessionId);\n\t}\n}\n\nexport class InMemoryContextProvider implements ContextProvider {\n\tprivate readonly values = new Map<string, ContextSnapshot>();\n\tget(sessionId: string): ContextSnapshot | undefined {\n\t\treturn this.values.get(sessionId);\n\t}\n\tset(sessionId: string, context: ContextSnapshot): void {\n\t\tthis.values.set(sessionId, Object.freeze({ ...context }));\n\t}\n\tclear(sessionId?: string): void {\n\t\tif (sessionId === undefined) this.values.clear();\n\t\telse this.values.delete(sessionId);\n\t}\n}\n","export type UpdateClass = \"immediate\" | \"coalesced\" | \"deferred\" | \"delayed-retry\";\nexport interface SchedulerHost {\n\trequestRender(): void;\n}\n\nexport class RenderScheduler {\n\tprivate stopped = false;\n\tprivate immediateQueued = false;\n\tprivate coalescedTimer: ReturnType<typeof setTimeout> | undefined;\n\tprivate deferredTimer: ReturnType<typeof setTimeout> | undefined;\n\tprivate retryTimer: ReturnType<typeof setTimeout> | undefined;\n\tconstructor(\n\t\tprivate readonly host: SchedulerHost,\n\t\tprivate readonly generation: number,\n\t\tprivate readonly isCurrent: (generation: number) => boolean = (current) => current === this.generation,\n\t) {}\n\tschedule(kind: UpdateClass): void {\n\t\tif (this.stopped || !this.isCurrent(this.generation)) return;\n\t\tif (kind === \"immediate\") {\n\t\t\tif (this.immediateQueued) return;\n\t\t\tthis.immediateQueued = true;\n\t\t\tqueueMicrotask(() => {\n\t\t\t\tthis.immediateQueued = false;\n\t\t\t\tthis.render();\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tconst target = kind === \"coalesced\" ? \"coalescedTimer\" : kind === \"deferred\" ? \"deferredTimer\" : \"retryTimer\";\n\t\tif (this[target] !== undefined) return;\n\t\tconst delay = kind === \"coalesced\" ? 16 : kind === \"deferred\" ? 50 : 100;\n\t\tthis[target] = setTimeout(() => {\n\t\t\tthis[target] = undefined;\n\t\t\tthis.render();\n\t\t}, delay);\n\t}\n\tprivate render(): void {\n\t\tif (!this.stopped && this.isCurrent(this.generation)) this.host.requestRender();\n\t}\n\tcancel(): void {\n\t\tthis.stopped = true;\n\t\tif (this.coalescedTimer !== undefined) clearTimeout(this.coalescedTimer);\n\t\tif (this.deferredTimer !== undefined) clearTimeout(this.deferredTimer);\n\t\tif (this.retryTimer !== undefined) clearTimeout(this.retryTimer);\n\t\tthis.coalescedTimer = undefined;\n\t\tthis.deferredTimer = undefined;\n\t\tthis.retryTimer = undefined;\n\t}\n}\n","import type { StatusSnapshot } from \"../domain/status.js\";\n\nexport interface UiSnapshot extends StatusSnapshot {\n\treadonly revision: number;\n\treadonly generation: number;\n}\n\nexport function createSnapshot(generation: number, revision = 0, values: StatusSnapshot = {}): UiSnapshot {\n\treturn Object.freeze({ generation, revision, ...values });\n}\n\nexport function replaceSnapshot(current: UiSnapshot, generation: number, values: StatusSnapshot): UiSnapshot {\n\tif (current.generation !== generation) return current;\n\treturn createSnapshot(generation, current.revision + 1, values);\n}\n","import type { ExtensionContext, ExtensionUIContext } from \"@earendil-works/pi-coding-agent\";\nimport { diffConfig } from \"../domain/config-diff.js\";\nimport type { NormalizedPiStyleConfig } from \"../domain/config-types.js\";\nimport type { GitCommandRunner } from \"../domain/providers.js\";\nimport type { StatusSnapshot } from \"../domain/status.js\";\nimport { normalizeThinkingLevel } from \"../domain/status.js\";\nimport { installEditor } from \"../features/editor/index.js\";\nimport {\n\tinstallStartup,\n\ttype StartupHost,\n\ttype StartupReason,\n\ttype StartupResources,\n\ttype StartupSnapshot,\n} from \"../features/startup/index.js\";\nimport { installStatusLine } from \"../features/status-line/index.js\";\nimport { DisposableStore } from \"../shared/disposable-store.js\";\nimport { CachedGitProvider, InMemoryContextProvider, InMemoryUsageProvider } from \"./providers.js\";\nimport { RenderScheduler } from \"./render-scheduler.js\";\nimport { createSnapshot, replaceSnapshot, type UiSnapshot } from \"./snapshot.js\";\n\nexport interface RuntimeInstallationState {\n\treadonly status: \"installed\" | \"disabled\" | \"failed\";\n\treadonly editor: \"installed\" | \"preserved\" | \"disabled\" | \"failed\";\n\treadonly startup: \"installed\" | \"disabled\" | \"failed\";\n}\n\nexport interface PiStyleRuntime {\n\tgeneration: number;\n\treadonly providerIdentity: { git: object; context: object; usage: object };\n\treadonly installationState: RuntimeInstallationState;\n\tmode: ExtensionContext[\"mode\"];\n\thasUI: boolean;\n\tdisposed: boolean;\n\tsnapshot: UiSnapshot;\n\tdisposables: DisposableStore;\n\tscheduler: RenderScheduler;\n\tupdate(values: StatusSnapshot): void;\n\tupdateStartupResources(resources: StartupResources): void;\n\tdismissStartup(): void;\n\tinvalidateGit(): void;\n\tconfigure(config: NormalizedPiStyleConfig): void;\n\tdispose(): void;\n}\n\nexport interface RuntimeHost {\n\treadonly mode: ExtensionContext[\"mode\"];\n\treadonly hasUI: boolean;\n\treadonly ui?: ExtensionUIContext;\n\treadonly cwd?: string;\n\treadonly model?: { id?: string; name?: string; provider?: string; reasoning?: boolean } | undefined;\n\treadonly thinkingLevel?: string | undefined;\n\treadonly config: NormalizedPiStyleConfig;\n\treadonly startupReason?: StartupReason;\n\treadonly provider?: string;\n\treadonly requestRender?: () => void;\n\treadonly resources?: StartupResources;\n\treadonly extensionStatusProvider?: () => readonly import(\"../domain/status.js\").ExtensionStatus[] | undefined;\n\treadonly gitRunner?: GitCommandRunner;\n\tgetContextUsage?:\n\t\t| (() => { tokens: number | null; contextWindow: number; percent: number | null } | undefined)\n\t\t| undefined;\n}\n\nexport function createPiStyleRuntime(\n\thost: RuntimeHost,\n\tgeneration: number,\n\trequestRender: () => void = () => {},\n): PiStyleRuntime {\n\tlet disposed = false;\n\tconst extensionStatuses = (): readonly import(\"../domain/status.js\").ExtensionStatus[] | undefined => {\n\t\tif (!host.extensionStatusProvider) return undefined;\n\t\ttry {\n\t\t\treturn host.extensionStatusProvider();\n\t\t} catch {\n\t\t\thost.ui?.notify?.(\"pi-style extension statuses unavailable; provider recovery required\", \"warning\");\n\t\t\treturn [];\n\t\t}\n\t};\n\tlet currentConfig = host.config;\n\tconst disposables = new DisposableStore();\n\tconst scheduler = new RenderScheduler({ requestRender }, generation, () => !disposed);\n\tconst git = new CachedGitProvider(host.gitRunner);\n\tconst contextProvider = new InMemoryContextProvider();\n\tconst usageProvider = new InMemoryUsageProvider();\n\tconst usage = host.getContextUsage?.();\n\tconst initialStatuses = extensionStatuses();\n\tconst initialValues = {\n\t\t...(initialStatuses ? { extensionStatuses: initialStatuses } : {}),\n\t\t...(host.model?.name || host.model?.id ? { model: host.model.name ?? host.model.id } : {}),\n\t\t...(host.model?.provider ? { provider: host.model.provider } : {}),\n\t\t...(host.model?.reasoning !== undefined ? { reasoning: host.model.reasoning } : {}),\n\t\t...(host.thinkingLevel ? { thinkingLevel: normalizeThinkingLevel(host.thinkingLevel) } : {}),\n\t\t...(host.cwd ? { cwd: host.cwd } : {}),\n\t\t...(usage\n\t\t\t? {\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\t...(usage.tokens !== null ? { currentTokens: usage.tokens } : {}),\n\t\t\t\t\t\twindowTokens: usage.contextWindow,\n\t\t\t\t\t\t...(usage.percent !== null ? { percent: usage.percent } : {}),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n\tlet currentSnapshot = createSnapshot(generation, 0, initialValues);\n\tlet statusLine: ReturnType<typeof installStatusLine> | undefined;\n\tlet editor: ReturnType<typeof installEditor> | undefined;\n\tlet startup: ReturnType<typeof installStartup> | undefined;\n\tlet installationState: RuntimeInstallationState = {\n\t\tstatus: \"disabled\",\n\t\teditor: \"disabled\",\n\t\tstartup: \"disabled\",\n\t};\n\tconst startupSnapshot = (config: NormalizedPiStyleConfig): StartupSnapshot => ({\n\t\t...currentSnapshot,\n\t\treason: host.startupReason ?? \"startup\",\n\t\t...(host.provider ? { startupProvider: host.provider } : {}),\n\t\t...(host.cwd ? { project: host.cwd.split(/[\\\\/]/).filter(Boolean).at(-1) } : {}),\n\t\tpreset: config.preset,\n\t\t...(host.resources ? { resources: host.resources } : {}),\n\t});\n\tconst installStatus = () => {\n\t\tif (!host.hasUI || host.mode !== \"tui\" || !host.ui || !currentConfig.enabled || !currentConfig.statusLine.enabled) {\n\t\t\tinstallationState = { ...installationState, status: \"disabled\" };\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tstatusLine = installStatusLine({\n\t\t\t\thost: host.ui,\n\t\t\t\tconfig: currentConfig,\n\t\t\t\tgeneration,\n\t\t\t\tinitialSnapshot: currentSnapshot,\n\t\t\t\tisCurrent: () => !disposed,\n\t\t\t\tclearOnStartup: host.startupReason === \"startup\",\n\t\t\t});\n\t\t\tif (statusLine) {\n\t\t\t\tdisposables.add(statusLine);\n\t\t\t\tinstallationState = { ...installationState, status: \"installed\" };\n\t\t\t} else installationState = { ...installationState, status: \"failed\" };\n\t\t} catch (error) {\n\t\t\thost.ui.notify?.(\n\t\t\t\t`pi-style status unavailable: ${error instanceof Error ? error.message : \"installation failed\"}`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\tstatusLine = undefined;\n\t\t\tinstallationState = { ...installationState, status: \"failed\" };\n\t\t}\n\t};\n\tconst installEditorFeature = () => {\n\t\tif (!host.hasUI || host.mode !== \"tui\" || !host.ui || !currentConfig.enabled || !currentConfig.editor.enabled) {\n\t\t\tinstallationState = { ...installationState, editor: \"disabled\" };\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\teditor = installEditor({\n\t\t\t\thost: host.ui,\n\t\t\t\tconfig: currentConfig,\n\t\t\t\tgeneration,\n\t\t\t\tinitialSnapshot: currentSnapshot,\n\t\t\t\tisCurrent: () => !disposed,\n\t\t\t});\n\t\t\tif (editor) {\n\t\t\t\tdisposables.add(editor);\n\t\t\t\tinstallationState = { ...installationState, editor: editor.preservedPrevious ? \"preserved\" : \"installed\" };\n\t\t\t} else installationState = { ...installationState, editor: \"failed\" };\n\t\t} catch (error) {\n\t\t\thost.ui.notify?.(\n\t\t\t\t`pi-style editor unavailable: ${error instanceof Error ? error.message : \"installation failed\"}`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\teditor = undefined;\n\t\t\tinstallationState = { ...installationState, editor: \"failed\" };\n\t\t}\n\t};\n\tconst installStartupFeature = () => {\n\t\tif (\n\t\t\t!host.hasUI ||\n\t\t\thost.mode !== \"tui\" ||\n\t\t\t!host.ui ||\n\t\t\t!currentConfig.enabled ||\n\t\t\tcurrentConfig.startup.mode === \"off\"\n\t\t) {\n\t\t\tinstallationState = { ...installationState, startup: \"disabled\" };\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tstartup = installStartup({\n\t\t\t\thost: { ...(host.ui as unknown as StartupHost), mode: host.mode, hasUI: host.hasUI },\n\t\t\t\tconfig: currentConfig,\n\t\t\t\tsnapshot: startupSnapshot(currentConfig),\n\t\t\t\tgeneration,\n\t\t\t\trequestRender,\n\t\t\t\ttimeoutMs: 3000,\n\t\t\t\tisCurrent: () => !disposed,\n\t\t\t});\n\t\t\tif (startup) {\n\t\t\t\tdisposables.add(startup);\n\t\t\t\tinstallationState = { ...installationState, startup: \"installed\" };\n\t\t\t} else installationState = { ...installationState, startup: \"failed\" };\n\t\t} catch (error) {\n\t\t\thost.ui.notify?.(\n\t\t\t\t`pi-style startup unavailable: ${error instanceof Error ? error.message : \"installation failed\"}`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\tstartup = undefined;\n\t\t\tinstallationState = { ...installationState, startup: \"failed\" };\n\t\t}\n\t};\n\tconst disposeFeature = (label: string, dispose: (() => void) | undefined): void => {\n\t\tif (!dispose) return;\n\t\ttry {\n\t\t\tdispose();\n\t\t} catch (error) {\n\t\t\thost.ui?.notify?.(`pi-style ${label} cleanup failed; preserving the current owner`, \"warning\");\n\t\t\tvoid error;\n\t\t}\n\t};\n\tconst disposeStatus = () => {\n\t\tdisposeFeature(\"status\", statusLine?.dispose);\n\t\tstatusLine = undefined;\n\t\tinstallationState = { ...installationState, status: \"disabled\" };\n\t};\n\tconst disposeEditor = () => {\n\t\tdisposeFeature(\"editor\", editor?.dispose);\n\t\teditor = undefined;\n\t\tinstallationState = { ...installationState, editor: \"disabled\" };\n\t};\n\tconst disposeStartup = () => {\n\t\tdisposeFeature(\"startup\", startup?.dispose);\n\t\tstartup = undefined;\n\t\tinstallationState = { ...installationState, startup: \"disabled\" };\n\t};\n\tinstallStatus();\n\tinstallEditorFeature();\n\tinstallStartupFeature();\n\tif (host.cwd && currentConfig.enabled && currentConfig.statusLine.enabled) {\n\t\tvoid git.get(host.cwd).then((value) => {\n\t\t\tif (disposed) return;\n\t\t\tcurrentSnapshot = replaceSnapshot(currentSnapshot, generation, { ...currentSnapshot, git: value });\n\t\t\tstatusLine?.update(currentSnapshot);\n\t\t\teditor?.update(currentSnapshot);\n\t\t\tstartup?.update({\n\t\t\t\t...currentSnapshot,\n\t\t\t\treason: host.startupReason ?? \"startup\",\n\t\t\t\t...(host.provider ? { startupProvider: host.provider } : {}),\n\t\t\t\t...(host.cwd ? { project: host.cwd.split(/[\\\\/]/).filter(Boolean).at(-1) } : {}),\n\t\t\t\tpreset: currentConfig.preset,\n\t\t\t\t...(host.resources ? { resources: host.resources } : {}),\n\t\t\t});\n\t\t\trequestRender();\n\t\t});\n\t}\n\tif (usage) {\n\t\tcontextProvider.set(\"active\", {\n\t\t\t...(usage.tokens !== null ? { currentTokens: usage.tokens } : {}),\n\t\t\twindowTokens: usage.contextWindow,\n\t\t\t...(usage.percent !== null ? { percent: usage.percent } : {}),\n\t\t});\n\t}\n\treturn {\n\t\tgeneration,\n\t\tproviderIdentity: { git, context: contextProvider, usage: usageProvider },\n\t\tget installationState() {\n\t\t\treturn installationState;\n\t\t},\n\t\tmode: host.mode,\n\t\thasUI: host.hasUI,\n\t\tsnapshot: currentSnapshot,\n\t\tdisposables,\n\t\tscheduler,\n\t\tupdateStartupResources(resources) {\n\t\t\tif (disposed) return;\n\t\t\tstartup?.update({\n\t\t\t\t...currentSnapshot,\n\t\t\t\treason: host.startupReason ?? \"startup\",\n\t\t\t\t...(host.provider ? { startupProvider: host.provider } : {}),\n\t\t\t\t...(host.cwd ? { project: host.cwd.split(/[\\\\/]/).filter(Boolean).at(-1) } : {}),\n\t\t\t\tpreset: currentConfig.preset,\n\t\t\t\tresources,\n\t\t\t});\n\t\t\trequestRender();\n\t\t},\n\t\tdismissStartup() {\n\t\t\tstartup?.dismiss();\n\t\t},\n\t\tupdate(values) {\n\t\t\tif (disposed) return;\n\t\t\tconst liveUsage = host.getContextUsage?.();\n\t\t\tconst context = liveUsage\n\t\t\t\t? {\n\t\t\t\t\t\t...(liveUsage.tokens !== null ? { currentTokens: liveUsage.tokens } : {}),\n\t\t\t\t\t\twindowTokens: liveUsage.contextWindow,\n\t\t\t\t\t\t...(liveUsage.percent !== null ? { percent: liveUsage.percent } : {}),\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\t\t\tconst statuses = extensionStatuses();\n\t\t\tcurrentSnapshot = replaceSnapshot(currentSnapshot, generation, {\n\t\t\t\t...currentSnapshot,\n\t\t\t\t...values,\n\t\t\t\t...(context ? { context } : {}),\n\t\t\t\t...(statuses ? { extensionStatuses: statuses } : {}),\n\t\t\t});\n\t\t\tstatusLine?.update(currentSnapshot);\n\t\t\teditor?.update(currentSnapshot);\n\t\t\tstartup?.update({\n\t\t\t\t...currentSnapshot,\n\t\t\t\treason: host.startupReason ?? \"startup\",\n\t\t\t\t...(host.provider ? { startupProvider: host.provider } : {}),\n\t\t\t\t...(host.cwd ? { project: host.cwd.split(/[\\\\/]/).filter(Boolean).at(-1) } : {}),\n\t\t\t\tpreset: currentConfig.preset,\n\t\t\t\t...(host.resources ? { resources: host.resources } : {}),\n\t\t\t});\n\t\t},\n\t\tconfigure(nextConfig) {\n\t\t\tif (disposed) return;\n\t\t\tconst previous = currentConfig;\n\t\t\tconst impactPlan = diffConfig(previous, nextConfig);\n\t\t\tif (impactPlan.impacts.length === 0) return;\n\t\t\tcurrentConfig = nextConfig;\n\t\t\tconst statusChanged =\n\t\t\t\tJSON.stringify(previous.statusLine) !== JSON.stringify(nextConfig.statusLine) ||\n\t\t\t\tprevious.placement !== nextConfig.placement ||\n\t\t\t\tprevious.enabled !== nextConfig.enabled;\n\t\t\tconst editorChanged =\n\t\t\t\tJSON.stringify(previous.editor) !== JSON.stringify(nextConfig.editor) ||\n\t\t\t\tprevious.enabled !== nextConfig.enabled;\n\t\t\tconst startupChanged =\n\t\t\t\tJSON.stringify(previous.startup) !== JSON.stringify(nextConfig.startup) ||\n\t\t\t\tprevious.enabled !== nextConfig.enabled;\n\t\t\tif (statusChanged) {\n\t\t\t\tdisposeStatus();\n\t\t\t\tcurrentConfig = nextConfig;\n\t\t\t\tinstallStatus();\n\t\t\t}\n\t\t\tif (editorChanged) {\n\t\t\t\tdisposeEditor();\n\t\t\t\tcurrentConfig = nextConfig;\n\t\t\t\tinstallEditorFeature();\n\t\t\t}\n\t\t\tif (startupChanged) {\n\t\t\t\tdisposeStartup();\n\t\t\t\tcurrentConfig = nextConfig;\n\t\t\t\tinstallStartupFeature();\n\t\t\t}\n\t\t\tstatusLine?.configure(nextConfig);\n\t\t\teditor?.configure(nextConfig);\n\t\t\tstartup?.configure(nextConfig);\n\t\t},\n\t\tinvalidateGit() {\n\t\t\tif (disposed || !host.cwd || !currentConfig.enabled || !currentConfig.statusLine.enabled) return;\n\t\t\tgit.invalidate(host.cwd);\n\t\t\tvoid git.get(host.cwd).then((value) => {\n\t\t\t\tif (disposed) return;\n\t\t\t\tcurrentSnapshot = replaceSnapshot(currentSnapshot, generation, { ...currentSnapshot, git: value });\n\t\t\t\tstatusLine?.update(currentSnapshot);\n\t\t\t\teditor?.update(currentSnapshot);\n\t\t\t\tstartup?.update({\n\t\t\t\t\t...currentSnapshot,\n\t\t\t\t\treason: host.startupReason ?? \"startup\",\n\t\t\t\t\t...(host.provider ? { startupProvider: host.provider } : {}),\n\t\t\t\t\t...(host.cwd ? { project: host.cwd.split(/[\\\\/]/).filter(Boolean).at(-1) } : {}),\n\t\t\t\t\tpreset: currentConfig.preset,\n\t\t\t\t});\n\t\t\t\trequestRender();\n\t\t\t});\n\t\t},\n\t\tget disposed() {\n\t\t\treturn disposed;\n\t\t},\n\t\tdispose() {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\tscheduler.cancel();\n\t\t\t// UI surfaces are restored synchronously so teardown is deterministic;\n\t\t\t// the store then disposes the (already disposed) feature instances idempotently.\n\t\t\tdisposeStatus();\n\t\t\tdisposeEditor();\n\t\t\tdisposeStartup();\n\t\t\tgit.dispose();\n\t\t\tcontextProvider.clear();\n\t\t\tusageProvider.reset();\n\t\t\tvoid disposables.dispose();\n\t\t},\n\t};\n}\n\nexport class PiStyleRuntimeController {\n\tprivate activeRuntime: PiStyleRuntime | undefined;\n\tprivate nextGeneration = 0;\n\n\tstart(ctx: RuntimeHost): PiStyleRuntime {\n\t\tthis.stop();\n\t\tthis.activeRuntime = createPiStyleRuntime(ctx, ++this.nextGeneration);\n\t\treturn this.activeRuntime;\n\t}\n\n\tstop(): void {\n\t\tthis.activeRuntime?.dispose();\n\t\tthis.activeRuntime = undefined;\n\t}\n\n\tget current(): PiStyleRuntime | undefined {\n\t\treturn this.activeRuntime;\n\t}\n}\n","import { boundedDiagnostics } from \"../domain/config-diagnostics.js\";\nimport { DEFAULT_CONFIG, normalizeConfig, resolveConfigDetailed } from \"../domain/config-normalization.js\";\nimport type { NormalizedPiStyleConfig } from \"../domain/config-types.js\";\nimport type { StartupDetailItem, StartupReason } from \"../features/startup/index.js\";\nimport { createDoctor, type DoctorOperationalState } from \"./doctor.js\";\nimport { PiStyleRuntimeController } from \"./runtime.js\";\n\nexport interface StartupResourceDiscovery {\n\treadonly skillPaths?: readonly string[];\n\treadonly promptPaths?: readonly string[];\n\treadonly themePaths?: readonly string[];\n\t/** Raw system prompt text; word/line counts are computed outside render. */\n\treadonly systemPrompt?: string;\n\t/** Context files with pre-computed word/line counts (discovery outside render). */\n\treadonly contextDetails?: readonly { path: string; words: number; lines: number }[];\n\t/** Active tools with compact source labels (discovery outside render). */\n\treadonly toolDetails?: readonly { source: string; name: string }[];\n\treadonly models?: number;\n}\n\nfunction countWords(text: string): number {\n\treturn text.match(/[\\p{L}\\p{N}_]+/gu)?.length ?? 0;\n}\n\nfunction countLines(text: string): number {\n\tif (text.length === 0) return 0;\n\tconst lines = text.split(/\\r\\n|\\r|\\n/).length;\n\treturn /\\r\\n$|\\r$|\\n$/.test(text) ? lines - 1 : lines;\n}\n\nfunction toStartupResources(resources: StartupResourceDiscovery) {\n\tconst details: StartupDetailItem[] = [];\n\tif (resources.systemPrompt) {\n\t\tconst words = countWords(resources.systemPrompt);\n\t\tconst lines = countLines(resources.systemPrompt);\n\t\tif (words > 0 && lines > 0) details.push({ kind: \"system\", path: \"system prompt\", words, lines });\n\t}\n\tfor (const file of resources.contextDetails ?? []) {\n\t\tif (file.words > 0 && file.lines > 0) {\n\t\t\tdetails.push({ kind: \"context\", path: file.path, words: file.words, lines: file.lines });\n\t\t}\n\t}\n\treturn {\n\t\t...(resources.promptPaths ? { contextFiles: resources.promptPaths.length } : {}),\n\t\t...(resources.themePaths ? { extensions: resources.themePaths.length } : {}),\n\t\t...(resources.skillPaths ? { skills: resources.skillPaths.length } : {}),\n\t\t...(resources.models !== undefined ? { models: resources.models } : {}),\n\t\t...(resources.toolDetails && resources.toolDetails.length > 0\n\t\t\t? { tools: resources.toolDetails.length, toolDetails: resources.toolDetails }\n\t\t\t: {}),\n\t\t...(details.length > 0 ? { details } : {}),\n\t};\n}\n\nexport interface ConfigReloadPort {\n\tload(trusted: boolean): Promise<{\n\t\treadonly config?: unknown;\n\t\treadonly diagnostics?: readonly import(\"../domain/config-diagnostics.js\").ConfigDiagnostic[];\n\t\treadonly sources?: Readonly<Record<string, string>>;\n\t\treadonly rawSources?: {\n\t\t\tdefaults?: unknown;\n\t\t\tglobal?: unknown;\n\t\t\tproject?: unknown;\n\t\t\tenvironment?: Record<string, string | undefined>;\n\t\t};\n\t\treadonly productPolicy?: { corePatchGate: \"omitted\" | \"allow\" | \"deny\" };\n\t}>;\n}\n\nexport interface AppHost {\n\treadonly mode: \"tui\" | \"rpc\" | \"json\" | \"print\";\n\treadonly hasUI: boolean;\n\treadonly ui?: Parameters<PiStyleRuntimeController[\"start\"]>[0][\"ui\"];\n\treadonly cwd?: string;\n\treadonly model?: { id?: string; name?: string; provider?: string; reasoning?: boolean };\n\treadonly thinkingLevel?: string;\n\treadonly getContextUsage?: () => { tokens: number | null; contextWindow: number; percent: number | null } | undefined;\n\treadonly projectTrusted?: boolean;\n\treadonly extensionStatusProvider?: () => readonly import(\"../domain/status.js\").ExtensionStatus[] | undefined;\n\treadonly gitRunner?: import(\"../domain/providers.js\").GitCommandRunner;\n}\n\nexport interface PiStyleApp {\n\treadonly runtime: PiStyleRuntimeController;\n\treadonly config: NormalizedPiStyleConfig;\n\treadonly productPolicy: { corePatchGate: \"omitted\" | \"allow\" | \"deny\" };\n\tsessionStart(ctx: AppHost, reason?: StartupReason, resources?: StartupResourceDiscovery): void;\n\tsetResources(resources: StartupResourceDiscovery): void;\n\tapplySession(patch: unknown): void;\n\tsetProjectTrusted(trusted: boolean): void;\n\tsetOperationalState(state: DoctorOperationalState): void;\n\tsetProductPolicy(policy: { corePatchGate: \"omitted\" | \"allow\" | \"deny\" }): void;\n\treload(): Promise<void>;\n\tdoctor(): Readonly<Record<string, unknown>>;\n\tsessionShutdown(): void;\n\tupdate(\n\t\tvalues: import(\"../domain/status.js\").StatusSnapshot,\n\t\tkind?: import(\"./render-scheduler.js\").UpdateClass,\n\t): void;\n}\n\nfunction submittedSessionPaths(value: unknown, prefix = \"\"): readonly string[] {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return [];\n\treturn Object.entries(value).flatMap(([key, nested]) => {\n\t\tconst path = prefix ? `${prefix}.${key}` : key;\n\t\treturn [path, ...submittedSessionPaths(nested, path)];\n\t});\n}\nfunction composeSources(\n\tdurable: Readonly<Record<string, string>>,\n\tresolved: Readonly<Record<string, string>>,\n\tsession: unknown,\n): Readonly<Record<string, string>> {\n\tconst next = { ...durable, ...resolved };\n\tfor (const path of submittedSessionPaths(session)) {\n\t\tconst effectiveSource = resolved[path];\n\t\tif (effectiveSource === undefined) delete next[path];\n\t\telse next[path] = effectiveSource;\n\t}\n\treturn next;\n}\n\nfunction mergePatch(base: unknown, patch: unknown): unknown {\n\tif (patch === undefined) return base;\n\tif (\n\t\ttypeof base !== \"object\" ||\n\t\tbase === null ||\n\t\tArray.isArray(base) ||\n\t\ttypeof patch !== \"object\" ||\n\t\tpatch === null ||\n\t\tArray.isArray(patch)\n\t)\n\t\treturn patch;\n\tconst result: Record<string, unknown> = { ...(base as Record<string, unknown>) };\n\tfor (const [key, value] of Object.entries(patch as Record<string, unknown>))\n\t\tresult[key] = mergePatch(result[key], value);\n\treturn result;\n}\n\nexport function createPiStyleApp(\n\tinitialConfig?: unknown,\n\treloadPort?: ConfigReloadPort,\n\tonConfigChange?: (config: NormalizedPiStyleConfig) => void,\n): PiStyleApp {\n\tconst runtime = new PiStyleRuntimeController();\n\tlet config = initialConfig === undefined ? DEFAULT_CONFIG : normalizeConfig(initialConfig);\n\tlet diagnostics: readonly import(\"../domain/config-diagnostics.js\").ConfigDiagnostic[] = [];\n\tlet durableDiagnostics: readonly import(\"../domain/config-diagnostics.js\").ConfigDiagnostic[] = [];\n\tlet durableSources: Readonly<Record<string, string>> = {};\n\tlet sources: Readonly<Record<string, string>> = {};\n\tlet trusted = true;\n\tlet resources: StartupResourceDiscovery | undefined;\n\tlet operational: DoctorOperationalState = {};\n\tlet sessionPatch: unknown;\n\tlet rawSources: {\n\t\tdefaults?: unknown;\n\t\tglobal?: unknown;\n\t\tproject?: unknown;\n\t\tenvironment?: Record<string, string | undefined>;\n\t} = { defaults: initialConfig ?? DEFAULT_CONFIG };\n\tlet productPolicy: { corePatchGate: \"omitted\" | \"allow\" | \"deny\" } = { corePatchGate: \"omitted\" };\n\tconst resolveAll = () => resolveConfigDetailed({ ...rawSources, session: sessionPatch, projectTrusted: trusted });\n\tconst resolveProductPolicy = () => {\n\t\tconst values = [rawSources.global, trusted ? rawSources.project : undefined, sessionPatch];\n\t\tfor (const value of values) {\n\t\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) continue;\n\t\t\tconst compatibility = (value as Record<string, unknown>).compatibility;\n\t\t\tif (\n\t\t\t\tcompatibility &&\n\t\t\t\ttypeof compatibility === \"object\" &&\n\t\t\t\t!Array.isArray(compatibility) &&\n\t\t\t\tObject.hasOwn(compatibility, \"allowCorePatches\") &&\n\t\t\t\t(compatibility as Record<string, unknown>).allowCorePatches === false\n\t\t\t)\n\t\t\t\treturn { corePatchGate: \"deny\" as const };\n\t\t}\n\t\treturn { corePatchGate: \"omitted\" as const };\n\t};\n\treturn {\n\t\truntime,\n\t\tget config() {\n\t\t\treturn config;\n\t\t},\n\t\tget productPolicy() {\n\t\t\treturn productPolicy;\n\t\t},\n\t\tsessionStart(ctx, reason = \"startup\", discoveredResources) {\n\t\t\ttrusted = ctx.projectTrusted ?? true;\n\t\t\tresources = discoveredResources;\n\t\t\toperational = {\n\t\t\t\t...operational,\n\t\t\t\tprovider: ctx.extensionStatusProvider\n\t\t\t\t\t? { status: \"configured\", recovery: \"provider will be checked on first snapshot\" }\n\t\t\t\t\t: { status: \"unavailable\", recovery: \"inject a capability-safe provider\" },\n\t\t\t\tinstallations: {\n\t\t\t\t\tstatus: config.enabled && config.statusLine.enabled ? \"active\" : \"disabled\",\n\t\t\t\t\teditor: config.enabled && config.editor.enabled ? \"active\" : \"disabled\",\n\t\t\t\t\tstartup: config.enabled && config.startup.mode !== \"off\" ? \"active\" : \"disabled\",\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst statusProvider = ctx.extensionStatusProvider\n\t\t\t\t? () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = ctx.extensionStatusProvider?.();\n\t\t\t\t\t\t\toperational = { ...operational, provider: { status: \"available\" } };\n\t\t\t\t\t\t\treturn result;\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\toperational = {\n\t\t\t\t\t\t\t\t...operational,\n\t\t\t\t\t\t\t\tprovider: { status: \"unavailable\", recovery: \"provider threw; retry after recovery\" },\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tctx.ui?.notify?.(\"pi-style extension statuses unavailable; provider recovery required\", \"warning\");\n\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\t\t\truntime.start({\n\t\t\t\tmode: ctx.mode,\n\t\t\t\thasUI: ctx.hasUI,\n\t\t\t\t...(ctx.ui ? { ui: ctx.ui } : {}),\n\t\t\t\t...(ctx.cwd ? { cwd: ctx.cwd } : {}),\n\t\t\t\t...(ctx.model ? { model: ctx.model } : {}),\n\t\t\t\t...(ctx.thinkingLevel ? { thinkingLevel: ctx.thinkingLevel } : {}),\n\t\t\t\tconfig,\n\t\t\t\tstartupReason: reason,\n\t\t\t\t...(resources ? { resources: toStartupResources(resources) } : {}),\n\t\t\t\t...(ctx.getContextUsage ? { getContextUsage: ctx.getContextUsage } : {}),\n\t\t\t\t...(ctx.projectTrusted !== undefined ? { projectTrusted: ctx.projectTrusted } : {}),\n\t\t\t\t...(ctx.gitRunner ? { gitRunner: ctx.gitRunner } : {}),\n\t\t\t\t...(statusProvider ? { extensionStatusProvider: statusProvider } : {}),\n\t\t\t});\n\t\t},\n\t\tsetResources(next) {\n\t\t\tresources = next;\n\t\t\truntime.current?.updateStartupResources(toStartupResources(next));\n\t\t},\n\t\tapplySession(patch) {\n\t\t\tsessionPatch = mergePatch(sessionPatch, patch);\n\t\t\tconst resolved = resolveAll();\n\t\t\tconfig = resolved.config;\n\t\t\tdiagnostics = boundedDiagnostics([...durableDiagnostics, ...resolved.diagnostics]);\n\t\t\tsources = composeSources(durableSources, resolved.sources, sessionPatch);\n\t\t\tproductPolicy = resolveProductPolicy();\n\t\t\toperational = {\n\t\t\t\t...operational,\n\t\t\t\tauthorization: { ...(operational.authorization ?? {}), productCorePatchGate: productPolicy.corePatchGate },\n\t\t\t};\n\t\t\truntime.current?.configure(config);\n\t\t\toperational = {\n\t\t\t\t...operational,\n\t\t\t\tinstallations: { ...(operational.installations ?? {}), configChange: \"reconciled\" },\n\t\t\t};\n\t\t\tonConfigChange?.(config);\n\t\t},\n\t\tsetProjectTrusted(nextTrusted) {\n\t\t\ttrusted = nextTrusted;\n\t\t},\n\t\tsetOperationalState(state) {\n\t\t\toperational = { ...operational, ...state };\n\t\t},\n\t\tsetProductPolicy(policy) {\n\t\t\tproductPolicy = policy;\n\t\t\toperational = {\n\t\t\t\t...operational,\n\t\t\t\tauthorization: { ...(operational.authorization ?? {}), productCorePatchGate: policy.corePatchGate },\n\t\t\t};\n\t\t},\n\t\tsessionShutdown() {\n\t\t\truntime.stop();\n\t\t},\n\t\tupdate(values, kind = \"coalesced\") {\n\t\t\tconst active = runtime.current;\n\t\t\tif (!active) return;\n\t\t\tactive.update(values);\n\t\t\tactive.scheduler.schedule(kind);\n\t\t},\n\t\treload() {\n\t\t\tif (!reloadPort) {\n\t\t\t\truntime.current?.configure(config);\n\t\t\t\treturn Promise.resolve();\n\t\t\t}\n\t\t\treturn reloadPort.load(trusted).then((result) => {\n\t\t\t\tdurableDiagnostics = boundedDiagnostics(result.diagnostics ?? []);\n\t\t\t\tdurableSources = result.sources ?? {};\n\t\t\t\tdiagnostics = durableDiagnostics;\n\t\t\t\tsources = durableSources;\n\t\t\t\tif (result.config !== undefined) {\n\t\t\t\t\trawSources = result.rawSources ?? { defaults: result.config };\n\t\t\t\t\tproductPolicy = resolveProductPolicy();\n\t\t\t\t\tconst resolved = resolveAll();\n\t\t\t\t\tconfig = resolved.config;\n\t\t\t\t\tdiagnostics = boundedDiagnostics([...durableDiagnostics, ...resolved.diagnostics]);\n\t\t\t\t\tsources = composeSources(durableSources, resolved.sources, sessionPatch);\n\t\t\t\t\tonConfigChange?.(config);\n\t\t\t\t\toperational = {\n\t\t\t\t\t\t...operational,\n\t\t\t\t\t\tauthorization: { ...(operational.authorization ?? {}), productCorePatchGate: productPolicy.corePatchGate },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\truntime.current?.configure(config);\n\t\t\t\tonConfigChange?.(config);\n\t\t\t});\n\t\t},\n\t\tdoctor() {\n\t\t\treturn createDoctor({\n\t\t\t\tconfig,\n\t\t\t\toperational,\n\t\t\t\tdiagnostics,\n\t\t\t\tsources,\n\t\t\t\tsurfaces: {\n\t\t\t\t\tstatus: operational.installations?.status ?? \"unknown\",\n\t\t\t\t\teditor: operational.installations?.editor ?? \"unknown\",\n\t\t\t\t\tstartup: operational.installations?.startup ?? \"unknown\",\n\t\t\t\t\tassistantMessage: operational.compatibility?.assistantMessage ?? \"unknown\",\n\t\t\t\t\tspecialBlocks: operational.compatibility?.specialBlocks ?? \"unknown\",\n\t\t\t\t\ttools: operational.compatibility?.tools ?? \"unknown\",\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t};\n}\n","// Special message-block presentation: compaction, skill invocation, branch\n// summary, and extension custom (MCP) messages, rendered as boxed blocks.\n//\n// These patches are pure delegates: the compatibility probe installs them\n// through its reversible, generation-tracked wrapper and restores the native\n// identity on shutdown. The delegate receives the native method and falls back\n// to it whenever the theme or component shape is unavailable.\n\nimport { keyText } from \"@earendil-works/pi-coding-agent\";\nimport { Markdown, type MarkdownTheme } from \"@earendil-works/pi-tui\";\nimport type { BoxTheme } from \"../../shared/box.js\";\nimport { setFullTheme } from \"../../shared/theme-extras.js\";\nimport { renderBoxedMessageBlock } from \"./boxed-block.js\";\n\nlet cachedTheme: BoxTheme | undefined;\n\nexport function setSpecialBlockTheme(theme: BoxTheme | undefined): void {\n\tcachedTheme = theme;\n\tif (theme) setFullTheme(theme);\n}\n\nexport type SpecialBlockSubtype =\n\t| \"native-compaction-message\"\n\t| \"native-branch-message\"\n\t| \"native-skill-message\"\n\t| \"native-custom-message\";\n\nexport type SpecialBlockCtor = { prototype?: unknown };\n\nexport interface SpecialBlockCtors {\n\tCompactionSummaryMessageComponent?: SpecialBlockCtor;\n\tSkillInvocationMessageComponent?: SpecialBlockCtor;\n\tBranchSummaryMessageComponent?: SpecialBlockCtor;\n\tCustomMessageComponent?: SpecialBlockCtor;\n}\n\n/** Structural view of the native message components as used by the patches. */\ninterface MessageBlockInstance {\n\tmessage?: {\n\t\ttokensBefore?: unknown;\n\t\tsummary?: unknown;\n\t\tcustomType?: unknown;\n\t\tcontent?: unknown;\n\t};\n\tskillBlock?: { name?: unknown; content?: unknown };\n\texpanded?: unknown;\n\t_expanded?: unknown;\n\tmarkdownTheme?: unknown;\n\tbox?: { clear(): void; addChild(child: unknown): void; setBgFn?(fn: (text: string) => string): void };\n\tcustomComponent?: unknown;\n\tcustomRenderer?: unknown;\n\tclear?(): void;\n\taddChild(child: unknown): void;\n\tremoveChild(child: unknown): void;\n\tsetBgFn?(fn: (text: string) => string): void;\n}\n\nconst EXPAND_HINT = \"Ctrl+O to expand\";\n\nfunction expandHint(): string {\n\ttry {\n\t\tconst text = keyText(\"app.tools.expand\");\n\t\treturn text ? `${text} to expand` : EXPAND_HINT;\n\t} catch {\n\t\treturn EXPAND_HINT;\n\t}\n}\n\nfunction createMarkdownBody(\n\ttext: string,\n\tmarkdownTheme: MarkdownTheme | undefined,\n\ttheme: BoxTheme,\n): (contentWidth: number) => string[] {\n\tconst md = new Markdown(text || \"\", 0, 0, markdownTheme as MarkdownTheme, {\n\t\tcolor: (t: string) => theme.fg(\"customMessageText\", t),\n\t});\n\treturn (contentWidth: number) => md.render(contentWidth);\n}\n\n/**\n * Neutralize the native customMessageBg fill for boxed blocks: the boxed block\n * owns its visual boundary, so the parent background is removed (the box sits\n * directly on the terminal/page background).\n */\nfunction neutralizeMessageBlockBackground(target: { setBgFn?(fn: (text: string) => string): void } | undefined): void {\n\tif (!target) return;\n\tif (typeof target.setBgFn === \"function\") target.setBgFn((text) => text);\n}\n\nfunction patchCompaction(instance: MessageBlockInstance, _original: () => void, theme: BoxTheme): boolean {\n\tconst tokensBefore = instance.message?.tokensBefore;\n\tif (tokensBefore == null) return false;\n\n\tif (typeof instance.clear === \"function\") instance.clear();\n\n\tconst expanded = Boolean(instance.expanded);\n\tconst summary = typeof instance.message?.summary === \"string\" ? instance.message.summary : \"\";\n\tconst markdownTheme = instance.markdownTheme as MarkdownTheme | undefined;\n\n\tneutralizeMessageBlockBackground(instance as { setBgFn?(fn: (text: string) => string): void });\n\n\tconst body = expanded && summary && markdownTheme ? createMarkdownBody(summary, markdownTheme, theme) : () => [];\n\n\tconst tokenStr = Number(tokensBefore).toLocaleString();\n\tneutralizeMessageBlockBackground(instance as { setBgFn?(fn: (text: string) => string): void });\n\tconst block = renderBoxedMessageBlock(theme, {\n\t\tkind: \"Compaction\",\n\t\ttitle: `${tokenStr} tokens`,\n\t\t...(expanded ? {} : { right: expandHint() }),\n\t\tbody,\n\t\ticon: \"⊟\",\n\t\thasDivider: expanded,\n\t});\n\tinstance.addChild(block);\n\treturn true;\n}\n\nfunction patchSkill(instance: MessageBlockInstance, _original: () => void, theme: BoxTheme): boolean {\n\tconst skillName = instance.skillBlock?.name;\n\tif (typeof skillName !== \"string\" || !skillName) return false;\n\n\tif (typeof instance.clear === \"function\") instance.clear();\n\n\tconst expanded = Boolean(instance.expanded);\n\tconst content = typeof instance.skillBlock?.content === \"string\" ? instance.skillBlock.content : \"\";\n\tconst markdownTheme = instance.markdownTheme as MarkdownTheme | undefined;\n\n\tneutralizeMessageBlockBackground(instance as { setBgFn?(fn: (text: string) => string): void });\n\n\tconst body = expanded && content && markdownTheme ? createMarkdownBody(content, markdownTheme, theme) : () => [];\n\n\tconst block = renderBoxedMessageBlock(theme, {\n\t\tkind: \"Skill\",\n\t\ttitle: skillName,\n\t\t...(expanded ? {} : { right: expandHint() }),\n\t\tbody,\n\t\ticon: \"⊟\",\n\t\thasDivider: expanded,\n\t});\n\tinstance.addChild(block);\n\treturn true;\n}\n\nfunction patchBranch(instance: MessageBlockInstance, _original: () => void, theme: BoxTheme): boolean {\n\tif (instance.message == null) return false;\n\n\tif (typeof instance.clear === \"function\") instance.clear();\n\n\tconst expanded = Boolean(instance.expanded);\n\tconst summary = typeof instance.message?.summary === \"string\" ? instance.message.summary : \"\";\n\tconst markdownTheme = instance.markdownTheme as MarkdownTheme | undefined;\n\n\tneutralizeMessageBlockBackground(instance as { setBgFn?(fn: (text: string) => string): void });\n\n\tconst body = expanded && summary && markdownTheme ? createMarkdownBody(summary, markdownTheme, theme) : () => [];\n\n\tconst block = renderBoxedMessageBlock(theme, {\n\t\tkind: \"Branch\",\n\t\t...(expanded ? {} : { right: expandHint() }),\n\t\tbody,\n\t\ticon: \"⊟\",\n\t\thasDivider: expanded,\n\t});\n\tinstance.addChild(block);\n\treturn true;\n}\n\nfunction attachCustomMessageBlock(instance: MessageBlockInstance, block: unknown): boolean {\n\tif (instance.box && typeof instance.box.clear === \"function\" && typeof instance.box.addChild === \"function\") {\n\t\tinstance.addChild(instance.box);\n\t\tinstance.box.clear();\n\t\tinstance.box.addChild(block);\n\t\treturn true;\n\t}\n\tinstance.customComponent = block;\n\tinstance.addChild(instance.customComponent);\n\treturn true;\n}\n\nfunction patchCustomMessage(instance: MessageBlockInstance, _original: () => void, theme: BoxTheme): boolean {\n\t// Remove previous content component\n\tif (instance.customComponent) {\n\t\tinstance.removeChild(instance.customComponent);\n\t\tinstance.customComponent = undefined;\n\t}\n\tif (instance.box) instance.removeChild(instance.box);\n\n\t// The boxed shell owns its boundary; drop the native customMessageBg fill.\n\tneutralizeMessageBlockBackground(instance.box);\n\tneutralizeMessageBlockBackground(instance as { setBgFn?(fn: (text: string) => string): void });\n\n\tconst rawCustomType = instance.message?.customType;\n\tconst customType = typeof rawCustomType === \"string\" ? rawCustomType : \"Custom\";\n\n\t// Try custom renderer first, but keep the special block shell/background owned here.\n\tif (typeof instance.customRenderer === \"function\") {\n\t\ttry {\n\t\t\tconst component = (instance.customRenderer as (message: unknown, options: object, theme: unknown) => unknown)(\n\t\t\t\tinstance.message,\n\t\t\t\t{ expanded: instance._expanded },\n\t\t\t\ttheme,\n\t\t\t);\n\t\t\tif (component && typeof (component as { render?: unknown }).render === \"function\") {\n\t\t\t\tconst block = renderBoxedMessageBlock(theme, {\n\t\t\t\t\tkind: \"Custom\",\n\t\t\t\t\ttitle: customType,\n\t\t\t\t\tbody: (contentWidth) => (component as { render(width: number): string[] }).render(contentWidth),\n\t\t\t\t\ticon: \"⊟\",\n\t\t\t\t\thasDivider: \"auto\",\n\t\t\t\t\tcache: false,\n\t\t\t\t});\n\t\t\t\tattachCustomMessageBlock(instance, block);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Fall through to default rendering\n\t\t}\n\t}\n\n\t// Default rendering: use boxed message block\n\n\t// Extract text content\n\tconst rawContent = instance.message?.content;\n\tlet text: string;\n\tif (typeof rawContent === \"string\") {\n\t\ttext = rawContent;\n\t} else if (Array.isArray(rawContent)) {\n\t\ttext = rawContent\n\t\t\t.filter((c: unknown) => {\n\t\t\t\tif (!c || typeof c !== \"object\") return false;\n\t\t\t\treturn (c as { type?: unknown }).type === \"text\";\n\t\t\t})\n\t\t\t.map((c) => String((c as { text?: unknown }).text ?? \"\"))\n\t\t\t.join(\"\\n\");\n\t} else {\n\t\ttext = \"\";\n\t}\n\n\tconst markdownTheme = instance.markdownTheme as MarkdownTheme | undefined;\n\n\tconst body = text && markdownTheme ? createMarkdownBody(text, markdownTheme, theme) : () => [];\n\n\tconst block = renderBoxedMessageBlock(theme, {\n\t\tkind: \"Custom\",\n\t\ttitle: customType,\n\t\tbody,\n\t\ticon: \"⊟\",\n\t\thasDivider: Boolean(text),\n\t});\n\n\tattachCustomMessageBlock(instance, block);\n\treturn true;\n}\n\n/**\n * Delegate invoked by the compatibility probe's wrapper for each special block\n * method. Falls back to the native implementation when the theme cache is\n * empty or the component shape is unsupported.\n */\nexport function renderSpecialMessageBlock(\n\tsubtype: SpecialBlockSubtype,\n\toriginal: unknown,\n\tthisArg: object,\n\targs: unknown[],\n): unknown {\n\tconst instance = thisArg as unknown as MessageBlockInstance;\n\tconst base = original as (this: object, ...rest: unknown[]) => unknown;\n\tconst applyBase = () => base.apply(thisArg, args);\n\tconst theme = cachedTheme;\n\tif (!theme) return applyBase();\n\ttry {\n\t\tlet handled = false;\n\t\tif (subtype === \"native-compaction-message\") handled = patchCompaction(instance, applyBase, theme);\n\t\telse if (subtype === \"native-skill-message\") handled = patchSkill(instance, applyBase, theme);\n\t\telse if (subtype === \"native-branch-message\") handled = patchBranch(instance, applyBase, theme);\n\t\telse if (subtype === \"native-custom-message\") handled = patchCustomMessage(instance, applyBase, theme);\n\t\treturn handled ? undefined : applyBase();\n\t} catch {\n\t\treturn applyBase();\n\t}\n}\n","// Boxed message-block shell (skill/compaction/branch/custom/MCP blocks).\n// Returns only border/content lines with foreground styling; the parent Box\n// applies the customMessageBg background (the native components already set\n// that bgFn).\n\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport type { BoxTheme } from \"../../shared/box.js\";\nimport { boxBlankLine, boxBorder, boxInnerWidth, boxLabeledBorder, boxLine, boxWidth } from \"../../shared/box.js\";\n\nexport type MessageBlockOptions = {\n\tkind: string;\n\ttitle?: string;\n\tright?: string;\n\tbody: (contentWidth: number) => string[];\n\thasDivider?: boolean | \"auto\";\n\ticon?: string;\n\tcache?: boolean;\n};\n\nfunction formatMessageBlockTitle(theme: BoxTheme, kind: string, title?: string, icon = \"➔\"): string {\n\tconst rawTitle = title ? `${icon} ${kind} · ${title}` : `${icon} ${kind}`;\n\tconst coloredTitle = theme.fg(\"accent\", rawTitle);\n\treturn typeof theme?.bold === \"function\" ? theme.bold(coloredTitle) : coloredTitle;\n}\n\n/**\n * Render a boxed message block.\n *\n * The title is embedded in the rounded top border, the body sits between\n * blank padding rows, and the expand hint (when present) is embedded at the\n * right end of the bottom border — no inset dividers.\n *\n * Returns only border/content lines with foreground styling. Background is\n * applied by the parent Box (all patched components extend Box with a\n * customMessageBg bgFn), so this helper must NOT apply background itself —\n * that would create a double-background conflict.\n */\nexport function renderBoxedMessageBlock(theme: BoxTheme, options: MessageBlockOptions): Component {\n\tconst { kind, title, right, body, icon = \"➔\", cache: shouldCache = true } = options;\n\tlet cache: { width: number; lines: string[] } | null = null;\n\n\treturn {\n\t\tinvalidate() {\n\t\t\tcache = null;\n\t\t},\n\t\trender(width: number): string[] {\n\t\t\tif (shouldCache && cache?.width === width) return cache.lines;\n\n\t\t\tconst renderedWidth = boxWidth(width);\n\t\t\tconst contentWidth = boxInnerWidth(renderedWidth);\n\t\t\tconst titleLine = formatMessageBlockTitle(theme, kind, title, icon);\n\t\t\tconst bodyLines = body(contentWidth);\n\n\t\t\tconst lines: string[] = [\n\t\t\t\tboxLabeledBorder(theme, \"╭\", \"╮\", titleLine, undefined, renderedWidth),\n\t\t\t\tboxBlankLine(theme, renderedWidth),\n\t\t\t\t...bodyLines.map((line) => boxLine(theme, line, renderedWidth)),\n\t\t\t];\n\t\t\tif (bodyLines.length > 0) lines.push(boxBlankLine(theme, renderedWidth));\n\t\t\tif (right) {\n\t\t\t\tlines.push(boxLabeledBorder(theme, \"╰\", \"╯\", \"\", theme.fg(\"dim\", right), renderedWidth));\n\t\t\t} else {\n\t\t\t\tlines.push(boxBorder(theme, \"╰\", \"╯\", renderedWidth));\n\t\t\t}\n\n\t\t\tif (shouldCache) cache = { width, lines };\n\t\t\treturn lines;\n\t\t},\n\t};\n}\n","// Boxed bash tool renderer\n// (renderCall/renderResult only).\n\nimport { highlightCode } from \"@earendil-works/pi-coding-agent\";\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport { stripAnsi } from \"../../../shared/ansi.js\";\nimport type { BoxTheme } from \"../../../shared/box.js\";\nimport {\n\tboxedToolWidthKey,\n\tformatBoxedRunningStatus,\n\tformatBoxedWords,\n\tformatToolOutputLine,\n\tgetTextOutput,\n\trenderBoxedToolCall,\n\trenderBoxedToolResult,\n\treplaceTabs,\n\tshortenPath,\n} from \"../../../shared/box.js\";\nimport { safeTruncateToWidth, truncateAtCodePointBoundary } from \"../../../shared/render-budget.js\";\nimport {\n\ttype GrepMatch,\n\tgroupMatchesByFile,\n\tparseFindOutput,\n\tparseGrepBareOutput,\n\tparseGrepOutput,\n\tparseLsLongOutput,\n\tparseLsOutput,\n\tpluralForm,\n\trenderGrepTree,\n\trenderOutputTree,\n\tSEARCH_ICON,\n\tTREE_INDENT,\n} from \"./output-tree.js\";\nimport {\n\tgetStateElapsedMs,\n\tgetToolsRenderConfig,\n\tisResultSeen,\n\tmarkResultSeen,\n\trecordExecutionEnded,\n\tstartElapsedTicker,\n\tstopElapsedTicker,\n} from \"./session-config.js\";\nimport { type BoxedToolContext, type BoxedToolDefinition, noteBoxedCallState, noteExecutionStart } from \"./shared.js\";\n\nconst MAX_LINE_CHARS = 2000;\nconst ESC = \"\\x1b\";\nconst BASH_TOOL_NOTICE_PATTERN = /^\\[Showing (?:last|lines)\\b.*\\. Full output: .+\\]$/;\nconst BG_ANSI_PATTERN = new RegExp(`${ESC}\\\\[4[0-9;]*m`, \"g\");\nconst SHELL_VAR_PATTERN = /\\$\\{?[A-Za-z_][A-Za-z0-9_]*\\}?/;\nconst SHELL_OP_PATTERN = /^(?:&&|\\|\\||>>|>&|\\|&|[|&;()<>])$/;\n\nfunction highlightBashFallback(line: string): string {\n\ttry {\n\t\tconst highlighted = highlightCode(line, \"bash\")[0] ?? line;\n\t\t// Strip background colors to avoid clashing with badge/parens styling\n\t\treturn highlighted.replace(BG_ANSI_PATTERN, \"\");\n\t} catch {\n\t\treturn line;\n\t}\n}\n\nfunction normalizeShellWord(word: string): string {\n\treturn word.replace(/^(['\"])(.*)\\1$/, \"$2\");\n}\n\nfunction colorShellWord(theme: BoxTheme, word: string, commandExpected: boolean): string {\n\tconst normalized = normalizeShellWord(word);\n\tif (/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(normalized)) return theme.fg(\"syntaxVariable\", word);\n\tif (normalized.startsWith(\"-\")) return theme.fg(\"syntaxKeyword\", word);\n\tif (normalized.includes(\"/\") || /^\\.{1,2}(?:\\/|$)/.test(normalized)) return theme.fg(\"syntaxVariable\", word);\n\tif (SHELL_VAR_PATTERN.test(normalized)) return theme.fg(\"syntaxVariable\", word);\n\treturn commandExpected ? theme.fg(\"syntaxFunction\", word) : theme.fg(\"syntaxString\", word);\n}\n\nfunction tokenizeShellLinePreservingText(line: string): string[] | undefined {\n\tconst tokens: string[] = [];\n\tlet current = \"\";\n\tlet quote: string | null = null;\n\n\tfor (let i = 0; i < line.length; i++) {\n\t\tconst char = line[i] ?? \"\";\n\t\tconst next = line[i + 1] ?? \"\";\n\n\t\tif (quote) {\n\t\t\tcurrent += char;\n\t\t\tif (char === \"\\\\\" && next) current += line[++i] ?? \"\";\n\t\t\telse if (char === quote) quote = null;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === \"'\" || char === '\"') {\n\t\t\tquote = char;\n\t\t\tcurrent += char;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (/\\s/.test(char)) {\n\t\t\tif (current) tokens.push(current);\n\t\t\tcurrent = \"\";\n\t\t\ttokens.push(char);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === \"#\" && !current) {\n\t\t\tif (current) tokens.push(current);\n\t\t\ttokens.push(line.slice(i));\n\t\t\treturn tokens;\n\t\t}\n\n\t\tconst two = `${char}${next}`;\n\t\tif (SHELL_OP_PATTERN.test(two) || SHELL_OP_PATTERN.test(char)) {\n\t\t\tif (current) tokens.push(current);\n\t\t\tcurrent = \"\";\n\t\t\tif (SHELL_OP_PATTERN.test(two)) {\n\t\t\t\ttokens.push(two);\n\t\t\t\ti++;\n\t\t\t} else {\n\t\t\t\ttokens.push(char);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tcurrent += char;\n\t}\n\n\tif (quote) return undefined;\n\tif (current) tokens.push(current);\n\treturn tokens;\n}\n\nfunction highlightBashLine(line: string, theme: BoxTheme): string {\n\tconst tokens = tokenizeShellLinePreservingText(line);\n\tif (!tokens) return highlightBashFallback(line);\n\tlet commandExpected = true;\n\treturn tokens\n\t\t.map((token) => {\n\t\t\tif (/^\\s+$/.test(token)) return token;\n\t\t\tif (token.startsWith(\"#\")) return theme.fg(\"syntaxComment\", token);\n\t\t\tif (SHELL_OP_PATTERN.test(token)) {\n\t\t\t\tcommandExpected = token === \"|\" || token === \"||\" || token === \"&&\" || token === \";\" || token === \"&\";\n\t\t\t\treturn theme.fg(\"syntaxOperator\", token);\n\t\t\t}\n\t\t\tconst styled = colorShellWord(theme, token, commandExpected);\n\t\t\tif (!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(normalizeShellWord(token))) commandExpected = false;\n\t\t\treturn styled;\n\t\t})\n\t\t.join(\"\");\n}\n\nfunction clampLineLength(line: string, max: number = MAX_LINE_CHARS): string {\n\tif (line.length <= max) return line;\n\treturn `${truncateAtCodePointBoundary(line, max)}… (truncated)`;\n}\n\nfunction countNewlines(text: string, from: number, to: number): number {\n\tlet count = 0;\n\tfor (let i = from; i < to; i++) {\n\t\tif (text.charCodeAt(i) === 10) count++;\n\t}\n\treturn count;\n}\n\nfunction stripBashToolNoticeLines(text: string): string {\n\tconst filteredLines = text\n\t\t.replace(/\\r/g, \"\")\n\t\t.split(\"\\n\")\n\t\t.filter((line) => !BASH_TOOL_NOTICE_PATTERN.test(line.trim()));\n\treturn filteredLines\n\t\t.join(\"\\n\")\n\t\t.replace(/\\n{3,}/g, \"\\n\\n\")\n\t\t.trimEnd();\n}\n\nfunction bashWidthKey(rawCommand: string, timeout: unknown): string {\n\treturn boxedToolWidthKey(\"Bash\", `${rawCommand}|${timeout ?? \"\"}`);\n}\n\nfunction renderBoxedBashCall(\n\ttheme: BoxTheme,\n\tcommandLines: string[],\n\tcontext: BoxedToolContext,\n\twidthKey: string,\n): Component {\n\tconst maxCommandLines = 5;\n\tconst shownCount = Math.min(commandLines.length, maxCommandLines + 1);\n\tconst detailLines: string[] = [];\n\tfor (let i = 0; i < shownCount; i++) {\n\t\tconst prefix = i === 0 ? theme.fg(\"dim\", \"$ \") : theme.fg(\"dim\", \"> \");\n\t\tdetailLines.push(`${prefix}${highlightBashLine(commandLines[i] ?? \"\", theme)}`);\n\t}\n\tif (commandLines.length > maxCommandLines + 1) {\n\t\tdetailLines.push(theme.fg(\"muted\", `... ${commandLines.length - maxCommandLines - 1} more lines`));\n\t}\n\tconst running = Boolean(context.executionStarted);\n\tconst resultSeen = isResultSeen(context.state);\n\tconst base = {\n\t\twidthKey,\n\t\tisError: Boolean(context.isError),\n\t\tisPartial: Boolean(context.isPartial),\n\t\tisPending: Boolean(context.isPartial),\n\t\trunning,\n\t};\n\tif (running && context.isPartial && !resultSeen) {\n\t\t// Pre-result running card: the call closes the box with a live running\n\t\t// footer and a `No output received yet` line. The first partial result\n\t\t// renders nothing, so this card is never duplicated below.\n\t\tdetailLines.push(theme.fg(\"dim\", \"No output received yet\"));\n\t\treturn renderBoxedToolCall(theme, \"Bash\", detailLines, {\n\t\t\t...base,\n\t\t\tpendingLabel: formatBoxedRunningStatus(theme, getStateElapsedMs(context.state)),\n\t\t});\n\t}\n\t// Streaming (a result renderer already continues this box) and terminal\n\t// (settled) passes leave the box open so the result closes it.\n\treturn renderBoxedToolCall(theme, \"Bash\", detailLines, { ...base, resultSeen });\n}\n\n// ── Terminal status detection ────────────────────────────────────────────────\n// The bash tool appends a `\\n\\n<status>` suffix to failed results (nonzero exit,\n// timeout, abort). Parse it off the raw text so the footer can carry the real\n// status instead of displaying the suffix as output.\n\ntype BashTerminalStatus =\n\t| { kind: \"exit\"; exitCode: number }\n\t| { kind: \"timeout\"; seconds: number }\n\t| { kind: \"cancelled\" };\n\nconst BASH_STATUS_PATTERNS: ReadonlyArray<{\n\tre: RegExp;\n\tbuild: (match: RegExpMatchArray) => BashTerminalStatus;\n}> = [\n\t{\n\t\tre: /(?:^|\\n\\n)Command timed out after ([\\d.]+) seconds$/i,\n\t\tbuild: (match) => ({ kind: \"timeout\", seconds: Number(match[1]) }),\n\t},\n\t{ re: /(?:^|\\n\\n)[^\\n]*aborted$/i, build: () => ({ kind: \"cancelled\" }) },\n\t{\n\t\tre: /(?:^|\\n\\n)Command exited with code (\\d+)$/i,\n\t\tbuild: (match) => ({ kind: \"exit\", exitCode: Number(match[1]) }),\n\t},\n];\n\nfunction parseBashTerminalStatus(text: string): { status: BashTerminalStatus | undefined; body: string } {\n\tconst clean = String(text ?? \"\").replace(/\\r/g, \"\");\n\tfor (const { re, build } of BASH_STATUS_PATTERNS) {\n\t\tconst match = clean.match(re);\n\t\tif (match && match.index !== undefined) {\n\t\t\treturn { status: build(match), body: clean.slice(0, match.index).trimEnd() };\n\t\t}\n\t}\n\t// Pi's message_end error path (agent aborted) sends a bare status text with\n\t// no bash output shape; recognize it as a cancelled state.\n\tif (/^(?:operation )?aborted(?: after \\d+ retry attempts?)?$/i.test(clean.trim())) {\n\t\treturn { status: { kind: \"cancelled\" }, body: \"\" };\n\t}\n\treturn { status: undefined, body: clean };\n}\n\nfunction bashErrorLabel(status: BashTerminalStatus | undefined): string | undefined {\n\tif (status?.kind === \"timeout\") return \"✗ Timed out\";\n\tif (status?.kind === \"cancelled\") return \"✗ Cancelled\";\n\treturn undefined;\n}\n\n/** Body text shown when a terminal bash result produced no output. */\nfunction bashEmptyBodyText(status: BashTerminalStatus | undefined, isError: boolean): string {\n\tif (status?.kind === \"timeout\") return \"No output was received before the timeout\";\n\tif (status?.kind === \"cancelled\") return \"Command was cancelled without producing output\";\n\tif (isError) return \"Command failed without producing output\";\n\treturn \"Command completed without producing output\";\n}\n\nfunction bashFooter(\n\ttheme: BoxTheme,\n\tstatus: BashTerminalStatus | undefined,\n\telapsedMs: number | undefined,\n\tbodyText: string,\n\tisError: boolean,\n): string {\n\tconst elapsed = elapsedMs === undefined ? \"--\" : `${(elapsedMs / 1000).toFixed(2)}s`;\n\tconst words = bodyText.trim() ? formatBoxedWords(bodyText) : \"\";\n\n\tif (status?.kind === \"timeout\") {\n\t\tconst seconds = Number.isFinite(status.seconds) && status.seconds > 0 ? status.seconds : Number.NaN;\n\t\treturn theme.fg(\n\t\t\t\"warning\",\n\t\t\tNumber.isFinite(seconds) ? `Terminated after ${seconds.toFixed(1)}s` : \"Terminated by timeout\",\n\t\t);\n\t}\n\tif (status?.kind === \"cancelled\") {\n\t\treturn [theme.fg(\"warning\", \"Cancelled\"), theme.fg(\"text\", elapsed)].join(theme.fg(\"dim\", \" · \"));\n\t}\n\n\tconst exitLabel = status?.kind === \"exit\" ? `Exit ${status.exitCode}` : isError ? \"Failed\" : \"Exit 0\";\n\tconst exitColor = status?.kind === \"exit\" && status.exitCode !== 0 ? \"error\" : \"text\";\n\tconst parts = [theme.fg(exitColor, exitLabel), theme.fg(\"text\", elapsed)];\n\tif (words) parts.push(theme.fg(\"dim\", words));\n\treturn parts.join(theme.fg(\"dim\", \" · \"));\n}\n\n// ── Interactive command heuristics ───────────────────────────────────────────\n// Terminal programs that read stdin or own the screen produce no pipe output;\n// when one runs silently we hint that it may be waiting for terminal input.\n\nconst INTERACTIVE_COMMANDS = new Set([\n\t\"pi\",\n\t\"vim\",\n\t\"vi\",\n\t\"nvim\",\n\t\"nano\",\n\t\"less\",\n\t\"more\",\n\t\"man\",\n\t\"top\",\n\t\"htop\",\n\t\"btop\",\n\t\"ssh\",\n\t\"telnet\",\n\t\"python\",\n\t\"python3\",\n\t\"node\",\n\t\"sqlite3\",\n\t\"mysql\",\n\t\"psql\",\n\t\"redis-cli\",\n\t\"mongosh\",\n\t\"bc\",\n\t\"irssi\",\n]);\n\nfunction isInteractiveCommand(command: unknown): boolean {\n\tconst base =\n\t\t(\n\t\t\tString(command ?? \"\")\n\t\t\t\t.trim()\n\t\t\t\t.split(/\\s+/)[0] ?? \"\"\n\t\t)\n\t\t\t.split(\"/\")\n\t\t\t.pop() ?? \"\";\n\treturn INTERACTIVE_COMMANDS.has(base);\n}\n\n/** Wrap an output preview so an empty result renders state text instead of `∅`. */\nfunction bashBodyComponent(preview: Component, emptyLines: string[] | undefined): Component {\n\tif (!emptyLines) return preview;\n\treturn {\n\t\tinvalidate: () => preview.invalidate(),\n\t\trender(width: number): string[] {\n\t\t\tconst lines = preview.render(width);\n\t\t\treturn lines.length > 0 ? lines : emptyLines;\n\t\t},\n\t};\n}\n\n/** Streaming continuation: streamed output (or `No output received yet`), a\n * live running footer, and no `Response` divider until the tool settles. */\nfunction renderBashStreamingResult(\n\ttheme: BoxTheme,\n\traw: string,\n\toptions: { expanded: boolean },\n\tcontext: BoxedToolContext,\n): Component {\n\tconst body = stripBashToolNoticeLines(stripAnsi(raw));\n\tconst hasOutput = body.trim().length > 0;\n\tconst elapsed = getStateElapsedMs(context.state);\n\tconst emptyLines: string[] = [theme.fg(\"dim\", \"No output received yet\")];\n\tif (!hasOutput && isInteractiveCommand(context?.args?.command) && (elapsed ?? 0) >= 1000) {\n\t\temptyLines.push(theme.fg(\"dim\", \"The process may be waiting for terminal input\"));\n\t}\n\tconst preview = createBashResultPreview(theme, body, options, \"toolOutput\");\n\tconst rawCommand = String(context?.args?.command ?? \"...\");\n\treturn renderBoxedToolResult(theme, bashBodyComponent(preview, hasOutput ? undefined : emptyLines), {\n\t\twidthKey: bashWidthKey(rawCommand, context?.args?.timeout),\n\t\treferenceLines: rawCommand.split(\"\\n\").map((line, index) => `${index === 0 ? \"$ \" : \"> \"}${line}`),\n\t\tdividerLabel: \"Output\",\n\t\tshowDivider: hasOutput,\n\t\tfooterLines: [formatBoxedRunningStatus(theme, elapsed)],\n\t\tisPartial: true,\n\t});\n}\n\nfunction renderBashFinalResult(\n\ttheme: BoxTheme,\n\traw: string,\n\toptions: { expanded: boolean },\n\tcontext: BoxedToolContext,\n): Component {\n\tconst isError = Boolean(context.isError);\n\tconst clean = stripAnsi(raw);\n\tconst { status, body: statusStripped } = parseBashTerminalStatus(clean);\n\tconst output = stripBashToolNoticeLines(statusStripped);\n\tconst elapsed = getStateElapsedMs(context.state);\n\tconst outputColor = isError ? \"error\" : \"toolOutput\";\n\tconst footer = bashFooter(theme, status, elapsed, output, isError);\n\tconst errorLabel = isError ? (bashErrorLabel(status) ?? \"✗ Error\") : undefined;\n\n\tconst rawCommand = String(context?.args?.command ?? \"...\");\n\tconst widthKey = bashWidthKey(rawCommand, context?.args?.timeout);\n\tconst referenceLines = rawCommand.split(\"\\n\").map((line, index) => `${index === 0 ? \"$ \" : \"> \"}${line}`);\n\n\tif (!options.expanded) {\n\t\t// Collapsed: only process the tail of the output (notices stripped per line).\n\t\tconst scanLines = getToolsRenderConfig().maxCollapsedLines + 10;\n\t\tlet nlCount = 0;\n\t\tlet tailStart = 0;\n\t\tfor (let i = statusStripped.length - 1; i >= 0; i--) {\n\t\t\tif (statusStripped.charCodeAt(i) === 10) {\n\t\t\t\tnlCount++;\n\t\t\t\tif (nlCount >= scanLines) {\n\t\t\t\t\ttailStart = i + 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst tail = stripBashToolNoticeLines(stripAnsi(statusStripped.slice(tailStart)));\n\t\tconst totalLinesBefore = tailStart > 0 ? countNewlines(statusStripped, 0, tailStart) : 0;\n\t\tconst preview = createBashResultPreview(theme, tail, options, outputColor);\n\t\treturn renderBoxedToolResult(\n\t\t\ttheme,\n\t\t\tbashBodyComponent(\n\t\t\t\tpreview,\n\t\t\t\tstatusStripped.trim() ? undefined : [theme.fg(\"muted\", bashEmptyBodyText(status, isError))],\n\t\t\t),\n\t\t\t{\n\t\t\t\twidthKey,\n\t\t\t\treferenceLines,\n\t\t\t\tfooterLines: [footer],\n\t\t\t\t...(totalLinesBefore > 0 ? { expandHint: \"Ctrl+O for more\" } : {}),\n\t\t\t\tisError,\n\t\t\t\tisPartial: false,\n\t\t\t\t...(errorLabel ? { errorLabel } : {}),\n\t\t\t},\n\t\t);\n\t}\n\n\tconst preview = createBashResultPreview(theme, output, options, outputColor);\n\treturn renderBoxedToolResult(\n\t\ttheme,\n\t\tbashBodyComponent(preview, output.trim() ? undefined : [theme.fg(\"muted\", bashEmptyBodyText(status, isError))]),\n\t\t{\n\t\t\twidthKey,\n\t\t\treferenceLines,\n\t\t\tfooterLines: [footer],\n\t\t\tisError,\n\t\t\tisPartial: false,\n\t\t\t...(errorLabel ? { errorLabel } : {}),\n\t\t},\n\t);\n}\n\n/** First-partial-pass result: the pending/running call card stands alone. */\nconst EMPTY_BASH_RESULT: Component = Object.freeze({\n\tinvalidate() {},\n\trender() {\n\t\treturn [];\n\t},\n});\n\nfunction createBashResultPreview(\n\ttheme: BoxTheme,\n\ttext: string,\n\toptions: { expanded: boolean },\n\tcolor: \"toolOutput\" | \"error\",\n): Component {\n\tlet cacheKey = \"\";\n\tlet cacheLines: string[] | null = null;\n\n\treturn {\n\t\tinvalidate() {\n\t\t\tcacheKey = \"\";\n\t\t\tcacheLines = null;\n\t\t},\n\t\trender(width: number): string[] {\n\t\t\tconst bodyWidth = Math.max(1, width);\n\t\t\tconst cfg = getToolsRenderConfig();\n\t\t\tconst expanded = Boolean(options.expanded);\n\t\t\tconst cacheId = `${bodyWidth}|${expanded ? 1 : 0}|${cfg.maxExpandedLines}|${cfg.dimOutput ? 1 : 0}`;\n\t\t\tif (cacheLines && cacheKey === cacheId) return cacheLines;\n\n\t\t\tif (!expanded) {\n\t\t\t\t// Collapsed: only process the tail of the output\n\t\t\t\tconst needed = cfg.maxCollapsedLines;\n\t\t\t\tlet totalNewlines = 0;\n\t\t\t\tlet scanFrom = 0; // default: take full text if fewer than needed newlines\n\t\t\t\tfor (let i = text.length - 1; i >= 0; i--) {\n\t\t\t\t\tif (text.charCodeAt(i) === 10) {\n\t\t\t\t\t\ttotalNewlines++;\n\t\t\t\t\t\tif (totalNewlines === needed) {\n\t\t\t\t\t\t\tscanFrom = i + 1;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (text.length === 0) {\n\t\t\t\t\tcacheKey = cacheId;\n\t\t\t\t\tcacheLines = [];\n\t\t\t\t\treturn cacheLines;\n\t\t\t\t}\n\n\t\t\t\tconst tail = replaceTabs(text.slice(scanFrom)).replace(/\\r/g, \"\");\n\t\t\t\tconst shownLines = tail ? tail.split(\"\\n\").map((l) => clampLineLength(l)) : [];\n\n\t\t\t\tif (shownLines.length === 0) {\n\t\t\t\t\tcacheKey = cacheId;\n\t\t\t\t\tcacheLines = [];\n\t\t\t\t\treturn cacheLines;\n\t\t\t\t}\n\n\t\t\t\tconst truncatedShown = shownLines.map((line) => {\n\t\t\t\t\tconst truncated = safeTruncateToWidth(line, bodyWidth, \"…\");\n\t\t\t\t\tif (color === \"error\") return formatToolOutputLine(theme, truncated, \"error\");\n\t\t\t\t\treturn cfg.dimOutput\n\t\t\t\t\t\t? formatToolOutputLine(theme, truncated)\n\t\t\t\t\t\t: formatToolOutputLine(theme, truncated, \"text\");\n\t\t\t\t});\n\n\t\t\t\tcacheKey = cacheId;\n\t\t\t\tcacheLines = truncatedShown;\n\t\t\t\treturn cacheLines;\n\t\t\t}\n\n\t\t\t// Expanded: process all lines\n\t\t\tconst normalized = replaceTabs(text);\n\t\t\tconst logicalLines = normalized.split(\"\\n\").map((l) => clampLineLength(l));\n\t\t\tconst hasOutput = !(logicalLines.length === 1 && logicalLines[0] === \"\");\n\n\t\t\tif (!hasOutput) {\n\t\t\t\tcacheKey = cacheId;\n\t\t\t\tcacheLines = [];\n\t\t\t\treturn cacheLines;\n\t\t\t}\n\n\t\t\tconst truncatedLines = logicalLines.map((line) => safeTruncateToWidth(line, bodyWidth, \"…\"));\n\t\t\tconst expandedLines = truncatedLines.length === 1 && truncatedLines[0] === \"\" ? [] : truncatedLines;\n\t\t\tconst applyColor = (l: string) =>\n\t\t\t\tcolor === \"error\"\n\t\t\t\t\t? formatToolOutputLine(theme, l, \"error\")\n\t\t\t\t\t: cfg.dimOutput\n\t\t\t\t\t\t? formatToolOutputLine(theme, l)\n\t\t\t\t\t\t: formatToolOutputLine(theme, l, \"text\");\n\t\t\tif (cfg.maxExpandedLines > 0 && expandedLines.length > cfg.maxExpandedLines) {\n\t\t\t\tconst truncated = expandedLines.slice(-cfg.maxExpandedLines).map(applyColor);\n\t\t\t\tconst remaining = expandedLines.length - cfg.maxExpandedLines;\n\t\t\t\ttruncated.unshift(theme.fg(\"dim\", `… ${remaining} earlier lines`));\n\t\t\t\tcacheKey = cacheId;\n\t\t\t\tcacheLines = truncated;\n\t\t\t\treturn cacheLines;\n\t\t\t}\n\n\t\t\tcacheKey = cacheId;\n\t\t\tcacheLines = expandedLines.map(applyColor);\n\t\t\treturn cacheLines;\n\t\t},\n\t};\n}\n\n// ── ls/find/grep/rg command detection ───────────────────────────────────────\n// A bash command whose real command is ls/find/grep/rg (after env assignments,\n// sudo/env/time prefixes, and path stripping), with no shell metacharacters\n// (pipes, redirects, `;`, `&&`, command substitution, subshells, newlines), is\n// rendered as the same boxless output tree as the corresponding native tool.\n// Everything else keeps the boxed command/response shell.\n\ntype BashTreeKind = \"ls\" | \"find\" | \"grep\";\n\ninterface BashTreeClass {\n\treadonly kind: BashTreeKind;\n\treadonly pattern?: string;\n\treadonly pathLabel?: string;\n\t/** grep: exactly one path positional — single-file output (`line: content`)\n\t * is attributed to it. */\n\treadonly singlePath?: string;\n}\n\nconst BASH_PREFIX_COMMANDS = new Set([\"sudo\", \"env\", \"time\", \"nice\", \"nohup\", \"command\", \"stdbuf\", \"ionice\", \"watch\"]);\nconst BASH_GREP_COMMANDS = new Set([\"grep\", \"egrep\", \"fgrep\", \"rg\"]);\n// Pipes (`|`), `;`, and `&` are excluded here: the classifier validates them\n// explicitly (allowing `cd X && cmd` chains and a trailing `| head/tail`).\nconst BASH_SHELL_META_CHARS = new Set([\"<\", \">\", \"(\", \")\", \"`\"]);\n\n/** Tokenize a single command line, stripping quotes. Returns null on an\n * unterminated quote. `hasMeta` is true if any shell metacharacter appears\n * *outside* quotes (so `grep 'a|b' f` stays classifiable). */\nfunction tokenizeCommandLine(line: string): { tokens: string[]; hasMeta: boolean } | null {\n\tconst tokens: string[] = [];\n\tlet current = \"\";\n\tlet inToken = false;\n\tlet quote: string | null = null;\n\tlet hasMeta = false;\n\tfor (let i = 0; i < line.length; i++) {\n\t\tconst char = line[i] ?? \"\";\n\t\tif (quote) {\n\t\t\tif (char === \"\\\\\" && quote === '\"') {\n\t\t\t\tcurrent += line[++i] ?? \"\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (char === quote) {\n\t\t\t\tquote = null;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcurrent += char;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === '\"' || char === \"'\") {\n\t\t\tquote = char;\n\t\t\tinToken = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === \" \" || char === \"\\t\") {\n\t\t\tif (inToken) {\n\t\t\t\ttokens.push(current);\n\t\t\t\tcurrent = \"\";\n\t\t\t\tinToken = false;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (BASH_SHELL_META_CHARS.has(char) || (char === \"$\" && (line[i + 1] ?? \"\") === \"(\")) {\n\t\t\thasMeta = true;\n\t\t\tcontinue;\n\t\t}\n\t\tcurrent += char;\n\t\tinToken = true;\n\t}\n\tif (quote) return null;\n\tif (inToken) tokens.push(current);\n\treturn { tokens, hasMeta };\n}\n\n/** grep/rg flags that consume a separate value token (`--type ts`). */\nconst GREP_VALUE_FLAGS = new Set([\n\t\"-e\",\n\t\"--regexp\",\n\t\"-g\",\n\t\"--glob\",\n\t\"--type\",\n\t\"-t\",\n\t\"--include\",\n\t\"--exclude\",\n\t\"-C\",\n\t\"-A\",\n\t\"-B\",\n\t\"--context\",\n\t\"--after-context\",\n\t\"--before-context\",\n\t\"-m\",\n\t\"--max-count\",\n\t\"-M\",\n\t\"--max-columns\",\n\t\"--ignore-file\",\n]);\n\n/** find flags that consume a separate value token (`-type f`). */\nconst FIND_VALUE_FLAGS = new Set([\n\t\"-type\",\n\t\"-mtime\",\n\t\"-atime\",\n\t\"-ctime\",\n\t\"-size\",\n\t\"-maxdepth\",\n\t\"-mindepth\",\n\t\"-perm\",\n\t\"-group\",\n\t\"-user\",\n\t\"-newer\",\n]);\n\nfunction classifyByArgs(kind: BashTreeKind, args: string[]): BashTreeClass {\n\tconst positionals: string[] = [];\n\tlet pattern: string | undefined;\n\tfor (let i = 0; i < args.length; i++) {\n\t\tconst token = args[i] ?? \"\";\n\t\tif (\n\t\t\t(kind === \"grep\" && (token === \"-e\" || token === \"--regexp\")) ||\n\t\t\t(kind === \"find\" && (token === \"-name\" || token === \"-iname\" || token === \"-path\" || token === \"-ipath\"))\n\t\t) {\n\t\t\tpattern = args[++i];\n\t\t\tcontinue;\n\t\t}\n\t\tif (kind === \"grep\" && GREP_VALUE_FLAGS.has(token)) {\n\t\t\ti++; // skip the flag and its value\n\t\t\tcontinue;\n\t\t}\n\t\tif (kind === \"find\" && FIND_VALUE_FLAGS.has(token)) {\n\t\t\ti++; // skip the flag and its value\n\t\t\tcontinue;\n\t\t}\n\t\tif (token.startsWith(\"-\")) continue;\n\t\tpositionals.push(token);\n\t}\n\tconst rawPath = positionals[0] ?? \".\";\n\tconst pathLabel = rawPath === \".\" ? \"current directory\" : shortenPath(rawPath);\n\tif (kind === \"ls\") return { kind, pathLabel };\n\tif (kind === \"find\") return { kind, ...(pattern !== undefined ? { pattern } : {}), pathLabel };\n\tconst grepPattern = pattern ?? positionals[0];\n\tconst pathArgs = pattern !== undefined ? positionals : positionals.slice(1);\n\tconst grepPath = pathArgs.join(\" \");\n\tconst grepPathLabel = !grepPath || grepPath === \".\" ? \"current directory\" : shortenPath(grepPath);\n\treturn {\n\t\tkind,\n\t\t...(grepPattern !== undefined ? { pattern: grepPattern } : {}),\n\t\tpathLabel: grepPathLabel,\n\t\t...(pathArgs.length === 1 ? { singlePath: pathArgs[0] ?? \"\" } : {}),\n\t};\n}\n\n/** `head [-n N]` / `tail [-n N]` truncation pipe tail (allowed at the end). */\nfunction isHeadOrTailTail(tokens: readonly string[]): boolean {\n\tif (tokens.length === 0 || (tokens[0] !== \"head\" && tokens[0] !== \"tail\")) return false;\n\tfor (let i = 1; i < tokens.length; i++) {\n\t\tconst token = tokens[i] ?? \"\";\n\t\tif (token === \"-n\") continue;\n\t\tif (/^\\d+$/.test(token)) continue;\n\t\tif (/^-\\d+$/.test(token)) continue;\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n/** Classify a bash command for tree rendering, or null to keep the boxed shell. */\nexport function classifyBashCommand(command: string): BashTreeClass | null {\n\tconst commandText = String(command ?? \"\").trim();\n\tif (!commandText || commandText.includes(\"\\n\")) return null;\n\tconst tokenized = tokenizeCommandLine(commandText);\n\tif (!tokenized || tokenized.hasMeta || tokenized.tokens.length === 0) return null;\n\tlet tokens = tokenized.tokens;\n\n\t// Allow a single trailing truncation pipe: `cmd | head [-n] N` / `| tail …`.\n\tconst pipes = tokens.flatMap((token, i) => (token === \"|\" ? [i] : []));\n\tif (pipes.length > 0) {\n\t\tif (pipes.length > 1) return null;\n\t\tconst last = pipes[0] ?? -1;\n\t\tif (!isHeadOrTailTail(tokens.slice(last + 1))) return null;\n\t\ttokens = tokens.slice(0, last);\n\t}\n\n\tlet index = 0;\n\t// Skip leading environment assignments (FOO=bar ...) and prefix commands.\n\twhile (index < tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[index] ?? \"\")) index++;\n\twhile (index < tokens.length && BASH_PREFIX_COMMANDS.has(tokens[index] ?? \"\")) index++;\n\t// `cd <dir> &&` / `cd <dir>;` chains: the last directory becomes the default\n\t// path when the command itself carries none.\n\tlet cdDir: string | undefined;\n\twhile (\n\t\ttokens[index] === \"cd\" &&\n\t\tindex + 2 < tokens.length &&\n\t\ttokens[index + 1] !== undefined &&\n\t\t(tokens[index + 2] === \"&&\" || tokens[index + 2] === \";\")\n\t) {\n\t\tcdDir = tokens[index + 1];\n\t\tindex += 3;\n\t}\n\tconst rest = tokens.slice(index);\n\tif (rest.length === 0 || rest.some((token) => token === \"&&\" || token === \";\" || token === \"&\")) return null;\n\n\tconst base = (rest[0] ?? \"\").split(\"/\").pop() ?? \"\";\n\tlet kind: BashTreeKind | null = null;\n\tif (base === \"ls\") kind = \"ls\";\n\telse if (base === \"find\") kind = \"find\";\n\telse if (BASH_GREP_COMMANDS.has(base)) kind = \"grep\";\n\tif (!kind) return null;\n\n\tconst cls = classifyByArgs(kind, rest.slice(1));\n\tif (cdDir && cls.pathLabel === \"current directory\") {\n\t\treturn {\n\t\t\tkind,\n\t\t\t...(cls.pattern !== undefined ? { pattern: cls.pattern } : {}),\n\t\t\tpathLabel: shortenPath(cdDir),\n\t\t\t...(cls.singlePath !== undefined ? { singlePath: cls.singlePath } : {}),\n\t\t};\n\t}\n\treturn cls;\n}\n\nfunction bashTreeHeader(theme: BoxTheme, cls: BashTreeClass, counts?: { files?: number; matches?: number }): string {\n\tconst label = cls.kind === \"find\" ? \"Glob\" : cls.kind === \"ls\" ? \"List\" : \"Grep\";\n\tconst hasDetail = Boolean(cls.pattern) || Boolean(counts);\n\t// ls/find/grep headers carry the magnifying-glass icon in Nerd Font mode.\n\tconst icon = getToolsRenderConfig().nerdFonts ? `${SEARCH_ICON} ` : \"\";\n\tconst prefix = icon + (hasDetail ? `${label}:` : label);\n\tconst patternPart = cls.pattern ? ` ${theme.fg(\"text\", cls.pattern)}` : \"\";\n\tlet middle = \"\";\n\tif (counts) {\n\t\tif (cls.kind === \"grep\") {\n\t\t\tconst matches = counts.matches ?? 0;\n\t\t\tconst files = counts.files ?? 0;\n\t\t\tmiddle = ` ${theme.fg(\"accent\", `${matches} ${pluralForm(\"match\", matches)}`)}${theme.fg(\"dim\", ` · ${files} ${pluralForm(\"file\", files)}`)}`;\n\t\t} else {\n\t\t\tconst files = counts.files ?? 0;\n\t\t\tmiddle = ` ${theme.fg(\"accent\", `${files} ${pluralForm(\"file\", files)}`)}`;\n\t\t}\n\t}\n\tconst pathPart =\n\t\tcls.pathLabel && cls.pathLabel !== \"current directory\" ? theme.fg(\"dim\", ` · in ${cls.pathLabel}`) : \"\";\n\treturn `${typeof theme?.bold === \"function\" ? theme.bold(prefix) : prefix}${patternPart}${middle}${pathPart}`;\n}\n\n/** `ls -l` long-format lines (permissions block) can't be parsed into names\n * reliably; fall back to the boxed shell for those. A leading `total N`\n * summary line is skipped before the check. */\nfunction isLongFormatLs(text: string): boolean {\n\tconst first = text\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trim())\n\t\t.find((line) => line.length > 0 && !/^total\\s+\\d+$/i.test(line));\n\treturn Boolean(first) && /^[bcdlsp-][rwxtsST-]{9}[\\s@]/.test(first as string);\n}\n\n/** Parsed bash tree output, or null to fall back to the boxed shell\n * (long-format ls, unparseable grep). */\ntype ParsedBashTree = { entries: string[] } | { matches: GrepMatch[] };\n\nfunction parseBashTreeOutput(cls: BashTreeClass, output: string): ParsedBashTree | null {\n\tif (cls.kind === \"ls\") {\n\t\t// `ls -l`/`ls -la` long format is parsed into names (with `/` for dirs)\n\t\t// so bash listings render like the List tool tree.\n\t\tif (isLongFormatLs(output)) return { entries: parseLsLongOutput(output) };\n\t\treturn { entries: parseLsOutput(output) };\n\t}\n\tif (cls.kind === \"find\") return { entries: parseFindOutput(output) };\n\tconst matches = parseGrepOutput(output);\n\tif (matches.length === 0 && output.trim().length > 0) {\n\t\t// Single-file `rg`/`grep` output is `line: content` with no filename:\n\t\t// attribute matches to the command's single path argument.\n\t\tif (cls.singlePath) {\n\t\t\tconst bare = parseGrepBareOutput(output, cls.singlePath);\n\t\t\tif (bare.length > 0) return { matches: bare };\n\t\t}\n\t\treturn null;\n\t}\n\treturn { matches };\n}\n\ninterface BashTreeState {\n\treadonly cls: BashTreeClass;\n\t/** Raw command, so the call panel can render the boxed bash call on fallback. */\n\treadonly command: string;\n\t/** `parsed` once the result arrives; `fallback` when the boxed shell takes over. */\n\tparsed?: ParsedBashTree;\n\tfallback?: boolean;\n}\n\nconst bashTreeStates = new Map<string, BashTreeState>();\n\n/** Reset all bash tree state (session start/shutdown, new message). */\nexport function resetBashTreeRegistry(): void {\n\tbashTreeStates.clear();\n}\n\nfunction renderBashTreeLines(theme: BoxTheme, state: BashTreeState, width: number): string[] {\n\tconst safeWidth = Math.max(1, width);\n\tconst cls = state.cls;\n\tif (state.parsed && \"entries\" in state.parsed) {\n\t\tconst entries = state.parsed.entries;\n\t\treturn renderOutputTree(theme, bashTreeHeader(theme, cls, { files: entries.length }), entries, safeWidth, {\n\t\t\tmoreUnit: \"file\",\n\t\t\tindent: TREE_INDENT,\n\t\t\twithIcons: getToolsRenderConfig().nerdFonts,\n\t\t});\n\t}\n\tif (state.parsed && \"matches\" in state.parsed) {\n\t\tconst matches = state.parsed.matches;\n\t\treturn renderGrepTree(\n\t\t\ttheme,\n\t\t\tbashTreeHeader(theme, cls, { matches: matches.length, files: groupMatchesByFile(matches).length }),\n\t\t\tmatches,\n\t\t\tsafeWidth,\n\t\t\t{ indent: TREE_INDENT, withIcons: getToolsRenderConfig().nerdFonts },\n\t\t);\n\t}\n\treturn [safeTruncateToWidth(bashTreeHeader(theme, cls), safeWidth, \"…\")];\n}\n\n/** Empty result component — the tree lives in the call panel, which re-renders\n * with the parsed output once the result arrives. */\nconst EMPTY_BASH_TREE_RESULT: Component = {\n\tinvalidate() {},\n\trender() {\n\t\treturn [];\n\t},\n};\n\n/** Live panel component for a classified bash command: pending header until the\n * result arrives, then the parsed output tree. When the result falls back to\n * the boxed shell, the call renders the boxed bash call instead, so call and\n * result form one complete box and never duplicate. The state reference is\n * captured at creation so a registry clear on session reset/resume does not\n * blank already-rendered panels. */\nfunction renderBashTreePanel(theme: BoxTheme, toolCallId: string, context: BoxedToolContext): Component {\n\tconst state = bashTreeStates.get(toolCallId);\n\treturn {\n\t\tinvalidate() {},\n\t\trender(width: number): string[] {\n\t\t\tif (!state) return [];\n\t\t\tif (state.fallback) {\n\t\t\t\treturn renderBoxedBashCall(\n\t\t\t\t\ttheme,\n\t\t\t\t\tstate.command.split(\"\\n\"),\n\t\t\t\t\tcontext,\n\t\t\t\t\tbashWidthKey(state.command, context?.args?.timeout),\n\t\t\t\t).render(width);\n\t\t\t}\n\t\t\treturn renderBashTreeLines(theme, state, width);\n\t\t},\n\t};\n}\n\nexport const bashTool: BoxedToolDefinition = {\n\tcall(args, theme, context) {\n\t\tnoteExecutionStart(context);\n\t\tconst cls = classifyBashCommand(String(args?.command ?? \"\"));\n\t\tif (cls) {\n\t\t\tbashTreeStates.set(context.toolCallId, { cls, command: String(args?.command ?? \"\") });\n\t\t\treturn renderBashTreePanel(theme, context.toolCallId, context);\n\t\t}\n\t\tnoteBoxedCallState(context);\n\t\tconst rawCommand = String(args?.command ?? \"...\");\n\t\treturn renderBoxedBashCall(theme, rawCommand.split(\"\\n\"), context, bashWidthKey(rawCommand, args?.timeout));\n\t},\n\tresult(result, options, theme, context) {\n\t\tconst firstResultPass = !isResultSeen(context.state);\n\t\tmarkResultSeen(context.state);\n\t\tconst cls = classifyBashCommand(String(context?.args?.command ?? \"\"));\n\t\tif (cls && !context.isError) {\n\t\t\t// Tree-classified commands render in the call panel; the result adds\n\t\t\t// nothing. Keep terminal state in sync without an elapsed ticker.\n\t\t\tif (!options.isPartial) {\n\t\t\t\trecordExecutionEnded(context.state);\n\t\t\t\tstopElapsedTicker(context.state);\n\t\t\t}\n\t\t\tconst output = stripBashToolNoticeLines(stripAnsi(getTextOutput(result)));\n\t\t\tconst parsed = parseBashTreeOutput(cls, output);\n\t\t\tconst state = bashTreeStates.get(context.toolCallId);\n\t\t\tif (parsed) {\n\t\t\t\tif (state) state.parsed = parsed;\n\t\t\t\telse bashTreeStates.set(context.toolCallId, { cls, command: String(context?.args?.command ?? \"\"), parsed });\n\t\t\t\treturn EMPTY_BASH_TREE_RESULT;\n\t\t\t}\n\t\t\t// Unparseable output (ls -l, raw rg summary): the boxed shell owns the\n\t\t\t// result; flag the call panel to render nothing so the two don't duplicate.\n\t\t\tif (state) state.fallback = true;\n\t\t} else if (options.isPartial) {\n\t\t\tstartElapsedTicker(context.state, context.invalidate);\n\t\t} else {\n\t\t\trecordExecutionEnded(context.state);\n\t\t\tstopElapsedTicker(context.state);\n\t\t}\n\t\tconst raw = getTextOutput(result);\n\t\tif (options.isPartial) {\n\t\t\t// First partial pass: the running call card stands alone. Later passes\n\t\t\t// stream output into the open continuation without a Response divider.\n\t\t\tif (firstResultPass) return EMPTY_BASH_RESULT;\n\t\t\treturn renderBashStreamingResult(theme, raw, options, context);\n\t\t}\n\t\treturn renderBashFinalResult(theme, raw, options, context);\n\t},\n};\n","// Shared context/view types + common helpers for the boxed tool renderers.\n\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport type { BoxTheme } from \"../../../shared/box.js\";\nimport {\n\tboxedToolWidthKey,\n\tclearCompactBoxedFooter,\n\tformatBoxedFooter,\n\tformatBoxedFooterFromValues,\n\tgetTextOutput,\n\trenderCompactBoxedFooter,\n\trenderCompactBoxedToolCall,\n\tresolveRelativePath,\n\tshortenPath,\n} from \"../../../shared/box.js\";\nimport {\n\tgetStateElapsedMs,\n\tisResultSeen,\n\tmarkResultSeen,\n\trecordExecutionEnded,\n\trecordExecutionStarted,\n\tstartElapsedTicker,\n\tstopElapsedTicker,\n} from \"./session-config.js\";\n\n/** Renderer context delivered by Pi's ToolExecutionComponent (getRenderContext). */\nexport interface BoxedToolContext {\n\treadonly args: Record<string, unknown>;\n\treadonly toolCallId: string;\n\treadonly invalidate: () => void;\n\treadonly state: Record<string, unknown>;\n\treadonly cwd: string;\n\treadonly executionStarted: boolean;\n\treadonly argsComplete: boolean;\n\treadonly isPartial: boolean;\n\treadonly expanded: boolean;\n\treadonly showImages: boolean;\n\treadonly isError: boolean;\n\treadonly lastComponent?: unknown;\n}\n\n/** Result view delivered to result renderers: { content, details }. */\nexport interface BoxedToolResult {\n\treadonly content?: readonly unknown[];\n\treadonly details?: unknown;\n}\n\nexport type BoxedCallRenderer = (\n\targs: Record<string, unknown>,\n\ttheme: BoxTheme,\n\tcontext: BoxedToolContext,\n) => Component;\nexport type BoxedResultRenderer = (\n\tresult: BoxedToolResult,\n\toptions: { expanded: boolean; isPartial: boolean },\n\ttheme: BoxTheme,\n\tcontext: BoxedToolContext,\n) => Component;\n\nexport interface BoxedToolDefinition {\n\treadonly call: BoxedCallRenderer;\n\treadonly result: BoxedResultRenderer;\n}\n\nexport function pendingFlag(context: BoxedToolContext): boolean {\n\treturn Boolean(context.isPartial);\n}\n\n/** Normalized display path: shortens HOME and resolves relative to the session cwd. */\nexport function displayPath(rawPath: string, context: BoxedToolContext): string {\n\tconst path = String(rawPath ?? \"\");\n\tif (!path) return \"(unknown)\";\n\treturn shortenPath(resolveRelativePath(path, context.cwd));\n}\n\nexport function pathRangeDetail(rawPath: string, offset: unknown, limit: unknown, context: BoxedToolContext): string {\n\tconst path = displayPath(rawPath, context);\n\tlet range = \"\";\n\tif (offset !== undefined || limit !== undefined) {\n\t\tconst start = offset ?? 1;\n\t\tconst end = limit !== undefined ? Number(start) + Number(limit) - 1 : \"\";\n\t\trange = `:${start}${end ? `-${end}` : \"\"}`;\n\t}\n\treturn path ? `${path}${range}` : \"(unknown)\";\n}\n\n/** Compact boxed call header for summary-style tools (read/write/ls/find/grep). */\nexport function compactCall(\n\ttheme: BoxTheme,\n\ttoolName: string,\n\tdetailLine: string,\n\toptions: { detailKey: string; context: BoxedToolContext },\n): Component {\n\treturn renderCompactBoxedToolCall(theme, toolName, detailLine, {\n\t\twidthKey: boxedToolWidthKey(toolName, options.detailKey),\n\t\tstate: options.context.state,\n\t\tisError: Boolean(options.context.isError),\n\t\tisPartial: Boolean(options.context.isPartial),\n\t\tisPending: pendingFlag(options.context),\n\t\trunning: Boolean(options.context.executionStarted),\n\t});\n}\n\n/** Record wall-clock start when execution begins (first render with executionStarted). */\nexport function noteExecutionStart(context: BoxedToolContext): void {\n\trecordExecutionStarted(context.state, context.executionStarted);\n}\n\n/**\n * Keep running/ended execution state in sync from a call renderer pass. While\n * the tool runs, a 1s re-render ticker keeps live elapsed labels current; once\n * the call renders in its terminal form the elapsed freezes.\n */\nexport function noteBoxedCallState(context: BoxedToolContext): void {\n\tif (!context.executionStarted) return;\n\tif (context.isPartial) startElapsedTicker(context.state, context.invalidate);\n\telse {\n\t\trecordExecutionEnded(context.state);\n\t\tstopElapsedTicker(context.state);\n\t}\n}\n\n/**\n * Record a result renderer pass and keep the ticker/ended state in sync.\n * Returns whether this is the first result pass for the call, so renderers can\n * render nothing while the pending/running call card stands alone.\n */\nexport function noteBoxedResultPhase(context: BoxedToolContext, isPartial: boolean): boolean {\n\tconst firstResultPass = !isResultSeen(context.state);\n\tmarkResultSeen(context.state);\n\tif (isPartial) startElapsedTicker(context.state, context.invalidate);\n\telse {\n\t\trecordExecutionEnded(context.state);\n\t\tstopElapsedTicker(context.state);\n\t}\n\treturn firstResultPass;\n}\n\nexport function stateElapsedMs(context: BoxedToolContext): number | undefined {\n\treturn getStateElapsedMs(context.state);\n}\n\n/** Footer parts with state-based elapsed when result.details lacks timing. */\nexport function boxedFooterWithState(\n\ttheme: BoxTheme,\n\tresult: BoxedToolResult | undefined,\n\tcontext: BoxedToolContext,\n\textraParts: string[] = [],\n): string {\n\treturn formatBoxedFooterFromValues(theme, stateElapsedMs(context), getTextOutput(result), extraParts);\n}\n\nexport function compactFooterWithState(\n\ttheme: BoxTheme,\n\tresult: BoxedToolResult,\n\tcontext: BoxedToolContext,\n\toptions: { isError?: boolean; isPartial?: boolean } = {},\n): Component {\n\tconst elapsedMs = stateElapsedMs(context);\n\treturn renderCompactBoxedFooter(theme, result, {\n\t\tstate: context.state,\n\t\tisError: Boolean(options.isError ?? context.isError),\n\t\tisPartial: Boolean(options.isPartial ?? context.isPartial),\n\t\t...(elapsedMs === undefined ? {} : { elapsedMs }),\n\t});\n}\n\nexport function resultFooterLines(\n\ttheme: BoxTheme,\n\tresult: BoxedToolResult,\n\tcontext: BoxedToolContext,\n\textraParts: string[] = [],\n): string[] {\n\treturn [formatBoxedFooter(theme, result, extraParts, stateElapsedMs(context))];\n}\n\nexport function clearFooterState(context: BoxedToolContext): void {\n\tclearCompactBoxedFooter(context.state);\n}\n\n/** Result-details truncation line count when the native tool truncated output. */\nexport function truncationOutputLines(result: BoxedToolResult | undefined): number | undefined {\n\tif (!result) return undefined;\n\tconst details = result.details as { truncation?: { outputLines?: number } } | undefined;\n\tconst value = details?.truncation?.outputLines;\n\treturn typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\n/** Result-details grep match-limit reached counter. */\nexport function matchLimitReached(result: BoxedToolResult | undefined): number | undefined {\n\tif (!result) return undefined;\n\tconst details = result.details as { matchLimitReached?: number } | undefined;\n\tconst value = details?.matchLimitReached;\n\treturn typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nexport { boxedToolWidthKey, getTextOutput, resolveRelativePath, shortenPath };\n","// Boxed grep/search tool renderer.\n//\n// grep renders a **boxless tree panel**: a summary header\n// (`Grep: <pattern> <N> matches · <M> files · in <path>`) followed by match rows\n// grouped by file (`├─ *line│content`). Like the quiet-tool batch panel, the\n// whole panel lives in the call component and reads a live registry on every\n// render, so the result's match data is picked up without cross-component\n// invalidation. grep does not batch (each call owns its own panel).\n//\n// Lifecycle: panels are keyed by toolCallId and cleared on session reset and new\n// message boundaries (see resetGrepRegistry wiring in session-coordinator.ts and\n// pi/index.ts), mirroring the batch registry.\n\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport { stripAnsi } from \"../../../shared/ansi.js\";\nimport { type BoxTheme, getTextOutput, shortenPath } from \"../../../shared/box.js\";\nimport { safeTruncateToWidth } from \"../../../shared/render-budget.js\";\nimport {\n\ttype GrepMatch,\n\tgroupMatchesByFile,\n\tparseGrepOutput,\n\tpluralForm,\n\trenderGrepTree,\n\tSEARCH_ICON,\n\tTREE_INDENT,\n} from \"./output-tree.js\";\nimport { getToolsRenderConfig } from \"./session-config.js\";\nimport { type BoxedToolDefinition, noteExecutionStart } from \"./shared.js\";\n\nconst GREP_HEAD_LIMIT = 6;\nconst GREP_ERROR_LINES = 2;\n\ninterface GrepPanelState {\n\tpattern: string;\n\tpathLabel: string;\n\t/** `undefined` until the result arrives; an empty array means zero matches. */\n\tmatches: GrepMatch[] | undefined;\n\tisError: boolean;\n\terrorText: string | undefined;\n\tisPartial: boolean;\n}\n\nconst grepPanels = new Map<string, GrepPanelState>();\n\n/** Reset all grep panel state (session start/shutdown). */\nexport function resetGrepRegistry(): void {\n\tgrepPanels.clear();\n}\n\nfunction pathLabel(rawPath: string): string {\n\tconst displayPath = String(rawPath ?? \".\");\n\treturn displayPath === \".\" || displayPath === \"\" ? \"current directory\" : shortenPath(displayPath);\n}\n\nfunction registerGrepCall(toolCallId: string, pattern: string, label: string): void {\n\tconst existing = grepPanels.get(toolCallId);\n\tif (existing) {\n\t\texisting.pattern = pattern;\n\t\texisting.pathLabel = label;\n\t\treturn;\n\t}\n\tgrepPanels.set(toolCallId, {\n\t\tpattern,\n\t\tpathLabel: label,\n\t\tmatches: undefined,\n\t\tisError: false,\n\t\terrorText: undefined,\n\t\tisPartial: true,\n\t});\n}\n\nfunction registerGrepResult(\n\ttoolCallId: string,\n\tdata: { matches: GrepMatch[]; isError: boolean; errorText: string | undefined; isPartial: boolean },\n): void {\n\tconst state = grepPanels.get(toolCallId);\n\tif (!state) return;\n\tstate.matches = data.matches;\n\tstate.isError = data.isError;\n\tstate.errorText = data.errorText;\n\tstate.isPartial = data.isPartial;\n}\n\nfunction bold(theme: BoxTheme, text: string): string {\n\treturn typeof theme?.bold === \"function\" ? theme.bold(text) : text;\n}\n\n/** `Grep: <pattern> <N> matches · <M> files · in <path>` (done) /\n * `Grep: <pattern> · in <path>` (pending). */\nfunction formatGrepHeader(theme: BoxTheme, state: GrepPanelState): string {\n\tconst icon = getToolsRenderConfig().nerdFonts ? `${SEARCH_ICON} ` : \"\";\n\tconst label = bold(theme, \"Grep:\");\n\tconst patternPart = state.pattern ? ` ${theme.fg(\"text\", state.pattern)}` : \"\";\n\tconst pathPart = state.pathLabel ? theme.fg(\"dim\", ` · in ${state.pathLabel}`) : \"\";\n\tif (state.isError) {\n\t\treturn `${icon}${theme.fg(\"error\", bold(theme, \"✗ Grep:\"))}${state.pattern ? ` ${theme.fg(\"error\", state.pattern)}` : \"\"}${pathPart}`;\n\t}\n\tif (state.matches === undefined) {\n\t\treturn `${icon}${label}${patternPart}${pathPart}`;\n\t}\n\tconst matchCount = state.matches.length;\n\tconst fileCount = groupMatchesByFile(state.matches).length;\n\tconst matchesPart = theme.fg(\"accent\", `${matchCount} ${pluralForm(\"match\", matchCount)}`);\n\tconst filesPart = theme.fg(\"dim\", ` · ${fileCount} ${pluralForm(\"file\", fileCount)}`);\n\treturn `${icon}${label}${patternPart} ${matchesPart}${filesPart}${pathPart}`;\n}\n\nfunction renderErrorLines(theme: BoxTheme, errorText: string, width: number): string[] {\n\tconst raw = stripAnsi(errorText)\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trim())\n\t\t.filter((line) => line.length > 0);\n\tif (raw.length === 0) return [];\n\tconst prefix = `${TREE_INDENT}${theme.fg(\"borderMuted\", \"└─\")} `;\n\tconst out = raw\n\t\t.slice(0, GREP_ERROR_LINES)\n\t\t.map((line) => safeTruncateToWidth(`${prefix}${theme.fg(\"error\", line)}`, Math.max(1, width), \"…\"));\n\tif (raw.length > GREP_ERROR_LINES)\n\t\tout.push(safeTruncateToWidth(`${prefix}${theme.fg(\"error\", \"…\")}`, Math.max(1, width), \"…\"));\n\treturn out;\n}\n\nfunction renderGrepPanelLines(theme: BoxTheme, state: GrepPanelState, width: number): string[] {\n\tconst safeWidth = Math.max(1, width);\n\tconst header = safeTruncateToWidth(formatGrepHeader(theme, state), safeWidth, \"…\");\n\tif (state.isError) {\n\t\treturn [header, ...(state.errorText ? renderErrorLines(theme, state.errorText, width) : [])];\n\t}\n\tif (state.matches === undefined) return [header];\n\treturn renderGrepTree(theme, header, state.matches, safeWidth, {\n\t\theadLimit: GREP_HEAD_LIMIT,\n\t\twithIcons: getToolsRenderConfig().nerdFonts,\n\t});\n}\n\n/** Live panel component reading the registry on every render pass. The state\n * reference is captured at creation (like the batch panel): a registry clear\n * on session reset/resume must not blank already-rendered panels — the result\n * renderer mutates this same object, so live updates still flow. */\nfunction renderGrepPanel(theme: BoxTheme, toolCallId: string): Component {\n\tconst state = grepPanels.get(toolCallId);\n\treturn {\n\t\tinvalidate() {},\n\t\trender(width: number): string[] {\n\t\t\tif (!state) return [safeTruncateToWidth(bold(theme, \"Grep:\"), Math.max(1, width), \"…\")];\n\t\t\treturn renderGrepPanelLines(theme, state, width);\n\t\t},\n\t};\n}\n\n/** Empty result component — the panel lives in the call component, which\n * re-renders when the result arrives (Pi re-renders the tool execution\n * component on tool_execution_end), picking up the stored matches. */\nconst EMPTY_GREP_RESULT: Component = {\n\tinvalidate() {},\n\trender() {\n\t\treturn [];\n\t},\n};\n\nexport const grepTool: BoxedToolDefinition = {\n\tcall(args, theme, context) {\n\t\tnoteExecutionStart(context);\n\t\tconst pattern = String(args?.pattern ?? \"\");\n\t\tregisterGrepCall(context.toolCallId, pattern, pathLabel(String(args?.path ?? \".\")));\n\t\treturn renderGrepPanel(theme, context.toolCallId);\n\t},\n\tresult(result, options, _theme, context) {\n\t\tconst output = stripAnsi(getTextOutput(result)).trimEnd();\n\t\tconst isError = Boolean(context.isError);\n\t\tconst matches = isError ? [] : parseGrepOutput(output);\n\t\tregisterGrepResult(context.toolCallId, {\n\t\t\tmatches,\n\t\t\tisError,\n\t\t\terrorText: isError ? output || undefined : undefined,\n\t\t\tisPartial: Boolean(options.isPartial),\n\t\t});\n\t\treturn EMPTY_GREP_RESULT;\n\t},\n};\n","import type { NormalizedPiStyleConfig } from \"./config-types.js\";\n\nexport interface TierCAuthorizationInput {\n\treadonly certifiedHost: boolean;\n\treadonly coreFlag: boolean;\n\treadonly surfaceFlag: boolean;\n\treadonly surface: \"messages\" | \"tools\" | \"assistantMessage\" | \"specialBlocks\";\n\treadonly config: NormalizedPiStyleConfig;\n}\n\n/** Persisted and ordinary command state is intentionally not an input: authorization is session-bound. */\nexport function isTierCAuthorized(input: TierCAuthorizationInput): boolean {\n\tif (!input.certifiedHost || !input.coreFlag || !input.surfaceFlag || !input.config.enabled) return false;\n\tif (input.surface === \"tools\") return input.config.tools.enabled;\n\tif (input.surface === \"assistantMessage\")\n\t\treturn input.config.messages.enabled && input.config.messages.assistantPrefix;\n\tif (input.surface === \"specialBlocks\") return input.config.messages.enabled && input.config.messages.specialBlocks;\n\treturn input.config.messages.enabled;\n}\n","import { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n\tAssistantMessageComponent,\n\tBranchSummaryMessageComponent,\n\tCompactionSummaryMessageComponent,\n\tCustomMessageComponent,\n\tSkillInvocationMessageComponent,\n\tToolExecutionComponent,\n} from \"@earendil-works/pi-coding-agent\";\nimport { decorateMessageRender, type MessageDecorationSnapshot } from \"../features/messages/index.js\";\nimport { renderSpecialMessageBlock, type SpecialBlockSubtype } from \"../features/messages/special-blocks.js\";\nimport { createToolDecorationOwner } from \"../features/tools/index.js\";\nimport {\n\ttype CompatibilityRecord,\n\tcurrentGeneration,\n\tinstallDelegatingPatch,\n\tnextGeneration,\n} from \"./compatibility-registry.js\";\n\nconst PI_VERSION_RANGE = \">=0.83.0 <0.84.0\";\nconst TRUSTED_PI_VERSION = \"0.83.0\";\nconst reportStates = new WeakMap<\n\tobject,\n\t{ records: CompatibilityRecord[]; toolOwner: ReturnType<typeof createToolDecorationOwner> | undefined }\n>();\n// These fingerprints are coupled to the installed 0.83.0 package source. A matching\n// name/arity/hash is evidence of the shipped native method, not a cryptographic proof:\n// code loaded before this module could spoof the same function source. We therefore\n// fail closed on every unrecorded Pi build and never use module-load capture as trust.\nexport const TRUSTED_NATIVE_FINGERPRINTS: Readonly<Record<string, string>> = Object.freeze({\n\t\"native-assistant-message:render\": \"2a39243f\",\n\t\"native-compaction-message:updateDisplay\": \"f8c44e78\",\n\t\"native-branch-message:updateDisplay\": \"415d57b7\",\n\t\"native-skill-message:updateDisplay\": \"48099ea6\",\n\t\"native-custom-message:rebuild\": \"76ae2e3a\",\n\t\"tool-call-renderer:getCallRenderer\": \"951ea0e0\",\n\t\"tool-result-renderer:getResultRenderer\": \"8a25cd71\",\n});\n\nexport const CERTIFICATION_TABLE = Object.freeze({\n\t\"0.83.0\": Object.freeze({\n\t\t\"native-assistant-message:render\": Object.freeze({\n\t\t\tfeature: \"messages\",\n\t\t\tsubtype: \"native-assistant-message\",\n\t\t\ttarget: AssistantMessageComponent.prototype,\n\t\t\tmethod: \"render\",\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t\tname: \"render\",\n\t\t\tarity: 1,\n\t\t\tfingerprint: TRUSTED_NATIVE_FINGERPRINTS[\"native-assistant-message:render\"],\n\t\t\tadapterId: \"message-prefix-osc133-v1\",\n\t\t\tstatus: \"certified\" as const,\n\t\t}),\n\t\t\"tool-call-renderer:getCallRenderer\": Object.freeze({\n\t\t\tfeature: \"tools\",\n\t\t\tsubtype: \"tool-call-renderer\",\n\t\t\ttarget: ToolExecutionComponent.prototype,\n\t\t\tmethod: \"getCallRenderer\",\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t\tname: \"getCallRenderer\",\n\t\t\tarity: 0,\n\t\t\tfingerprint: TRUSTED_NATIVE_FINGERPRINTS[\"tool-call-renderer:getCallRenderer\"],\n\t\t\tadapterId: \"tool-renderer-component-v1\",\n\t\t\tstatus: \"certified\" as const,\n\t\t}),\n\t\t\"tool-result-renderer:getResultRenderer\": Object.freeze({\n\t\t\tfeature: \"tools\",\n\t\t\tsubtype: \"tool-result-renderer\",\n\t\t\ttarget: ToolExecutionComponent.prototype,\n\t\t\tmethod: \"getResultRenderer\",\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t\tname: \"getResultRenderer\",\n\t\t\tarity: 0,\n\t\t\tfingerprint: TRUSTED_NATIVE_FINGERPRINTS[\"tool-result-renderer:getResultRenderer\"],\n\t\t\tadapterId: \"tool-renderer-component-v1\",\n\t\t\tstatus: \"certified\" as const,\n\t\t}),\n\t\t\"native-compaction-message:updateDisplay\": Object.freeze({\n\t\t\tfeature: \"messages\",\n\t\t\tsubtype: \"native-compaction-message\",\n\t\t\ttarget: CompactionSummaryMessageComponent.prototype,\n\t\t\tmethod: \"updateDisplay\",\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t\tadapterId: \"message-block-boxed-v1\",\n\t\t\tstatus: \"certified\" as const,\n\t\t}),\n\t\t\"native-branch-message:updateDisplay\": Object.freeze({\n\t\t\tfeature: \"messages\",\n\t\t\tsubtype: \"native-branch-message\",\n\t\t\ttarget: BranchSummaryMessageComponent.prototype,\n\t\t\tmethod: \"updateDisplay\",\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t\tadapterId: \"message-block-boxed-v1\",\n\t\t\tstatus: \"certified\" as const,\n\t\t}),\n\t\t\"native-skill-message:updateDisplay\": Object.freeze({\n\t\t\tfeature: \"messages\",\n\t\t\tsubtype: \"native-skill-message\",\n\t\t\ttarget: SkillInvocationMessageComponent.prototype,\n\t\t\tmethod: \"updateDisplay\",\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t\tadapterId: \"message-block-boxed-v1\",\n\t\t\tstatus: \"certified\" as const,\n\t\t}),\n\t\t\"native-custom-message:rebuild\": Object.freeze({\n\t\t\tfeature: \"messages\",\n\t\t\tsubtype: \"native-custom-message\",\n\t\t\ttarget: CustomMessageComponent.prototype,\n\t\t\tmethod: \"rebuild\",\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t\tadapterId: \"message-block-boxed-v1\",\n\t\t\tstatus: \"certified\" as const,\n\t\t}),\n\t}),\n});\n\nexport interface CompatibilityDescriptorSnapshot {\n\treadonly kind: \"data\" | \"accessor\";\n\treadonly value?: unknown;\n\treadonly get?: unknown;\n\treadonly set?: unknown;\n\treadonly writable?: boolean;\n\treadonly enumerable: boolean;\n\treadonly configurable: boolean;\n}\n\nexport interface CompatibilityRecordSnapshot {\n\treadonly feature: CompatibilityRecord[\"feature\"];\n\treadonly subtype: CompatibilityRecord[\"subtype\"];\n\treadonly method: PropertyKey;\n\treadonly shape: string;\n\treadonly piVersion: string;\n\treadonly versionRange: string;\n\treadonly generation: number;\n\treadonly disposed: boolean;\n\treadonly diagnostic: string | undefined;\n}\n\nexport interface CompatibilityProbeReport {\n\tattemptedVersion: string;\n\tmatchedCertifiedVersion: string | undefined;\n\tcertificationTable: typeof CERTIFICATION_TABLE;\n\tpiVersion: string;\n\tversionRange: string;\n\tgeneration: number;\n\trecordSnapshots: readonly CompatibilityRecordSnapshot[];\n\tunsupported: ReadonlyArray<{ subtype: string; method: PropertyKey; reason: string }>;\n\tdelegationMarkers: readonly string[];\n\tcertification: readonly {\n\t\treadonly version: string;\n\t\treadonly attemptedVersion: string;\n\t\treadonly matchedCertifiedVersion: string | undefined;\n\t\treadonly expected: unknown;\n\t\treadonly actualPreinstall: CompatibilityDescriptorSnapshot | undefined;\n\t\treadonly feature: CompatibilityRecord[\"feature\"];\n\t\treadonly subtype: CompatibilityRecord[\"subtype\"];\n\t\treadonly target: object;\n\t\treadonly method: string;\n\t\treadonly descriptor: CompatibilityDescriptorSnapshot | undefined;\n\t\treadonly name: string | undefined;\n\t\treadonly arity: number | undefined;\n\t\treadonly fingerprint: string | undefined;\n\t\treadonly adapterId: string | undefined;\n\t\treadonly status: \"certified\" | \"native-fallback\";\n\t\treadonly fallbackReason?: string;\n\t}[];\n\tgetRuntimeDiagnostics: () => ReadonlyMap<string, number>;\n\tgetFinalDiagnostics: () => Readonly<import(\"../features/tools/index.js\").ToolDiagnosticArchive> | undefined;\n\tgetActiveToolRecordCount: () => number;\n\tdisposeOwner: () => void;\n}\n\nexport interface TargetSpec {\n\tfeature: CompatibilityRecord[\"feature\"];\n\tsubtype: CompatibilityRecord[\"subtype\"];\n\ttarget: object;\n\tmethod: string;\n\tadapterId: string | undefined;\n\tstatus: \"certified\" | \"native-fallback\";\n\tfallbackReason?: string;\n}\n\nexport function fingerprint(value: unknown): string | undefined {\n\tif (typeof value !== \"function\") return undefined;\n\tlet hash = 2166136261;\n\tfor (const character of Function.prototype.toString.call(value)) {\n\t\thash ^= character.charCodeAt(0);\n\t\thash = Math.imul(hash, 16777619) >>> 0;\n\t}\n\treturn hash.toString(16).padStart(8, \"0\");\n}\n\nfunction trustedNativeIdentity(spec: TargetSpec, piVersion: string | undefined): unknown {\n\tif (piVersion !== TRUSTED_PI_VERSION) return undefined;\n\tconst descriptor = Object.getOwnPropertyDescriptor(spec.target, spec.method);\n\tconst value = descriptor?.value;\n\tconst key = `${spec.subtype}:${spec.method}`;\n\tif (\n\t\tdescriptor?.writable !== true ||\n\t\tdescriptor.configurable !== true ||\n\t\ttypeof value !== \"function\" ||\n\t\tvalue.name !== spec.method ||\n\t\tvalue.length !== (spec.method === \"render\" ? 1 : 0) ||\n\t\tfingerprint(value) !== TRUSTED_NATIVE_FINGERPRINTS[key]\n\t)\n\t\treturn undefined;\n\treturn value;\n}\n\nexport const targetSpecs: readonly TargetSpec[] = [\n\t{\n\t\tfeature: \"messages\",\n\t\tsubtype: \"native-assistant-message\",\n\t\ttarget: AssistantMessageComponent.prototype,\n\t\tmethod: \"render\",\n\t\tadapterId: \"message-prefix-osc133-v1\",\n\t\tstatus: \"certified\",\n\t},\n\t{\n\t\tfeature: \"messages\",\n\t\tsubtype: \"native-compaction-message\",\n\t\ttarget: CompactionSummaryMessageComponent.prototype,\n\t\tmethod: \"updateDisplay\",\n\t\tadapterId: \"message-block-boxed-v1\",\n\t\tstatus: \"certified\",\n\t},\n\t{\n\t\tfeature: \"messages\",\n\t\tsubtype: \"native-branch-message\",\n\t\ttarget: BranchSummaryMessageComponent.prototype,\n\t\tmethod: \"updateDisplay\",\n\t\tadapterId: \"message-block-boxed-v1\",\n\t\tstatus: \"certified\",\n\t},\n\t{\n\t\tfeature: \"messages\",\n\t\tsubtype: \"native-skill-message\",\n\t\ttarget: SkillInvocationMessageComponent.prototype,\n\t\tmethod: \"updateDisplay\",\n\t\tadapterId: \"message-block-boxed-v1\",\n\t\tstatus: \"certified\",\n\t},\n\t{\n\t\tfeature: \"messages\",\n\t\tsubtype: \"native-custom-message\",\n\t\ttarget: CustomMessageComponent.prototype,\n\t\tmethod: \"rebuild\",\n\t\tadapterId: \"message-block-boxed-v1\",\n\t\tstatus: \"certified\",\n\t},\n\t{\n\t\tfeature: \"tools\",\n\t\tsubtype: \"tool-call-renderer\",\n\t\ttarget: ToolExecutionComponent.prototype,\n\t\tmethod: \"getCallRenderer\",\n\t\tadapterId: \"tool-renderer-component-v1\",\n\t\tstatus: \"certified\",\n\t},\n\t{\n\t\tfeature: \"tools\",\n\t\tsubtype: \"tool-result-renderer\",\n\t\ttarget: ToolExecutionComponent.prototype,\n\t\tmethod: \"getResultRenderer\",\n\t\tadapterId: \"tool-renderer-component-v1\",\n\t\tstatus: \"certified\",\n\t},\n];\n\nexport interface PiVersionResolution {\n\tresolvePackageEntry?: (packageName: string) => string;\n\treadFile?: (path: string) => string;\n}\n\nexport function detectPiVersion(resolution: PiVersionResolution = {}): {\n\tversion: string | undefined;\n\tdiagnostic?: string;\n} {\n\tconst resolvePackageEntry =\n\t\tresolution.resolvePackageEntry ??\n\t\t((name: string) => {\n\t\t\ttry {\n\t\t\t\treturn fileURLToPath(new URL(import.meta.resolve(name)));\n\t\t\t} catch (error) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`public package entry resolution failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\tconst readFile = resolution.readFile ?? ((path: string) => readFileSync(path, \"utf8\"));\n\ttry {\n\t\tconst entry = resolvePackageEntry(\"@earendil-works/pi-coding-agent\");\n\t\tlet directory = dirname(entry);\n\t\tfor (;;) {\n\t\t\tconst packagePath = join(directory, \"package.json\");\n\t\t\ttry {\n\t\t\t\tconst packageJson = JSON.parse(readFile(packagePath)) as { name?: string; version?: string };\n\t\t\t\tif (packageJson.name === \"@earendil-works/pi-coding-agent\" && typeof packageJson.version === \"string\")\n\t\t\t\t\treturn { version: packageJson.version };\n\t\t\t} catch {\n\t\t\t\t// Walk upward only; package exports may place the entry below the package root.\n\t\t\t}\n\t\t\tconst parent = dirname(directory);\n\t\t\tif (parent === directory) break;\n\t\t\tdirectory = parent;\n\t\t}\n\t\treturn { version: undefined, diagnostic: \"Pi package version was not found\" };\n\t} catch (error) {\n\t\treturn {\n\t\t\tversion: undefined,\n\t\t\tdiagnostic: `Pi package version detection failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t};\n\t}\n}\n\nfunction descriptorSnapshot(descriptor: PropertyDescriptor | undefined): CompatibilityDescriptorSnapshot | undefined {\n\tif (!descriptor) return undefined;\n\treturn Object.freeze(\n\t\t\"value\" in descriptor\n\t\t\t? {\n\t\t\t\t\tkind: \"data\",\n\t\t\t\t\tvalue: descriptor.value,\n\t\t\t\t\twritable: descriptor.writable === true,\n\t\t\t\t\tenumerable: descriptor.enumerable === true,\n\t\t\t\t\tconfigurable: descriptor.configurable === true,\n\t\t\t\t}\n\t\t\t: {\n\t\t\t\t\tkind: \"accessor\",\n\t\t\t\t\tget: descriptor.get,\n\t\t\t\t\tset: descriptor.set,\n\t\t\t\t\tenumerable: descriptor.enumerable === true,\n\t\t\t\t\tconfigurable: descriptor.configurable === true,\n\t\t\t\t},\n\t);\n}\n\nfunction certificationRecord(\n\tspec: TargetSpec,\n\tattemptedVersion: string | undefined,\n\tevidence = Object.getOwnPropertyDescriptor(spec.target, spec.method),\n) {\n\tconst descriptor = evidence;\n\tconst value = descriptor?.value;\n\treturn {\n\t\tversion: attemptedVersion ?? \"unknown\",\n\t\tattemptedVersion: attemptedVersion ?? \"unknown\",\n\t\tmatchedCertifiedVersion: attemptedVersion === TRUSTED_PI_VERSION ? TRUSTED_PI_VERSION : undefined,\n\t\texpected: undefined,\n\t\tactualPreinstall: descriptorSnapshot(descriptor),\n\t\tfeature: spec.feature,\n\t\tsubtype: spec.subtype,\n\t\ttarget: spec.target,\n\t\tmethod: spec.method,\n\t\tdescriptor: descriptorSnapshot(descriptor),\n\t\tname: typeof value === \"function\" ? value.name : undefined,\n\t\tarity: typeof value === \"function\" ? value.length : undefined,\n\t\tfingerprint: fingerprint(value),\n\t\tadapterId: spec.adapterId,\n\t\tstatus: spec.status,\n\t\t...(spec.fallbackReason ? { fallbackReason: spec.fallbackReason } : {}),\n\t};\n}\n\nfunction versionInRange(version: string | undefined): boolean {\n\treturn version === TRUSTED_PI_VERSION;\n}\n\nfunction shape(target: object, method: string): boolean {\n\tconst descriptor = Object.getOwnPropertyDescriptor(target, method);\n\treturn typeof descriptor?.value === \"function\" && descriptor.writable === true && descriptor.configurable === true;\n}\n\nexport interface CompatibilityProbeOptions {\n\tmarkers?: Set<string>;\n\tconfig?: Readonly<{\n\t\tmessages: { enabled: boolean; assistantPrefix: boolean; specialBlocks: boolean };\n\t\ttools: { enabled: boolean; style: string; maxCollapsedLines: number; maxExpandedLines: number; dimOutput: boolean };\n\t\tpreset: string;\n\t}>;\n\ttoolSnapshot?: Readonly<{ callMarker?: string; resultMarker?: string; style?: \"marker\" | \"compact-box\" }>;\n\tmessageSnapshot?: MessageDecorationSnapshot;\n}\n\nfunction isSpecialBlock(spec: TargetSpec): boolean {\n\treturn spec.feature === \"messages\" && spec.status === \"certified\" && spec.adapterId === \"message-block-boxed-v1\";\n}\n\nfunction createFallbackRecord(\n\tspec: TargetSpec,\n\tpiVersion: string | undefined,\n\tgeneration: number,\n\treason: string,\n): CompatibilityRecord {\n\treturn {\n\t\tfeature: spec.feature,\n\t\tsubtype: spec.subtype,\n\t\ttarget: spec.target,\n\t\towner: spec.target,\n\t\tmethod: spec.method,\n\t\toriginalIdentity: Reflect.get(spec.target, spec.method),\n\t\tpiVersion: piVersion ?? \"unknown\",\n\t\tversionRange: PI_VERSION_RANGE,\n\t\tshape: \"unsupported\",\n\t\tdiagnostic: reason,\n\t\tgeneration,\n\t\tdisposed: true,\n\t\tdisposer: () => {},\n\t};\n}\n\nfunction probeDiagnostic(spec: TargetSpec, piVersion: string | undefined, identity: unknown): string {\n\tif (!versionInRange(piVersion)) return \"Pi version is unknown or outside the recorded 0.83.0 support build\";\n\tif (!shape(spec.target, spec.method)) return \"target method shape is not an own writable/configurable function\";\n\tif (identity === undefined) return \"recorded 0.83.0 native fingerprint, name, or arity did not match\";\n\treturn \"exact native identity verified; certified guarded decoration enabled\";\n}\n\nfunction surfaceDisabled(spec: TargetSpec, config: CompatibilityProbeOptions[\"config\"]): boolean {\n\tif (!config) return false;\n\tif (spec.feature === \"tools\") return !config.tools.enabled;\n\tif (!config.messages.enabled) return true;\n\tif (spec.subtype === \"native-assistant-message\") return !config.messages.assistantPrefix;\n\tif (isSpecialBlock(spec)) return !config.messages.specialBlocks;\n\treturn true;\n}\n\nfunction probeSpec(options: {\n\tspec: TargetSpec;\n\tpiVersion: string | undefined;\n\tgeneration: number;\n\tmarkers: Set<string>;\n\tconfig?: CompatibilityProbeOptions[\"config\"];\n\tmessageSnapshot: MessageDecorationSnapshot | undefined;\n\ttoolOwner: ReturnType<typeof createToolDecorationOwner> | undefined;\n}) {\n\tconst { spec, piVersion, generation, markers, config, toolOwner, messageSnapshot } = options;\n\tconst identity = trustedNativeIdentity(spec, piVersion);\n\tconst diagnostic = probeDiagnostic(spec, piVersion, identity);\n\tconst disabled = surfaceDisabled(spec, config);\n\tif (disabled) {\n\t\tconst reason = \"native fallback: surface disabled by normalized configuration\";\n\t\treturn { record: createFallbackRecord(spec, piVersion, generation, reason), reason, fallback: true };\n\t}\n\tconst result = installDelegatingPatch({\n\t\tfeature: spec.feature,\n\t\tsubtype: spec.subtype,\n\t\ttarget: spec.target,\n\t\tmethod: spec.method,\n\t\tpiVersion: piVersion ?? \"unknown\",\n\t\tversionRange: PI_VERSION_RANGE,\n\t\tshape: identity !== undefined && versionInRange(piVersion) && shape(spec.target, spec.method),\n\t\tgeneration,\n\t\texpectedIdentity: identity,\n\t\thasExpectedIdentity: true,\n\t\tdiagnostic,\n\t\tdelegate: (original, target, args) => {\n\t\t\tmarkers.add(`${spec.subtype}:delegated`);\n\t\t\tif (spec.feature === \"tools\")\n\t\t\t\treturn (\n\t\t\t\t\ttoolOwner?.decorateToolRendererSelection(\n\t\t\t\t\t\tspec.subtype as \"tool-call-renderer\" | \"tool-result-renderer\",\n\t\t\t\t\t\toriginal,\n\t\t\t\t\t\ttarget,\n\t\t\t\t\t\targs,\n\t\t\t\t\t) ?? Reflect.apply(original as (...values: unknown[]) => unknown, target, args)\n\t\t\t\t);\n\t\t\tif (spec.subtype === \"native-assistant-message\")\n\t\t\t\treturn decorateMessageRender(original, target, args, messageSnapshot);\n\t\t\treturn renderSpecialMessageBlock(spec.subtype as SpecialBlockSubtype, original, target, args);\n\t\t},\n\t});\n\treturn {\n\t\trecord: result.record,\n\t\treason: result.reason ?? result.record.diagnostic ?? \"skipped\",\n\t\tfallback: result.status === \"skipped\",\n\t};\n}\n\nexport function probePiCompatibility(\n\tpiVersion: string | undefined,\n\toptions: Set<string> | CompatibilityProbeOptions = new Set(),\n): CompatibilityProbeReport {\n\tconst markers = options instanceof Set ? options : (options.markers ?? new Set<string>());\n\tconst generation = nextGeneration();\n\tconst toolSpecs = targetSpecs.filter((spec) => spec.feature === \"tools\");\n\tlet toolOwner: ReturnType<typeof createToolDecorationOwner> | undefined;\n\tif (\n\t\ttoolSpecs.some((spec) => trustedNativeIdentity(spec, piVersion) !== undefined) &&\n\t\t(options instanceof Set || options.config?.tools.enabled !== false)\n\t) {\n\t\ttoolOwner = createToolDecorationOwner(options instanceof Set ? {} : options.toolSnapshot);\n\t}\n\tconst evidence = Object.freeze(\n\t\ttargetSpecs.map((spec) =>\n\t\t\tObject.freeze({\n\t\t\t\tsubtype: spec.subtype,\n\t\t\t\tmethod: spec.method,\n\t\t\t\ttarget: spec.target,\n\t\t\t\tdescriptor: Object.getOwnPropertyDescriptor(spec.target, spec.method),\n\t\t\t\tvalue: Object.getOwnPropertyDescriptor(spec.target, spec.method)?.value,\n\t\t\t}),\n\t\t),\n\t);\n\tconst evidenceByKey = new Map(evidence.map((item) => [`${item.subtype}:${String(item.method)}`, item]));\n\tconst records: CompatibilityRecord[] = [];\n\tconst unsupported: Array<{ subtype: string; method: PropertyKey; reason: string }> = [];\n\tconst certification: NonNullable<CompatibilityProbeReport[\"certification\"]>[number][] = [];\n\tfor (const spec of targetSpecs) {\n\t\tconst captured = evidenceByKey.get(`${spec.subtype}:${String(spec.method)}`);\n\t\tconst preinstallDescriptor = captured?.descriptor;\n\t\tconst result = probeSpec({\n\t\t\tmessageSnapshot: options instanceof Set ? undefined : options.messageSnapshot,\n\t\t\tspec,\n\t\t\tpiVersion,\n\t\t\tgeneration,\n\t\t\tmarkers,\n\t\t\tconfig: options instanceof Set ? undefined : options.config,\n\t\t\ttoolOwner,\n\t\t});\n\t\trecords.push(result.record);\n\t\tconst certificate = certificationRecord(spec, piVersion, preinstallDescriptor);\n\t\tcertification.push({\n\t\t\t...certificate,\n\t\t\tattemptedVersion: piVersion ?? \"unknown\",\n\t\t\tmatchedCertifiedVersion: piVersion === TRUSTED_PI_VERSION ? TRUSTED_PI_VERSION : undefined,\n\t\t\texpected:\n\t\t\t\tCERTIFICATION_TABLE[TRUSTED_PI_VERSION][\n\t\t\t\t\t`${spec.subtype}:${spec.method}` as keyof (typeof CERTIFICATION_TABLE)[\"0.83.0\"]\n\t\t\t\t],\n\t\t\tactualPreinstall: descriptorSnapshot(preinstallDescriptor),\n\t\t\tstatus: result.fallback ? \"native-fallback\" : \"certified\",\n\t\t\t...(result.fallback ? { fallbackReason: result.reason } : {}),\n\t\t});\n\t\tif (result.fallback) unsupported.push({ subtype: spec.subtype, method: spec.method, reason: result.reason });\n\t}\n\tconst report: CompatibilityProbeReport = {\n\t\tattemptedVersion: piVersion ?? \"unknown\",\n\t\tmatchedCertifiedVersion: piVersion === TRUSTED_PI_VERSION ? TRUSTED_PI_VERSION : undefined,\n\t\tcertificationTable: CERTIFICATION_TABLE,\n\t\tpiVersion: piVersion ?? \"unknown\",\n\t\tversionRange: PI_VERSION_RANGE,\n\t\tgeneration: currentGeneration(),\n\t\trecordSnapshots: Object.freeze(\n\t\t\trecords.map((record) =>\n\t\t\t\tObject.freeze({\n\t\t\t\t\tfeature: record.feature,\n\t\t\t\t\tsubtype: record.subtype,\n\t\t\t\t\tmethod: record.method,\n\t\t\t\t\tshape: record.shape,\n\t\t\t\t\tpiVersion: record.piVersion,\n\t\t\t\t\tversionRange: record.versionRange,\n\t\t\t\t\tgeneration: record.generation,\n\t\t\t\t\tdisposed: record.disposed,\n\t\t\t\t\tdiagnostic: record.diagnostic,\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\t\tunsupported: Object.freeze(unsupported.map((item) => Object.freeze({ ...item }))),\n\t\tdelegationMarkers: Object.freeze([...markers]),\n\t\tcertification: Object.freeze(\n\t\t\tcertification.map((item) =>\n\t\t\t\tObject.freeze({\n\t\t\t\t\t...item,\n\t\t\t\t\tactualPreinstall: item.actualPreinstall,\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\t\tgetRuntimeDiagnostics: () => toolOwner?.getDiagnostics() ?? new Map(),\n\t\tgetFinalDiagnostics: () => toolOwner?.getFinalArchive(),\n\t\tgetActiveToolRecordCount: () => toolOwner?.getActiveRecordCount() ?? 0,\n\t\tdisposeOwner: () => {\n\t\t\ttoolOwner?.dispose();\n\t\t},\n\t};\n\tObject.freeze(report);\n\treportStates.set(report, { records, toolOwner });\n\treturn report;\n}\n\nexport type CompatibilityCleanupResult = Readonly<{\n\tcomplete: boolean;\n\tretryablePrototypeRecords: number;\n\tretryableToolRecords: number;\n\tfinalDiagnostics?: Readonly<import(\"../features/tools/index.js\").ToolDiagnosticArchive>;\n}>;\n\nexport function disposePiCompatibilityProbe(report: CompatibilityProbeReport): CompatibilityCleanupResult {\n\tconst state = reportStates.get(report);\n\tif (!state) return { complete: true, retryablePrototypeRecords: 0, retryableToolRecords: 0 };\n\tfor (const record of state.records) record.disposer();\n\treport.disposeOwner();\n\tconst retryablePrototypeRecords = state.records.filter((record) => !record.disposed).length;\n\tconst finalDiagnostics = report.getFinalDiagnostics();\n\tconst retryableToolRecords = report.getActiveToolRecordCount();\n\tconst toolOwnerWasCreated = report.recordSnapshots.some(\n\t\t(record) => record.feature === \"tools\" && record.shape === \"installed\",\n\t);\n\treturn {\n\t\tcomplete:\n\t\t\tretryablePrototypeRecords === 0 &&\n\t\t\tretryableToolRecords === 0 &&\n\t\t\t(!toolOwnerWasCreated || finalDiagnostics !== undefined),\n\t\tretryablePrototypeRecords,\n\t\tretryableToolRecords,\n\t\t...(finalDiagnostics ? { finalDiagnostics } : {}),\n\t};\n}\n","import { visibleWidth } from \"@earendil-works/pi-tui\";\n\nconst OSC133_ZONE_START = \"\\x1b]133;A\\x07\";\nconst OSC133_ZONE_END = \"\\x1b]133;B\\x07\";\nconst OSC133_ZONE_FINAL = \"\\x1b]133;C\\x07\";\ntype OscParts = { start: string; body: string; end: string };\n\nfunction extractOscEnvelope(line: string): OscParts | undefined {\n\tif (!line.startsWith(OSC133_ZONE_START)) return undefined;\n\tconst bodyEnd = line.indexOf(OSC133_ZONE_END, OSC133_ZONE_START.length);\n\tif (bodyEnd < 0 || !line.endsWith(OSC133_ZONE_FINAL)) return undefined;\n\treturn { start: OSC133_ZONE_START, body: line.slice(OSC133_ZONE_START.length, bodyEnd), end: line.slice(bodyEnd) };\n}\n\nconst BG_RESET = \"\\x1b[49m\";\n\n/** Leading zero-width OSC sequences (e.g. OSC133 markers) of a line. */\nfunction splitLeadingMarkers(line: string): { head: string; rest: string } {\n\tlet index = 0;\n\twhile (line.startsWith(\"\\x1b]\", index)) {\n\t\tconst bel = line.indexOf(\"\\x07\", index + 2);\n\t\tconst st = line.indexOf(\"\\x1b\\\\\", index + 2);\n\t\tconst end = bel === -1 ? st : st === -1 ? bel : Math.min(bel, st);\n\t\tif (end === -1) break;\n\t\tindex = end + 1;\n\t}\n\treturn { head: line.slice(0, index), rest: line.slice(index) };\n}\n\n/** Leading SGR escape sequence of a line (\"\" when none). */\nfunction leadingSgr(line: string): string {\n\tif (!line.startsWith(\"\\x1b[\")) return \"\";\n\tlet index = 2;\n\twhile (index < line.length) {\n\t\tconst code = line.charCodeAt(index);\n\t\tif (code >= 64 && code <= 126) return line.slice(0, index + 1);\n\t\tindex++;\n\t}\n\treturn \"\";\n}\n\n/** Whether an SGR sequence sets/resets the terminal background color. */\nfunction isBackgroundSgr(sequence: string): boolean {\n\tif (!sequence.startsWith(\"\\x1b[\") || !sequence.endsWith(\"m\")) return false;\n\tfor (const code of sequence.slice(2, -1).split(\";\")) {\n\t\tconst value = Number(code);\n\t\tif (value === 48 || value === 49) return true;\n\t\tif (value >= 40 && value <= 47) return true;\n\t\tif (value >= 100 && value <= 107) return true;\n\t}\n\treturn false;\n}\n\n/**\n * Rebuild a native line so `lead` (prompt prefix / continuation indent) and the\n * full target width are covered by the line's background.\n *\n * Native Box lines (user messages) are `bgAnsi + body + \\x1b[49m`; prepending the\n * prefix outside that wrap shifted the input row's background right by the\n * prefix width while keeping the full container width, producing a staircase\n * box (indented left, overflowing right). Rebuilding inside the wrap keeps the\n * background flush across every row; plain (unwrapped) lines are padded to the\n * target width instead so left/right edges stay aligned.\n */\nfunction rebuildAtWidth(line: string, width: number, lead: string): string {\n\tconst { head, rest } = splitLeadingMarkers(line);\n\tconst bgAnsi = leadingSgr(rest);\n\tif (bgAnsi && isBackgroundSgr(bgAnsi) && rest.endsWith(BG_RESET)) {\n\t\tconst body = rest.slice(bgAnsi.length, rest.length - BG_RESET.length);\n\t\tconst pad = \" \".repeat(Math.max(0, width - visibleWidth(lead) - visibleWidth(body)));\n\t\treturn `${head}${bgAnsi}${lead}${body}${pad}${BG_RESET}`;\n\t}\n\tconst padded = `${lead}${line}`;\n\treturn `${padded}${\" \".repeat(Math.max(0, width - visibleWidth(padded)))}`;\n}\n\nfunction decorateMessageLine(\n\tline: string,\n\tindex: number,\n\tlastIndex: number,\n\tcontentIndex: number,\n\twidth: number,\n\toptions: {\n\t\tfirstEnvelope: OscParts | undefined;\n\t\tfirstHasStart: boolean;\n\t\tmultilineEnvelope: boolean;\n\t\tprefix: string;\n\t},\n): string {\n\tconst { firstEnvelope, firstHasStart, multilineEnvelope, prefix } = options;\n\tconst prefixWidth = visibleWidth(prefix);\n\tconst lead = index === contentIndex ? prefix : index > contentIndex ? \" \".repeat(prefixWidth) : \"\";\n\tif (index === contentIndex && firstEnvelope)\n\t\treturn `${firstEnvelope.start}${rebuildAtWidth(firstEnvelope.body, width, prefix)}${firstEnvelope.end}`;\n\tif (index === contentIndex && firstHasStart)\n\t\treturn `${OSC133_ZONE_START}${rebuildAtWidth(line.slice(OSC133_ZONE_START.length), width, prefix)}`;\n\tif (index === lastIndex && multilineEnvelope && index !== contentIndex)\n\t\treturn `${OSC133_ZONE_END}${OSC133_ZONE_FINAL}${rebuildAtWidth(\n\t\t\tline.slice((OSC133_ZONE_END + OSC133_ZONE_FINAL).length),\n\t\t\twidth,\n\t\t\tlead,\n\t\t)}`;\n\tif (\n\t\tindex === contentIndex &&\n\t\tindex === lastIndex &&\n\t\tmultilineEnvelope &&\n\t\tline.startsWith(OSC133_ZONE_END + OSC133_ZONE_FINAL)\n\t)\n\t\treturn `${OSC133_ZONE_END}${OSC133_ZONE_FINAL}${rebuildAtWidth(\n\t\t\tline.slice((OSC133_ZONE_END + OSC133_ZONE_FINAL).length),\n\t\t\twidth,\n\t\t\tprefix,\n\t\t)}`;\n\treturn rebuildAtWidth(line, width, lead);\n}\n\nfunction contentText(line: string): string {\n\tlet output = \"\";\n\tfor (let index = 0; index < line.length; index++) {\n\t\tif (line.charCodeAt(index) !== 27) {\n\t\t\toutput += line[index];\n\t\t\tcontinue;\n\t\t}\n\t\tconst next = line[index + 1];\n\t\tif (next === \"]\") {\n\t\t\tindex += 2;\n\t\t\twhile (index < line.length && line.charCodeAt(index) !== 7) index++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (next === \"[\") {\n\t\t\tindex += 2;\n\t\t\twhile (index < line.length && (line.charCodeAt(index) < 64 || line.charCodeAt(index) > 126)) index++;\n\t\t}\n\t}\n\treturn output.replaceAll(OSC133_ZONE_START, \"\").replaceAll(OSC133_ZONE_END, \"\").replaceAll(OSC133_ZONE_FINAL, \"\");\n}\n\nfunction hasContent(line: string): boolean {\n\treturn [...contentText(line)].some((character) => !/\\s/u.test(character));\n}\n\nfunction prefixNative(lines: unknown, width: number, prefix: string): string[] | undefined {\n\tif (!Array.isArray(lines) || lines.length === 0 || !lines.every((line) => typeof line === \"string\")) return undefined;\n\tconst nativeLines = lines as string[];\n\tconst prefixWidth = visibleWidth(prefix);\n\tif (width <= prefixWidth) return undefined;\n\tconst bodyWidth = width - prefixWidth;\n\tconst first = nativeLines[0] ?? \"\";\n\tconst last = nativeLines.at(-1) ?? \"\";\n\tconst multilineEnvelope = nativeLines.length > 1 && last.startsWith(OSC133_ZONE_END + OSC133_ZONE_FINAL);\n\t// The last line is a content-start candidate only when the envelope is\n\t// single-line, or when no earlier line carries content. Assistant messages\n\t// with a single content line render as a multiline envelope whose only body\n\t// sits on the final line ([OSC133_A, OSC133_END+FINAL+body]); excluding it\n\t// would drop the prefix for every short assistant reply.\n\tconst firstContentIndex = nativeLines.findIndex((line, index) => {\n\t\tif (index !== nativeLines.length - 1 || !multilineEnvelope) return hasContent(line);\n\t\treturn !nativeLines.slice(0, index).some((earlier) => hasContent(earlier)) && hasContent(line);\n\t});\n\tif (firstContentIndex < 0) return nativeLines;\n\tconst firstEnvelope = firstContentIndex === 0 ? extractOscEnvelope(first) : undefined;\n\tconst firstHasStart = firstContentIndex === 0 && first.startsWith(OSC133_ZONE_START);\n\tconst decorated = nativeLines.map((line, index) =>\n\t\tdecorateMessageLine(line, index, nativeLines.length - 1, firstContentIndex, width, {\n\t\t\tfirstEnvelope,\n\t\t\tfirstHasStart,\n\t\t\tmultilineEnvelope,\n\t\t\tprefix,\n\t\t}),\n\t);\n\tif (!decorated.every((line) => visibleWidth(line) <= width)) return undefined;\n\tif (!nativeLines.every((line) => visibleWidth(line) <= bodyWidth)) return undefined;\n\treturn decorated;\n}\n\nexport type MessageDecorationSnapshot = Readonly<{\n\tassistantPrefix: string;\n\tassistantEnabled: boolean;\n}>;\n\nexport function decorateMessageRender(\n\toriginal: unknown,\n\tinstance: object,\n\targs: unknown[],\n\tsnapshot: MessageDecorationSnapshot = {\n\t\tassistantPrefix: \"│ \",\n\t\tassistantEnabled: true,\n\t},\n): unknown {\n\tif (typeof original !== \"function\") return undefined;\n\tconst width = typeof args[0] === \"number\" ? args[0] : 0;\n\tconst prefix = snapshot.assistantPrefix;\n\tif (!snapshot.assistantEnabled) return Reflect.apply(original, instance, args);\n\tif (width <= visibleWidth(prefix)) return Reflect.apply(original, instance, args);\n\t// Exactly one native invocation. If the reduced render cannot be certified, the\n\t// already-obtained result is the only safe fallback; retrying can mutate state.\n\tconst reducedWidth = width - visibleWidth(prefix);\n\tconst native = Reflect.apply(original, instance, [reducedWidth, ...args.slice(1)]);\n\treturn prefixNative(native, width, prefix) ?? native;\n}\n\n// Special private layouts are intentionally not installed; their prototypes remain native.\n","import { visibleWidth } from \"@earendil-works/pi-tui\";\nimport { EMPTY_BATCH_COMPONENT } from \"./boxed/batch.js\";\nimport { renderBoxedToolCall, renderBoxedToolResult } from \"./boxed/index.js\";\n\n/**\n * Batch members render zero lines. Pi's ToolExecutionComponent always adds a\n * built-in Spacer child (one blank line) and only sets hideComponent when\n * hasContent is false — but adding an empty renderer still marks hasContent\n * true. Mark the instance hidden so members contribute zero lines (no stray\n * blank margin after the batch panel). updateDisplay resets hideComponent on\n * every pass; the wrapper re-applies it on each dispatch.\n */\nfunction hideBatchMember(instance: object): void {\n\t(instance as { hideComponent?: boolean }).hideComponent = true;\n}\n\n/**\n * Neutralize the native ToolExecutionComponent status background for boxed\n * rendering: Pi's updateDisplay sets contentBox/selfRenderContainer bgFn to\n * toolPendingBg/toolErrorBg/toolSuccessBg before invoking the renderers. The\n * boxed renderers own their visual boundary (borders + ✓/✗ state marks), so the\n * container fill is removed (no background slab).\n * Runs on every boxed dispatch; updateDisplay re-applies the bgFn on the next\n * pass and this wrapper re-neutralizes it.\n */\nfunction neutralizeToolContainerBackground(instance: object): void {\n\tconst host = instance as {\n\t\tgetRenderShell?(): string;\n\t\tselfRenderContainer?: { setBgFn?(fn: (text: string) => string): void; paddingX?: number; paddingY?: number };\n\t\tcontentBox?: { setBgFn?(fn: (text: string) => string): void; paddingX?: number; paddingY?: number };\n\t};\n\tconst container =\n\t\ttypeof host.getRenderShell === \"function\" && host.getRenderShell() === \"self\"\n\t\t\t? host.selfRenderContainer\n\t\t\t: host.contentBox;\n\tif (!container) return;\n\tcontainer.paddingX = 0;\n\tcontainer.paddingY = 0;\n\tif (typeof container.setBgFn === \"function\") container.setBgFn((text) => text);\n}\n\ntype RenderFunction = (this: object, ...args: unknown[]) => unknown;\ntype RendererSubtype = \"tool-call-renderer\" | \"tool-result-renderer\";\ntype RendererKind = \"call\" | \"result\";\ntype TransactionState = \"never-written\" | \"installed-owned\" | \"owner-changed\" | \"rollback-restored\" | \"rollback-failed\";\ntype ToolRenderContext = {\n\targs: object;\n\ttoolCallId: string;\n\tinvalidate: () => void;\n\tlastComponent: object | undefined;\n\tstate: object;\n\tcwd: string;\n\texecutionStarted: boolean;\n\targsComplete: boolean;\n\tisPartial: boolean;\n\texpanded: boolean;\n\tshowImages: boolean;\n\tisError: boolean;\n};\ntype ToolDecorationSnapshot = Readonly<{\n\tcallMarker: string;\n\tresultMarker: string;\n\t/** marker = prefix lines; compact-box = boxed tool call/result rendering. */\n\tstyle?: \"marker\" | \"compact-box\";\n}>;\ntype DescriptorView = Readonly<{\n\tkind: \"data\" | \"accessor\";\n\tvalue?: unknown;\n\tget?: unknown;\n\tset?: unknown;\n\twritable?: boolean;\n\tenumerable: boolean;\n\tconfigurable: boolean;\n}>;\ntype FailureEntry = Readonly<{ reason: string; transaction: TransactionState }>;\nexport type ToolDiagnosticArchive = Readonly<{\n\towner: string;\n\tgeneration: number;\n\treasons: Readonly<Record<string, number>>;\n\trestored: number;\n\tfailed: number;\n\tlaterOwner: number;\n\tfailures: readonly FailureEntry[];\n}>;\ntype CleanupOutcome = \"restored\" | \"later-owner\" | \"retry\";\ntype DecorationRecord = {\n\tcomponent: object;\n\tnativeRender: RenderFunction;\n\twrappedRender: RenderFunction;\n\tattemptedDescriptor: PropertyDescriptor;\n\toriginalOwnDescriptor?: PropertyDescriptor;\n\tinheritedDescriptor?: PropertyDescriptor;\n\tcontext: ToolRenderContext;\n\ttransaction: TransactionState;\n\tlastFailureSignature?: string;\n};\ntype DecorationState = {\n\tsnapshot: ToolDecorationSnapshot;\n\tdecorated: WeakMap<object, DecorationRecord>;\n\tactive: Set<DecorationRecord>;\n\tdiagnostics: Map<string, number>;\n\tfailures: FailureEntry[];\n\tarchive?: ToolDiagnosticArchive;\n\trestored: number;\n\tfailed: number;\n\tlaterOwner: number;\n\tgeneration: number;\n};\nconst DEFAULT_SNAPSHOT: ToolDecorationSnapshot = Object.freeze({\n\tcallMarker: \"[tool] \",\n\tresultMarker: \"[tool:result] \",\n\tstyle: \"marker\",\n});\nlet ownerGeneration = 0;\nconst piStyleWrappers = new WeakSet<RenderFunction>();\nlet toolTestHooks: { defineProperty?: typeof Reflect.defineProperty; deleteProperty?: typeof Reflect.deleteProperty } =\n\t{};\nexport function __setToolDecorationTestHooks(hooks: typeof toolTestHooks): () => void {\n\tconst previous = toolTestHooks;\n\ttoolTestHooks = hooks;\n\treturn () => {\n\t\ttoolTestHooks = previous;\n\t};\n}\n\nfunction note(state: DecorationState, reason: string, transaction: TransactionState = \"never-written\"): void {\n\tstate.diagnostics.set(reason, (state.diagnostics.get(reason) ?? 0) + 1);\n\tif (state.failures.length < 32) state.failures.push(Object.freeze({ reason, transaction }));\n}\nfunction isObject(value: unknown): value is object {\n\treturn typeof value === \"object\" && value !== null;\n}\nfunction ownData(object: object, key: string): unknown {\n\tconst descriptor = Object.getOwnPropertyDescriptor(object, key);\n\treturn descriptor && \"value\" in descriptor ? descriptor.value : undefined;\n}\nfunction hasOwnData(object: object, key: string): boolean {\n\tconst descriptor = Object.getOwnPropertyDescriptor(object, key);\n\treturn descriptor !== undefined && \"value\" in descriptor;\n}\nfunction validContext(value: unknown): value is ToolRenderContext {\n\tif (!isObject(value)) return false;\n\tconst booleans = [\"isPartial\", \"expanded\", \"isError\", \"executionStarted\", \"argsComplete\", \"showImages\"] as const;\n\treturn (\n\t\tisObject(ownData(value, \"args\")) &&\n\t\ttypeof ownData(value, \"toolCallId\") === \"string\" &&\n\t\ttypeof ownData(value, \"invalidate\") === \"function\" &&\n\t\tisObject(ownData(value, \"state\")) &&\n\t\ttypeof ownData(value, \"cwd\") === \"string\" &&\n\t\tbooleans.every((key) => typeof ownData(value, key) === \"boolean\") &&\n\t\thasOwnData(value, \"lastComponent\") &&\n\t\t(ownData(value, \"lastComponent\") === undefined || isObject(ownData(value, \"lastComponent\")))\n\t);\n}\nfunction validCallArgs(args: unknown[]): args is [object, object, ToolRenderContext] {\n\treturn args.length === 3 && isObject(args[0]) && isObject(args[1]) && validContext(args[2]);\n}\nfunction validResultArgs(args: unknown[]): args is [object, object, object, ToolRenderContext] {\n\tconst [result, options, theme, context] = args;\n\treturn (\n\t\tisObject(result) &&\n\t\thasOwnData(result, \"content\") &&\n\t\tArray.isArray(ownData(result, \"content\")) &&\n\t\thasOwnData(result, \"details\") &&\n\t\tisObject(options) &&\n\t\ttypeof ownData(options, \"expanded\") === \"boolean\" &&\n\t\ttypeof ownData(options, \"isPartial\") === \"boolean\" &&\n\t\tisObject(theme) &&\n\t\tvalidContext(context)\n\t);\n}\nfunction descriptorView(descriptor: PropertyDescriptor | undefined): DescriptorView | undefined {\n\tif (!descriptor) return undefined;\n\tif (\"value\" in descriptor)\n\t\treturn Object.freeze({\n\t\t\tkind: \"data\",\n\t\t\tvalue: descriptor.value,\n\t\t\twritable: descriptor.writable === true,\n\t\t\tenumerable: descriptor.enumerable === true,\n\t\t\tconfigurable: descriptor.configurable === true,\n\t\t});\n\treturn Object.freeze({\n\t\tkind: \"accessor\",\n\t\tget: descriptor.get,\n\t\tset: descriptor.set,\n\t\tenumerable: descriptor.enumerable === true,\n\t\tconfigurable: descriptor.configurable === true,\n\t});\n}\nfunction descriptorEqual(actual: PropertyDescriptor | undefined, expected: PropertyDescriptor | undefined): boolean {\n\tconst a = descriptorView(actual),\n\t\te = descriptorView(expected);\n\treturn (\n\t\ta?.kind === e?.kind &&\n\t\ta?.value === e?.value &&\n\t\ta?.get === e?.get &&\n\t\ta?.set === e?.set &&\n\t\ta?.writable === e?.writable &&\n\t\ta?.enumerable === e?.enumerable &&\n\t\ta?.configurable === e?.configurable\n\t);\n}\nfunction renderDescriptor(\n\tcomponent: object,\n): { own?: PropertyDescriptor; inherited?: PropertyDescriptor; native?: RenderFunction } | false {\n\tconst own = Object.getOwnPropertyDescriptor(component, \"render\");\n\tif (own && !(\"value\" in own && typeof own.value === \"function\" && own.writable === true && own.configurable === true))\n\t\treturn false;\n\tlet cursor = Object.getPrototypeOf(component);\n\tlet inherited: PropertyDescriptor | undefined;\n\twhile (cursor && !inherited) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(cursor, \"render\");\n\t\tif (descriptor) inherited = descriptor;\n\t\tcursor = Object.getPrototypeOf(cursor);\n\t}\n\tif (!own && inherited && !(\"value\" in inherited && typeof inherited.value === \"function\")) return false;\n\tconst native = own?.value ?? (inherited && \"value\" in inherited ? inherited.value : undefined);\n\treturn typeof native === \"function\"\n\t\t? { ...(own ? { own } : {}), ...(inherited ? { inherited } : {}), native }\n\t\t: false;\n}\nfunction marker(state: DecorationState, context: ToolRenderContext, kind: RendererKind): string {\n\tif (context.isError) return \"[tool:error] \";\n\tif (context.isPartial) return context.executionStarted ? \"[tool:running] \" : \"[tool:pending] \";\n\treturn kind === \"call\" ? state.snapshot.callMarker : state.snapshot.resultMarker;\n}\nfunction decorateLines(state: DecorationState, value: unknown, width: unknown, prefix: string): unknown {\n\tif (!Array.isArray(value) || !value.every((line) => typeof line === \"string\")) {\n\t\tnote(state, \"malformed-render\");\n\t\treturn value;\n\t}\n\tif (typeof width !== \"number\" || !Number.isFinite(width) || width < 0) {\n\t\tnote(state, \"invalid-width\");\n\t\treturn value;\n\t}\n\tconst lines = value as string[],\n\t\tprefixWidth = visibleWidth(prefix),\n\t\tbodyWidth = width - prefixWidth;\n\tif (width <= prefixWidth || !lines.every((line) => visibleWidth(line) <= bodyWidth)) {\n\t\tnote(state, \"reduced-native-fallback\");\n\t\treturn value;\n\t}\n\tconst output =\n\t\tlines.length === 0 ? [prefix.trimEnd()] : lines.map((line, index) => (index === 0 ? `${prefix}${line}` : line));\n\tif (output.every((line) => visibleWidth(line) <= width)) return output;\n\tnote(state, \"overwide-decoration\");\n\treturn value;\n}\nfunction createRecord(\n\tstate: DecorationState,\n\tcomponent: object,\n\tnativeRender: RenderFunction,\n\tcontext: ToolRenderContext,\n\tkind: RendererKind,\n\tdescriptors: { own?: PropertyDescriptor; inherited?: PropertyDescriptor },\n): DecorationRecord {\n\tconst attemptedDescriptor = descriptors.own\n\t\t? { ...descriptors.own, value: undefined as unknown as RenderFunction }\n\t\t: { value: undefined as unknown as RenderFunction, writable: true, enumerable: false, configurable: true };\n\tconst record = {\n\t\tcomponent,\n\t\tnativeRender,\n\t\twrappedRender: undefined as unknown as RenderFunction,\n\t\tattemptedDescriptor,\n\t\t...(descriptors.own ? { originalOwnDescriptor: descriptors.own } : {}),\n\t\t...(descriptors.inherited ? { inheritedDescriptor: descriptors.inherited } : {}),\n\t\tcontext,\n\t\ttransaction: \"never-written\" as TransactionState,\n\t};\n\trecord.wrappedRender = function (this: object, ...renderArgs: unknown[]): unknown {\n\t\tconst width = renderArgs[0],\n\t\t\tprefix = marker(state, record.context, kind);\n\t\tconst nativeArgs =\n\t\t\ttypeof width === \"number\" && width > visibleWidth(prefix)\n\t\t\t\t? [width - visibleWidth(prefix), ...renderArgs.slice(1)]\n\t\t\t\t: renderArgs;\n\t\treturn decorateLines(state, Reflect.apply(record.nativeRender, this, nativeArgs), width, prefix);\n\t};\n\tpiStyleWrappers.add(record.wrappedRender);\n\treturn record;\n}\nfunction installDecoration(state: DecorationState, record: DecorationRecord): void {\n\trecord.attemptedDescriptor.value = record.wrappedRender;\n\tlet wrote = false;\n\ttry {\n\t\twrote = Reflect.defineProperty(record.component, \"render\", record.attemptedDescriptor);\n\t} catch (error) {\n\t\tnote(state, `render-install-threw: ${error instanceof Error ? error.message : String(error)}`, \"never-written\");\n\t\treturn;\n\t}\n\tif (!wrote) {\n\t\tnote(state, \"render-install-rejected\", \"never-written\");\n\t\treturn;\n\t}\n\tconst current = Object.getOwnPropertyDescriptor(record.component, \"render\");\n\tif (!descriptorEqual(current, record.attemptedDescriptor)) {\n\t\tif (current?.value === record.wrappedRender) {\n\t\t\tconst restored = record.originalOwnDescriptor\n\t\t\t\t? (toolTestHooks.defineProperty ?? Reflect.defineProperty)(\n\t\t\t\t\t\trecord.component,\n\t\t\t\t\t\t\"render\",\n\t\t\t\t\t\trecord.originalOwnDescriptor,\n\t\t\t\t\t)\n\t\t\t\t: (toolTestHooks.deleteProperty ?? Reflect.deleteProperty)(record.component, \"render\");\n\t\t\tconst after = Object.getOwnPropertyDescriptor(record.component, \"render\");\n\t\t\tif (\n\t\t\t\trestored &&\n\t\t\t\t(record.originalOwnDescriptor ? descriptorEqual(after, record.originalOwnDescriptor) : after === undefined)\n\t\t\t) {\n\t\t\t\trecord.transaction = \"rollback-restored\";\n\t\t\t\tnote(state, \"render-install-flags-mismatch-rolled-back\", record.transaction);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\trecord.transaction = \"rollback-failed\";\n\t\t\tstate.decorated.set(record.component, record);\n\t\t\tstate.active.add(record);\n\t\t\tnote(state, \"render-install-rollback-failed\", record.transaction);\n\t\t\treturn;\n\t\t}\n\t\trecord.transaction = \"owner-changed\";\n\t\tnote(state, \"render-owner-changed-during-install\", record.transaction);\n\t\treturn;\n\t}\n\trecord.transaction = \"installed-owned\";\n\tstate.decorated.set(record.component, record);\n\tstate.active.add(record);\n}\nfunction restoreDecoration(state: DecorationState, record: DecorationRecord): CleanupOutcome {\n\tconst current = Object.getOwnPropertyDescriptor(record.component, \"render\");\n\tif (!descriptorEqual(current, record.attemptedDescriptor)) {\n\t\trecord.transaction = \"owner-changed\";\n\t\tstate.laterOwner++;\n\t\tnote(state, \"render-owner-changed\", record.transaction);\n\t\treturn \"later-owner\";\n\t}\n\tconst restored = record.originalOwnDescriptor\n\t\t? (toolTestHooks.defineProperty ?? Reflect.defineProperty)(record.component, \"render\", record.originalOwnDescriptor)\n\t\t: (toolTestHooks.deleteProperty ?? Reflect.deleteProperty)(record.component, \"render\");\n\tconst after = Object.getOwnPropertyDescriptor(record.component, \"render\");\n\tconst ok = record.originalOwnDescriptor ? descriptorEqual(after, record.originalOwnDescriptor) : after === undefined;\n\tif (!restored || !ok) {\n\t\trecord.transaction = \"rollback-failed\";\n\t\tconst signature = JSON.stringify(descriptorView(after));\n\t\tif (record.lastFailureSignature !== signature) {\n\t\t\trecord.lastFailureSignature = signature;\n\t\t\tnote(state, \"render-restore-failed\", record.transaction);\n\t\t}\n\t\treturn \"retry\";\n\t}\n\trecord.transaction = \"rollback-restored\";\n\treturn \"restored\";\n}\nfunction finalize(state: DecorationState): ToolDiagnosticArchive {\n\tif (state.archive) return state.archive;\n\tconst reasons = Object.freeze(Object.fromEntries(state.diagnostics));\n\tstate.archive = Object.freeze({\n\t\towner: `tool-owner-${state.generation}`,\n\t\tgeneration: state.generation,\n\t\treasons,\n\t\trestored: state.restored,\n\t\tfailed: state.failed,\n\t\tlaterOwner: state.laterOwner,\n\t\tfailures: Object.freeze(state.failures.slice(0, 32)),\n\t});\n\treturn state.archive;\n}\nexport function createToolDecorationOwner(snapshot: Partial<ToolDecorationSnapshot> = {}) {\n\tconst state: DecorationState = {\n\t\tsnapshot: Object.freeze({ ...DEFAULT_SNAPSHOT, ...snapshot }),\n\t\tdecorated: new WeakMap(),\n\t\tactive: new Set(),\n\t\tdiagnostics: new Map(),\n\t\tfailures: [],\n\t\trestored: 0,\n\t\tfailed: 0,\n\t\tlaterOwner: 0,\n\t\tgeneration: ++ownerGeneration,\n\t};\n\tconst dispose = () => {\n\t\tif (state.archive)\n\t\t\treturn {\n\t\t\t\trestored: state.restored,\n\t\t\t\tfailed: state.failed,\n\t\t\t\tdiagnostics: new Map(state.diagnostics),\n\t\t\t\tarchive: state.archive,\n\t\t\t};\n\t\tfor (const record of [...state.active]) {\n\t\t\tconst outcome = restoreDecoration(state, record);\n\t\t\tif (outcome === \"restored\") {\n\t\t\t\tstate.restored++;\n\t\t\t\tstate.active.delete(record);\n\t\t\t} else if (outcome === \"later-owner\") state.active.delete(record);\n\t\t\telse state.failed++;\n\t\t}\n\t\tconst archive = state.active.size === 0 ? finalize(state) : undefined;\n\t\treturn { restored: state.restored, failed: state.failed, diagnostics: new Map(state.diagnostics), archive };\n\t};\n\treturn Object.freeze({\n\t\tdecorateToolRendererSelection(subtype: RendererSubtype, original: unknown, instance: object, args: unknown[]) {\n\t\t\tif (typeof original !== \"function\") return undefined;\n\t\t\tconst renderer = Reflect.apply(original, instance, args);\n\t\t\tif (state.snapshot.style === \"compact-box\") {\n\t\t\t\tconst toolName = (instance as { toolName?: unknown }).toolName;\n\t\t\t\t// Tools without a native renderCall/renderResult (e.g. extension tools\n\t\t\t\t// like TaskUpdate/TaskList) still get boxed presentation through a\n\t\t\t\t// fallback renderer, mirroring the generic boxed fallback used for\n\t\t\t\t// unknown tool names.\n\t\t\t\tif (typeof renderer !== \"function\") {\n\t\t\t\t\tneutralizeToolContainerBackground(instance);\n\t\t\t\t\tif (subtype === \"tool-call-renderer\")\n\t\t\t\t\t\treturn (callArgs: unknown, theme: unknown, context: unknown) =>\n\t\t\t\t\t\t\trenderBoxedToolCall(toolName, callArgs as Record<string, unknown>, theme as never, context as never);\n\t\t\t\t\treturn (result: unknown, options: unknown, theme: unknown, context: unknown) =>\n\t\t\t\t\t\trenderBoxedToolResult(\n\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\tresult as { content?: readonly unknown[]; details?: unknown },\n\t\t\t\t\t\t\toptions as { expanded: boolean; isPartial: boolean },\n\t\t\t\t\t\t\ttheme as never,\n\t\t\t\t\t\t\tcontext as never,\n\t\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn function (this: unknown, ...rendererArgs: unknown[]) {\n\t\t\t\t\tconst valid = subtype === \"tool-call-renderer\" ? validCallArgs(rendererArgs) : validResultArgs(rendererArgs);\n\t\t\t\t\tif (!valid) {\n\t\t\t\t\t\tnote(state, `${subtype}-malformed-context`);\n\t\t\t\t\t\treturn Reflect.apply(renderer, this, rendererArgs);\n\t\t\t\t\t}\n\t\t\t\t\tconst component =\n\t\t\t\t\t\tsubtype === \"tool-call-renderer\"\n\t\t\t\t\t\t\t? (() => {\n\t\t\t\t\t\t\t\t\tconst [args, theme, context] = rendererArgs as [object, object, ToolRenderContext];\n\t\t\t\t\t\t\t\t\treturn renderBoxedToolCall(\n\t\t\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\t\t\targs as Record<string, unknown>,\n\t\t\t\t\t\t\t\t\t\ttheme as never,\n\t\t\t\t\t\t\t\t\t\tcontext as never,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t})()\n\t\t\t\t\t\t\t: (() => {\n\t\t\t\t\t\t\t\t\tconst [result, options, theme, context] = rendererArgs as [object, object, object, ToolRenderContext];\n\t\t\t\t\t\t\t\t\treturn renderBoxedToolResult(\n\t\t\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\t\t\tresult as { content?: readonly unknown[]; details?: unknown },\n\t\t\t\t\t\t\t\t\t\toptions as { expanded: boolean; isPartial: boolean },\n\t\t\t\t\t\t\t\t\t\ttheme as never,\n\t\t\t\t\t\t\t\t\t\tcontext as never,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t})();\n\t\t\t\t\tneutralizeToolContainerBackground(instance);\n\t\t\t\t\tif (component === EMPTY_BATCH_COMPONENT) hideBatchMember(instance);\n\t\t\t\t\treturn component;\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (typeof renderer !== \"function\") return renderer;\n\t\t\treturn function (this: unknown, ...rendererArgs: unknown[]) {\n\t\t\t\tconst valid = subtype === \"tool-call-renderer\" ? validCallArgs(rendererArgs) : validResultArgs(rendererArgs);\n\t\t\t\tif (!valid) {\n\t\t\t\t\tnote(state, `${subtype}-malformed-context`);\n\t\t\t\t\treturn Reflect.apply(renderer, this, rendererArgs);\n\t\t\t\t}\n\t\t\t\tconst component = Reflect.apply(renderer, this, rendererArgs);\n\t\t\t\tif (!isObject(component)) return component;\n\t\t\t\tconst descriptors = renderDescriptor(component);\n\t\t\t\tif (descriptors !== false && descriptors.native && piStyleWrappers.has(descriptors.native)) {\n\t\t\t\t\tnote(state, `${subtype}-owner-conflict`);\n\t\t\t\t\treturn component;\n\t\t\t\t}\n\t\t\t\tif (!descriptors) {\n\t\t\t\t\tnote(state, `${subtype}-unsafe-render-descriptor`);\n\t\t\t\t\treturn component;\n\t\t\t\t}\n\t\t\t\tconst record = state.decorated.get(component);\n\t\t\t\tif (record) {\n\t\t\t\t\trecord.context = rendererArgs.at(-1) as ToolRenderContext;\n\t\t\t\t\treturn component;\n\t\t\t\t}\n\t\t\t\tconst next = createRecord(\n\t\t\t\t\tstate,\n\t\t\t\t\tcomponent,\n\t\t\t\t\tdescriptors.native as RenderFunction,\n\t\t\t\t\trendererArgs.at(-1) as ToolRenderContext,\n\t\t\t\t\tsubtype === \"tool-call-renderer\" ? \"call\" : \"result\",\n\t\t\t\t\tdescriptors,\n\t\t\t\t);\n\t\t\t\tinstallDecoration(state, next);\n\t\t\t\treturn component;\n\t\t\t};\n\t\t},\n\t\tgetDiagnostics: () => new Map(state.diagnostics),\n\t\tgetFinalArchive: () => state.archive,\n\t\tgetActiveRecordCount: () => state.active.size,\n\t\tdispose,\n\t});\n}\n","// Boxed edit tool renderer\n// (renderCall/renderResult only; no edit-core re-registration).\n\nimport { getLanguageFromPath } from \"@earendil-works/pi-coding-agent\";\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport { stripAnsi } from \"../../../shared/ansi.js\";\nimport {\n\ttype BoxTheme,\n\tformatBoxedRunningStatus,\n\tgetTextOutput,\n\trenderBoxedToolCall,\n\trenderBoxedToolResult,\n} from \"../../../shared/box.js\";\nimport { formatElapsedMs, getElapsedMs } from \"../../../shared/elapsed.js\";\nimport {\n\tAdaptiveDiffComponent,\n\tbuildSplitRows,\n\tcountDiffStats,\n\textractEditedPath,\n\tfirstText,\n} from \"../../../shared/split-diff.js\";\nimport { isResultSeen } from \"./session-config.js\";\nimport {\n\ttype BoxedToolContext,\n\ttype BoxedToolDefinition,\n\tdisplayPath,\n\tnoteBoxedCallState,\n\tnoteBoxedResultPhase,\n\tnoteExecutionStart,\n\tresultFooterLines,\n\tstateElapsedMs,\n} from \"./shared.js\";\n\nconst MAX_HIGHLIGHT_DIFF_CHARS = 12000;\nconst MAX_HIGHLIGHT_DIFF_ROWS = 120;\n\n/** First-partial-pass result: the pending/running call card stands alone. */\nconst EMPTY_EDIT_RESULT: Component = Object.freeze({\n\tinvalidate() {},\n\trender() {\n\t\treturn [];\n\t},\n});\n\ntype EditResultDetails = { diff?: string; path?: string } | undefined;\n\n/** `Diff · +3 -0` divider label. */\nfunction diffDividerLabel(theme: BoxTheme, stats: { additions: number; removals: number }): string {\n\tconst plus = stats.additions > 0 ? theme.fg(\"toolDiffAdded\", `+${stats.additions}`) : theme.fg(\"dim\", \"+0\");\n\tconst minus = stats.removals > 0 ? theme.fg(\"toolDiffRemoved\", `-${stats.removals}`) : theme.fg(\"dim\", \"-0\");\n\treturn `Diff · ${plus} ${minus}`;\n}\n\n/** Edit footer: `1 file · +3 -0`, prefixed with elapsed time when known. */\nfunction editDiffFooter(\n\ttheme: BoxTheme,\n\tresult: { content?: readonly unknown[]; details?: unknown },\n\tcontext: BoxedToolContext,\n\tstats: { additions: number; removals: number },\n): string {\n\tconst elapsedMs = getElapsedMs(result) ?? stateElapsedMs(context);\n\tconst parts: string[] = [];\n\tif (elapsedMs !== undefined) parts.push(theme.fg(\"text\", formatElapsedMs(elapsedMs)));\n\tconst plus = stats.additions > 0 ? theme.fg(\"toolDiffAdded\", `+${stats.additions}`) : theme.fg(\"dim\", \"+0\");\n\tconst minus = stats.removals > 0 ? theme.fg(\"toolDiffRemoved\", `-${stats.removals}`) : theme.fg(\"dim\", \"-0\");\n\tparts.push(theme.fg(\"dim\", \"1 file\"), `${plus} ${minus}`);\n\treturn parts.join(theme.fg(\"dim\", \" · \"));\n}\n\nexport const editTool: BoxedToolDefinition = {\n\tcall(args, theme, context) {\n\t\tnoteExecutionStart(context);\n\t\tnoteBoxedCallState(context);\n\t\tconst detail = displayPath(String(args?.path ?? args?.file_path ?? \"\"), context);\n\t\treturn renderBoxedToolCall(theme, \"Edit\", [], {\n\t\t\theaderDetail: detail,\n\t\t\tisError: Boolean(context.isError),\n\t\t\tisPartial: Boolean(context.isPartial),\n\t\t\tisPending: Boolean(context.isPartial),\n\t\t\trunning: Boolean(context.executionStarted),\n\t\t\tresultSeen: isResultSeen(context.state),\n\t\t});\n\t},\n\tresult(result, options, theme, context) {\n\t\t// Handle partial/streaming state: continue the open call box with the\n\t\t// applying hint (no Response divider until the tool settles).\n\t\tif (options.isPartial) {\n\t\t\tconst firstResultPass = noteBoxedResultPhase(context, options.isPartial);\n\t\t\tif (firstResultPass) return EMPTY_EDIT_RESULT;\n\t\t\treturn renderBoxedToolResult(theme, () => [`${theme.fg(\"dim\", \"↳\")} ${theme.fg(\"muted\", \"Applying edit...\")}`], {\n\t\t\t\tshowDivider: false,\n\t\t\t\tfooterLines: [formatBoxedRunningStatus(theme, stateElapsedMs(context))],\n\t\t\t\tisPartial: true,\n\t\t\t});\n\t\t}\n\n\t\t// Handle errors\n\t\tif (context.isError) {\n\t\t\tconst output = getTextOutput(result);\n\t\t\treturn renderBoxedToolResult(theme, () => [theme.fg(\"error\", stripAnsi(output).trim() || \"Error\")], {\n\t\t\t\tfooterLines: resultFooterLines(theme, result, context),\n\t\t\t\tisError: true,\n\t\t\t});\n\t\t}\n\n\t\t// Extract diff from result details\n\t\tconst details = result.details as EditResultDetails;\n\t\tconst diff = details?.diff as string | undefined;\n\n\t\tif (!diff) {\n\t\t\tconst output = stripAnsi(getTextOutput(result)).trim();\n\t\t\tconst fallback = `↳ ${output || \"Edit applied\"}`;\n\t\t\treturn renderBoxedToolResult(theme, () => [theme.fg(\"dim\", fallback)], {\n\t\t\t\tfooterLines: resultFooterLines(theme, result, context),\n\t\t\t});\n\t\t}\n\n\t\t// Resolve language for syntax highlighting\n\t\tconst message = firstText(result.content as Array<{ type: string; text?: string }>);\n\t\tconst argPath = String(context?.args?.path ?? context?.args?.file_path ?? \"\");\n\t\tconst sourcePath = details?.path ?? (argPath || extractEditedPath(message));\n\t\tconst language = sourcePath ? getLanguageFromPath(sourcePath) : undefined;\n\n\t\t// Build diff rows + adaptive layout\n\t\tconst rows = buildSplitRows(diff);\n\t\tconst expanded = options.expanded;\n\t\tconst shouldHighlight =\n\t\t\tBoolean(language) && diff.length <= MAX_HIGHLIGHT_DIFF_CHARS && rows.length <= MAX_HIGHLIGHT_DIFF_ROWS;\n\t\tconst stats = countDiffStats(diff);\n\n\t\t// Render adaptive diff (unified/split per width) with syntax colors for small outputs.\n\t\tconst maxRows = expanded ? 160 : 36;\n\t\tconst diffView = new AdaptiveDiffComponent(theme, rows, maxRows, shouldHighlight ? language : undefined);\n\t\tconst expandHint = !expanded && diffView.hasCollapsed() ? \"Ctrl+O more\" : undefined;\n\n\t\treturn renderBoxedToolResult(\n\t\t\ttheme,\n\t\t\t{\n\t\t\t\trender(width: number): string[] {\n\t\t\t\t\treturn diffView.render(width);\n\t\t\t\t},\n\t\t\t\tinvalidate(): void {\n\t\t\t\t\tdiffView.invalidate();\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tdividerLabel: diffDividerLabel(theme, stats),\n\t\t\t\t...(expandHint ? { dividerRightLabel: expandHint } : {}),\n\t\t\t\tfooterLines: [editDiffFooter(theme, result, context, stats)],\n\t\t\t},\n\t\t);\n\t},\n};\n\nexport type { BoxedToolContext };\n","// Adaptive diff renderer — side-by-side (split) for short corresponding\n// changes, unified for additions/removals-only diffs and narrow terminals,\n// with long runs of unchanged context collapsed into a single\n// \"⋯ N unchanged lines hidden\" row instead of arbitrary output truncation.\n\nimport { highlightCode } from \"@earendil-works/pi-coding-agent\";\nimport type { Component } from \"@earendil-works/pi-tui\";\n\nimport { stripAnsi } from \"./ansi.js\";\nimport { safeTruncateToWidth, safeVisibleWidth } from \"./render-budget.js\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\ntype DiffLine = {\n\tprefix: \"+\" | \"-\" | \" \";\n\tline: string;\n\tlineNumber: string;\n};\n\ntype SplitDiffRow = {\n\tkind: \"context\" | \"changed\" | \"added\" | \"removed\";\n\tleft?: DiffLine;\n\tright?: DiffLine;\n};\n\ntype CellLineKind = \"add\" | \"remove\" | \"context\";\n\ntype DiffSpan = { start: number; end: number };\n\ntype RgbColor = { r: number; g: number; b: number };\n\n/** Structural view of the theme as used by the diff renderers. */\nexport interface SplitDiffTheme {\n\tfg(color: string, text: string): string;\n\tgetBgAnsi?(color: string): string;\n\tgetFgAnsi?(color: string): string;\n}\n\nexport type DiffMode = \"unified\" | \"split\";\n\ntype DiffPalette = {\n\taddRowBgAnsi: string;\n\tremoveRowBgAnsi: string;\n\taddEmphasisBgAnsi: string;\n\tremoveEmphasisBgAnsi: string;\n};\n\n/** A planned render entry: a diff row, a collapsed context gap, or a budget omission. */\ntype DiffEntry =\n\t| { kind: \"row\"; row: SplitDiffRow }\n\t| { kind: \"gap\"; hidden: number }\n\t| { kind: \"omitted\"; count: number };\n\n// ── Constants ──────────────────────────────────────────────────────\n\nconst ESC = \"\\x1b\";\nconst BG_ANSI_PATTERN = new RegExp(`${ESC}\\\\[(?:4\\\\d|10\\\\d|48;5;\\\\d{1,3}|48;2;\\\\d{1,3};\\\\d{1,3};\\\\d{1,3}|49)m`, \"g\");\nconst CONTROL_CHARS = \"\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F\";\n\nconst ADD_ROW_BACKGROUND_MIX_RATIO = 0.24;\nconst REMOVE_ROW_BACKGROUND_MIX_RATIO = 0.12;\nconst ADD_INLINE_EMPHASIS_MIX_RATIO = 0.44;\nconst REMOVE_INLINE_EMPHASIS_MIX_RATIO = 0.26;\n\n/** Context lines kept on each side of a collapsed run of unchanged lines. */\nconst CONTEXT_KEEP_DEFAULT = 2;\n/** Context runs of this length (or less) are shown in full. */\nconst CONTEXT_RUN_SHOW_MAX = 4;\n\n/**\n * Minimum diff content width before split mode is even considered. Box chrome\n * (2 borders + 4 side padding) costs ~6 columns, so this corresponds to a\n * ~120-column terminal — below that the two panes wrap too aggressively and\n * unified is always used.\n */\nconst SPLIT_DIFF_MIN_WIDTH = 114;\n\n// ── ANSI color utilities (diff-specific) ───────────────────────────\n\nfunction ansi256ToRgb(code: number): RgbColor {\n\tif (code <= 15) {\n\t\tconst base16: RgbColor[] = [\n\t\t\t{ r: 0, g: 0, b: 0 },\n\t\t\t{ r: 128, g: 0, b: 0 },\n\t\t\t{ r: 0, g: 128, b: 0 },\n\t\t\t{ r: 128, g: 128, b: 0 },\n\t\t\t{ r: 0, g: 0, b: 128 },\n\t\t\t{ r: 128, g: 0, b: 128 },\n\t\t\t{ r: 0, g: 128, b: 128 },\n\t\t\t{ r: 192, g: 192, b: 192 },\n\t\t\t{ r: 128, g: 128, b: 128 },\n\t\t\t{ r: 255, g: 0, b: 0 },\n\t\t\t{ r: 0, g: 255, b: 0 },\n\t\t\t{ r: 255, g: 255, b: 0 },\n\t\t\t{ r: 0, g: 0, b: 255 },\n\t\t\t{ r: 255, g: 0, b: 255 },\n\t\t\t{ r: 0, g: 255, b: 255 },\n\t\t\t{ r: 255, g: 255, b: 255 },\n\t\t];\n\t\treturn base16[code] ?? { r: 255, g: 255, b: 255 };\n\t}\n\tif (code >= 232) {\n\t\tconst value = Math.max(0, Math.min(255, 8 + (code - 232) * 10));\n\t\treturn { r: value, g: value, b: value };\n\t}\n\tconst cube = code - 16;\n\tconst levels = [0, 95, 135, 175, 215, 255];\n\tconst blue = cube % 6;\n\tconst green = Math.floor(cube / 6) % 6;\n\tconst red = Math.floor(cube / 36) % 6;\n\treturn {\n\t\tr: levels[red] ?? 0,\n\t\tg: levels[green] ?? 0,\n\t\tb: levels[blue] ?? 0,\n\t};\n}\n\nfunction parseAnsiColorCode(ansi: string | undefined): RgbColor | null {\n\tif (!ansi) return null;\n\tconst rgbMatch = new RegExp(`${ESC}\\\\[(?:3|4)8;2;(\\\\d{1,3});(\\\\d{1,3});(\\\\d{1,3})m`).exec(ansi);\n\tif (rgbMatch) {\n\t\tconst r = Number.parseInt(rgbMatch[1] ?? \"0\", 10);\n\t\tconst g = Number.parseInt(rgbMatch[2] ?? \"0\", 10);\n\t\tconst b = Number.parseInt(rgbMatch[3] ?? \"0\", 10);\n\t\treturn { r, g, b };\n\t}\n\tconst bitMatch = new RegExp(`${ESC}\\\\[(?:3|4)8;5;(\\\\d{1,3})m`).exec(ansi);\n\tif (bitMatch) {\n\t\tconst code = Number.parseInt(bitMatch[1] ?? \"0\", 10);\n\t\treturn ansi256ToRgb(code);\n\t}\n\treturn null;\n}\n\nfunction rgbToBgAnsi(color: RgbColor): string {\n\tconst r = Math.max(0, Math.min(255, Math.round(color.r)));\n\tconst g = Math.max(0, Math.min(255, Math.round(color.g)));\n\tconst b = Math.max(0, Math.min(255, Math.round(color.b)));\n\treturn `\\x1b[48;2;${r};${g};${b}m`;\n}\n\nfunction mixRgb(base: RgbColor, tint: RgbColor, ratio: number): RgbColor {\n\tconst clamped = Math.max(0, Math.min(1, ratio));\n\treturn {\n\t\tr: base.r * (1 - clamped) + tint.r * clamped,\n\t\tg: base.g * (1 - clamped) + tint.g * clamped,\n\t\tb: base.b * (1 - clamped) + tint.b * clamped,\n\t};\n}\n\nfunction resolveDiffPalette(theme: SplitDiffTheme): DiffPalette {\n\tconst baseBg = parseAnsiColorCode(theme.getBgAnsi?.(\"toolSuccessBg\")) ??\n\t\tparseAnsiColorCode(theme.getBgAnsi?.(\"toolPendingBg\")) ?? { r: 32, g: 35, b: 42 };\n\tconst addFg = parseAnsiColorCode(theme.getFgAnsi?.(\"toolDiffAdded\")) ?? { r: 88, g: 173, b: 88 };\n\tconst removeFg = parseAnsiColorCode(theme.getFgAnsi?.(\"toolDiffRemoved\")) ?? { r: 196, g: 98, b: 98 };\n\n\tconst addRowBg = mixRgb(baseBg, addFg, ADD_ROW_BACKGROUND_MIX_RATIO);\n\tconst removeRowBg = mixRgb(baseBg, removeFg, REMOVE_ROW_BACKGROUND_MIX_RATIO);\n\tconst addEmphasisBg = mixRgb(baseBg, addFg, ADD_INLINE_EMPHASIS_MIX_RATIO);\n\tconst removeEmphasisBg = mixRgb(baseBg, removeFg, REMOVE_INLINE_EMPHASIS_MIX_RATIO);\n\n\treturn {\n\t\taddRowBgAnsi: rgbToBgAnsi(addRowBg),\n\t\tremoveRowBgAnsi: rgbToBgAnsi(removeRowBg),\n\t\taddEmphasisBgAnsi: rgbToBgAnsi(addEmphasisBg),\n\t\tremoveEmphasisBgAnsi: rgbToBgAnsi(removeEmphasisBg),\n\t};\n}\n\n// ── ANSI background helpers ────────────────────────────────────────\n\nfunction keepBackgroundAcrossResets(text: string, rowBgAnsi: string): string {\n\tif (!text) return text;\n\n\treturn text.replace(new RegExp(`${ESC}\\\\[([0-9;]*)m`, \"g\"), (sequence, rawCodes) => {\n\t\tconst split = String(rawCodes ?? \"\")\n\t\t\t.split(\";\")\n\t\t\t.filter(Boolean);\n\t\tconst codes = split.length > 0 ? split : [\"0\"]; // ESC[m == reset\n\t\tconst hasGlobalReset = codes.includes(\"0\");\n\t\tconst hasBgReset = codes.includes(\"49\");\n\t\tif (!hasGlobalReset && !hasBgReset) return sequence;\n\n\t\tconst rebuiltCodes = codes.filter((code: string) => code !== \"49\");\n\t\tconst rebuilt = rebuiltCodes.length > 0 ? `\\x1b[${rebuiltCodes.join(\";\")}m` : \"\";\n\t\treturn `${rebuilt}${rowBgAnsi}`;\n\t});\n}\n\nfunction applyBackgroundToVisibleRange(\n\tansiText: string,\n\tstart: number,\n\tend: number,\n\tbackgroundAnsi: string,\n\trestoreBackgroundAnsi: string,\n): string {\n\tif (!ansiText || start >= end || end <= 0) return ansiText;\n\n\tlet output = \"\";\n\tlet visibleIndex = 0;\n\tlet index = 0;\n\tlet inRange = false;\n\n\twhile (index < ansiText.length) {\n\t\tif (ansiText[index] === \"\\x1b\") {\n\t\t\tconst sequenceEnd = ansiText.indexOf(\"m\", index);\n\t\t\tif (sequenceEnd !== -1) {\n\t\t\t\toutput += ansiText.slice(index, sequenceEnd + 1);\n\t\t\t\tindex = sequenceEnd + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (visibleIndex === start && !inRange) {\n\t\t\toutput += backgroundAnsi;\n\t\t\tinRange = true;\n\t\t}\n\t\tif (visibleIndex === end && inRange) {\n\t\t\toutput += restoreBackgroundAnsi;\n\t\t\tinRange = false;\n\t\t}\n\n\t\toutput += ansiText[index] ?? \"\";\n\t\tvisibleIndex++;\n\t\tindex++;\n\t}\n\n\tif (inRange) output += restoreBackgroundAnsi;\n\treturn output;\n}\n\n// ── Text utilities ─────────────────────────────────────────────────\n\nfunction sanitizeSingleLineText(value: string): string {\n\treturn value\n\t\t.replace(/\\r/g, \"\")\n\t\t.replace(/\\n/g, \"\")\n\t\t.replace(new RegExp(`[${CONTROL_CHARS}]`, \"g\"), \"\");\n}\n\nfunction stripInlineBreaksPreserveAnsi(value: string): string {\n\treturn value.replace(/\\r/g, \"\").replace(/\\n/g, \"\");\n}\n\nfunction padRight(value: string, width: number): string {\n\tconst visual = safeVisibleWidth(stripAnsi(value));\n\tif (visual >= width) return value;\n\treturn value + \" \".repeat(width - visual);\n}\n\nfunction fitToWidth(value: string, width: number): string {\n\treturn padRight(safeTruncateToWidth(value, width), width);\n}\n\nfunction padRenderedLineWidth(line: string, width: number): string {\n\tconst safeWidth = Math.max(1, width);\n\tconst current = safeVisibleWidth(stripAnsi(line));\n\tif (current >= safeWidth) return line;\n\treturn line + \" \".repeat(safeWidth - current);\n}\n\nfunction wrapPlainText(text: string, width: number): string[] {\n\tconst safeWidth = Math.max(1, width);\n\tconst safeText = sanitizeSingleLineText(text);\n\tif (!safeText) return [\"\"];\n\n\tconst lines: string[] = [];\n\tlet cursor = 0;\n\n\twhile (cursor < safeText.length) {\n\t\tconst remaining = safeText.length - cursor;\n\t\tif (remaining <= safeWidth) {\n\t\t\tlines.push(safeText.slice(cursor));\n\t\t\tbreak;\n\t\t}\n\n\t\tconst window = safeText.slice(cursor, cursor + safeWidth);\n\t\tconst breakOnSpace = window.lastIndexOf(\" \");\n\n\t\tif (breakOnSpace > 0) {\n\t\t\tconst next = breakOnSpace + 1; // keep the space so offsets stay stable for inline diff spans\n\t\t\tlines.push(safeText.slice(cursor, cursor + next));\n\t\t\tcursor += next;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Fallback for long uninterrupted tokens (paths, hashes, etc.)\n\t\tlines.push(window);\n\t\tcursor += safeWidth;\n\t}\n\n\treturn lines.length > 0 ? lines : [\"\"];\n}\n\n// ── Diff parsing ───────────────────────────────────────────────────\n\nfunction parseLineNumber(value: string): number | undefined {\n\tconst trimmed = value.trim();\n\tif (!/^\\d+$/.test(trimmed)) return undefined;\n\tconst parsed = Number.parseInt(trimmed, 10);\n\treturn Number.isFinite(parsed) ? parsed : undefined;\n}\n\nfunction makeDiffLine(prefix: \"+\" | \"-\" | \" \", lineNumber: string | number | undefined, line: string): DiffLine {\n\treturn {\n\t\tprefix,\n\t\tlineNumber: lineNumber === undefined ? \"\" : String(lineNumber),\n\t\tline,\n\t};\n}\n\nfunction parseDiffLine(rawLine: string): DiffLine | undefined {\n\tconst match = rawLine.match(/^([+\\- ])\\s?(.*)$/);\n\tif (!match) return undefined;\n\tconst [, prefix, rest = \"\"] = match;\n\tif (prefix !== \"+\" && prefix !== \"-\" && prefix !== \" \") return undefined;\n\n\tconst gutterMatch = rest.match(/^(\\d+)\\s(.*)$/);\n\tconst lineNumber = gutterMatch?.[1] ?? \"\";\n\tconst line = gutterMatch?.[2] ?? rest;\n\tconst cleanLineNumber = sanitizeSingleLineText(lineNumber);\n\tconst cleanLine = sanitizeSingleLineText(line).replace(/\\t/g, \" \");\n\treturn { prefix, lineNumber: cleanLineNumber, line: cleanLine };\n}\n\nfunction computeInlineDiffSpans(leftLine: string, rightLine: string): { left: DiffSpan[]; right: DiffSpan[] } {\n\tif (leftLine === rightLine) return { left: [], right: [] };\n\tlet start = 0;\n\tconst minLen = Math.min(leftLine.length, rightLine.length);\n\twhile (start < minLen && leftLine[start] === rightLine[start]) start++;\n\n\tlet leftEnd = leftLine.length;\n\tlet rightEnd = rightLine.length;\n\twhile (leftEnd > start && rightEnd > start && leftLine[leftEnd - 1] === rightLine[rightEnd - 1]) {\n\t\tleftEnd--;\n\t\trightEnd--;\n\t}\n\n\tconst leftSpan = leftEnd > start ? [{ start, end: leftEnd }] : [];\n\tconst rightSpan = rightEnd > start ? [{ start, end: rightEnd }] : [];\n\treturn { left: leftSpan, right: rightSpan };\n}\n\n// ── Exported helpers ───────────────────────────────────────────────\n\nexport function buildSplitRows(diff: string): SplitDiffRow[] {\n\tconst rows: SplitDiffRow[] = [];\n\tconst pendingLeft: DiffLine[] = [];\n\tconst pendingRight: DiffLine[] = [];\n\tlet oldCursor: number | undefined;\n\tlet newCursor: number | undefined;\n\n\tconst flushPending = () => {\n\t\twhile (pendingLeft.length > 0 || pendingRight.length > 0) {\n\t\t\tconst left = pendingLeft.shift();\n\t\t\tconst right = pendingRight.shift();\n\t\t\tif (left && right) rows.push({ kind: \"changed\", left, right });\n\t\t\telse if (left) rows.push({ kind: \"removed\", left });\n\t\t\telse if (right) rows.push({ kind: \"added\", right });\n\t\t}\n\t};\n\n\tfor (const rawLine of diff.split(\"\\n\")) {\n\t\tconst parsed = parseDiffLine(rawLine);\n\t\tif (!parsed) continue;\n\n\t\tconst parsedNum = parseLineNumber(parsed.lineNumber);\n\t\tif (parsed.prefix === \"-\") {\n\t\t\tconst oldNum = parsedNum ?? oldCursor;\n\t\t\tif (oldNum !== undefined) oldCursor = oldNum + 1;\n\t\t\tpendingLeft.push(makeDiffLine(\"-\", oldNum, parsed.line));\n\t\t\tcontinue;\n\t\t}\n\t\tif (parsed.prefix === \"+\") {\n\t\t\tconst newNum = parsedNum ?? newCursor;\n\t\t\tif (newNum !== undefined) newCursor = newNum + 1;\n\t\t\tpendingRight.push(makeDiffLine(\"+\", newNum, parsed.line));\n\t\t\tcontinue;\n\t\t}\n\n\t\tflushPending();\n\n\t\tconst oldNum = parsedNum ?? oldCursor;\n\t\tconst newNum = newCursor ?? oldNum;\n\t\tif (oldNum !== undefined) oldCursor = oldNum + 1;\n\t\tif (newNum !== undefined) newCursor = newNum + 1;\n\n\t\trows.push({\n\t\t\tkind: \"context\",\n\t\t\tleft: makeDiffLine(\" \", oldNum, parsed.line),\n\t\t\tright: makeDiffLine(\" \", newNum, parsed.line),\n\t\t});\n\t}\n\n\tflushPending();\n\treturn rows;\n}\n\nexport function countDiffStats(diff: string): { additions: number; removals: number } {\n\tlet additions = 0;\n\tlet removals = 0;\n\tfor (const line of diff.split(\"\\n\")) {\n\t\tif (line.startsWith(\"+++\") || line.startsWith(\"---\")) continue;\n\t\tif (line.startsWith(\"+\")) additions += 1;\n\t\tif (line.startsWith(\"-\")) removals += 1;\n\t}\n\treturn { additions, removals };\n}\n\nexport function extractEditedPath(message: string): string | undefined {\n\tconst m = message.match(/Successfully replaced (?:text|\\d+ block\\(s\\)|lines L\\d+-\\d+) in (.+)\\.$/);\n\treturn m?.[1];\n}\n\nexport function firstText(content: Array<{ type: string; text?: string }>): string {\n\tfor (const part of content) {\n\t\tif (part.type === \"text\" && typeof part.text === \"string\") {\n\t\t\treturn part.text;\n\t\t}\n\t}\n\treturn \"\";\n}\n\nfunction longestChangedLineWidth(rows: SplitDiffRow[]): number {\n\tlet longest = 0;\n\tfor (const row of rows) {\n\t\tconst candidates: string[] = [];\n\t\tif (row.kind === \"changed\") {\n\t\t\tif (row.left) candidates.push(row.left.line);\n\t\t\tif (row.right) candidates.push(row.right.line);\n\t\t} else if (row.kind === \"added\" && row.right) {\n\t\t\tcandidates.push(row.right.line);\n\t\t} else if (row.kind === \"removed\" && row.left) {\n\t\t\tcandidates.push(row.left.line);\n\t\t}\n\t\tfor (const candidate of candidates) {\n\t\t\tlongest = Math.max(longest, safeVisibleWidth(candidate));\n\t\t}\n\t}\n\treturn longest;\n}\n\n/**\n * Adaptive layout rule: split side-by-side only when the change has both\n * additions and removals (so both panes carry content), the terminal is wide\n * enough, and no changed line is so long that it would wrap badly in a half\n * pane. Everything else renders as a unified diff.\n */\nexport function pickDiffMode(\n\tstats: { additions: number; removals: number },\n\trows: SplitDiffRow[],\n\twidth: number,\n): DiffMode {\n\tif (stats.additions <= 0 || stats.removals <= 0) return \"unified\";\n\tif (width < SPLIT_DIFF_MIN_WIDTH) return \"unified\";\n\tif (longestChangedLineWidth(rows) > width / 2) return \"unified\";\n\treturn \"split\";\n}\n\nfunction collapseContextRows(rows: SplitDiffRow[], options: { keep: number; runShowMax?: number }): DiffEntry[] {\n\tconst keep = options.keep;\n\tconst runShowMax = options.runShowMax ?? CONTEXT_RUN_SHOW_MAX;\n\tconst out: DiffEntry[] = [];\n\tlet i = 0;\n\n\twhile (i < rows.length) {\n\t\tconst row = rows[i];\n\t\tif (row?.kind !== \"context\") {\n\t\t\tif (row) out.push({ kind: \"row\", row });\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet j = i;\n\t\twhile (j < rows.length && rows[j]?.kind === \"context\") j++;\n\t\tconst run = j - i;\n\n\t\tif (run <= runShowMax) {\n\t\t\tfor (let k = i; k < j; k++) out.push({ kind: \"row\", row: rows[k] as SplitDiffRow });\n\t\t} else {\n\t\t\tconst leading = i === 0;\n\t\t\tconst trailing = j >= rows.length;\n\t\t\tconst keepHead = leading ? 0 : Math.min(keep, run);\n\t\t\tconst keepTail = trailing ? 0 : Math.min(keep, Math.max(0, run - keepHead));\n\t\t\tconst hidden = Math.max(0, run - keepHead - keepTail);\n\n\t\t\tif (keepHead > 0) {\n\t\t\t\tfor (let k = i; k < i + keepHead; k++) out.push({ kind: \"row\", row: rows[k] as SplitDiffRow });\n\t\t\t}\n\t\t\tif (hidden > 0) out.push({ kind: \"gap\", hidden });\n\t\t\tif (keepTail > 0) {\n\t\t\t\tfor (let k = j - keepTail; k < j; k++) out.push({ kind: \"row\", row: rows[k] as SplitDiffRow });\n\t\t\t}\n\t\t}\n\n\t\ti = j;\n\t}\n\n\treturn out;\n}\n\n/**\n * Plan the render entries under a row budget: collapse long context runs with\n * the default padding first, then drop all context if the diff is still too\n * tall, then finally trim the head and append an omission marker. The budget\n * applies to entries (each renders at least one line, gaps included).\n */\nfunction planEntries(rows: SplitDiffRow[], maxRows: number): DiffEntry[] {\n\tconst budget = Math.max(1, maxRows);\n\n\tlet entries = collapseContextRows(rows, { keep: CONTEXT_KEEP_DEFAULT });\n\tif (entries.length <= budget) return entries;\n\n\tentries = collapseContextRows(rows, { keep: 0, runShowMax: 0 });\n\tif (entries.length <= budget) return entries;\n\n\tconst kept = entries.slice(0, Math.max(1, budget - 1));\n\tconst omitted = Math.max(0, entries.length - kept.length);\n\tif (omitted <= 0) return kept;\n\treturn [...kept, { kind: \"omitted\", count: omitted }];\n}\n\nfunction formatGapLabel(hidden: number): string {\n\treturn `⋯ ${hidden} unchanged ${hidden === 1 ? \"line\" : \"lines\"} hidden`;\n}\n\nfunction formatOmittedLabel(count: number): string {\n\treturn `⋯ ${count} ${count === 1 ? \"line\" : \"lines\"} omitted · Ctrl+O to show full diff`;\n}\n\n// ── DiffRenderContext ──────────────────────────────────────────────\n// Shared per-instance state: palette, gutter width, syntax-highlight cache,\n// and inline-emphasis spans for paired changed rows.\n\nclass DiffRenderContext {\n\treadonly lineNumberWidth: number;\n\treadonly palette: DiffPalette;\n\treadonly containerBgAnsi: string;\n\tprivate readonly highlightCache = new Map<string, string>();\n\tprivate readonly inlineHighlights = new WeakMap<DiffLine, DiffSpan[]>();\n\n\tconstructor(\n\t\tprivate readonly theme: SplitDiffTheme,\n\t\trows: SplitDiffRow[],\n\t\tprivate readonly language?: string,\n\t) {\n\t\tlet maxDigits = 3;\n\t\tfor (const row of rows) {\n\t\t\tconst leftDigits = row.left?.lineNumber.trim().length ?? 0;\n\t\t\tconst rightDigits = row.right?.lineNumber.trim().length ?? 0;\n\t\t\tmaxDigits = Math.max(maxDigits, leftDigits, rightDigits);\n\n\t\t\tif (row.kind === \"changed\" && row.left && row.right) {\n\t\t\t\tconst spans = computeInlineDiffSpans(row.left.line, row.right.line);\n\t\t\t\tif (spans.left.length > 0) this.inlineHighlights.set(row.left, spans.left);\n\t\t\t\tif (spans.right.length > 0) this.inlineHighlights.set(row.right, spans.right);\n\t\t\t}\n\t\t}\n\t\tthis.lineNumberWidth = maxDigits;\n\t\tthis.palette = resolveDiffPalette(theme);\n\t\tthis.containerBgAnsi = theme.getBgAnsi?.(\"toolSuccessBg\") ?? \"\";\n\t}\n\n\tfg(color: string, text: string): string {\n\t\treturn this.theme.fg(color, text);\n\t}\n\n\tinlineSpans(line: DiffLine): DiffSpan[] {\n\t\treturn this.inlineHighlights.get(line) ?? [];\n\t}\n\n\tsyntaxHighlight(line: string): string {\n\t\tif (!this.language) return stripInlineBreaksPreserveAnsi(line);\n\t\tconst safeLine = sanitizeSingleLineText(line);\n\t\tconst key = `${this.language}\\n${safeLine}`;\n\t\tconst cached = this.highlightCache.get(key);\n\t\tif (cached) return cached;\n\n\t\tlet highlighted = safeLine;\n\t\ttry {\n\t\t\thighlighted = highlightCode(safeLine, this.language)[0] ?? safeLine;\n\t\t\thighlighted = stripInlineBreaksPreserveAnsi(highlighted).replace(BG_ANSI_PATTERN, \"\");\n\t\t} catch {\n\t\t\thighlighted = safeLine;\n\t\t}\n\t\tthis.highlightCache.set(key, highlighted);\n\t\treturn highlighted;\n\t}\n}\n\n// ── Unified diff renderer ──────────────────────────────────────────\n// One column: marker + gutter + content, with added/removed lines carrying\n// the same row backgrounds as the split view. Changed rows expand back into\n// their removed-then-added pair (like `git diff`).\n\nclass UnifiedDiffRenderer {\n\tconstructor(\n\t\tprivate readonly ctx: DiffRenderContext,\n\t\tprivate readonly entries: DiffEntry[],\n\t) {}\n\n\tprivate gapLine(entry: { hidden: number }, width: number): string {\n\t\treturn padRenderedLineWidth(this.ctx.fg(\"muted\", formatGapLabel(entry.hidden)), width);\n\t}\n\n\tprivate omittedLine(entry: { count: number }, width: number): string {\n\t\treturn padRenderedLineWidth(this.ctx.fg(\"muted\", formatOmittedLabel(entry.count)), width);\n\t}\n\n\trender(width: number): string[] {\n\t\tconst safeWidth = Math.max(20, width);\n\t\tconst prefixWidth = 1 + 1 + this.ctx.lineNumberWidth + 2; // marker + space + gutter + 2 spaces\n\t\tconst codeWidth = Math.max(1, safeWidth - prefixWidth);\n\t\tconst lines: string[] = [];\n\n\t\tfor (const entry of this.entries) {\n\t\t\tif (entry.kind === \"gap\") {\n\t\t\t\tlines.push(this.gapLine(entry, safeWidth));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (entry.kind === \"omitted\") {\n\t\t\t\tlines.push(this.omittedLine(entry, safeWidth));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlines.push(...this.rowLines(entry.row, codeWidth, safeWidth));\n\t\t}\n\n\t\treturn lines;\n\t}\n\n\tprivate rowLines(row: SplitDiffRow, codeWidth: number, width: number): string[] {\n\t\tconst segments: Array<{ kind: CellLineKind; line: DiffLine }> = [];\n\t\tif (row.kind === \"changed\") {\n\t\t\tif (row.left) segments.push({ kind: \"remove\", line: row.left });\n\t\t\tif (row.right) segments.push({ kind: \"add\", line: row.right });\n\t\t} else if (row.kind === \"added\" && row.right) {\n\t\t\tsegments.push({ kind: \"add\", line: row.right });\n\t\t} else if (row.kind === \"removed\" && row.left) {\n\t\t\tsegments.push({ kind: \"remove\", line: row.left });\n\t\t} else {\n\t\t\tconst line = row.left ?? row.right;\n\t\t\tif (line) segments.push({ kind: \"context\", line });\n\t\t}\n\n\t\tconst out: string[] = [];\n\t\tfor (const segment of segments) {\n\t\t\tout.push(...this.segmentLines(segment.kind, segment.line, codeWidth, width));\n\t\t}\n\t\treturn out;\n\t}\n\n\tprivate segmentLines(kind: CellLineKind, line: DiffLine, codeWidth: number, width: number): string[] {\n\t\tconst isAdd = kind === \"add\";\n\t\tconst isRemove = kind === \"remove\";\n\t\tconst blank = line.line === \"\";\n\t\t// Blank added/removed lines render like context (no tinted band), but the\n\t\t// +/- marker still shows that a line was inserted/removed.\n\t\tconst visualKind: CellLineKind = kind === \"context\" || blank ? \"context\" : kind;\n\t\tconst markerChar = kind === \"context\" ? \" \" : isAdd ? \"+\" : \"-\";\n\t\tconst markerColor = isAdd ? \"toolDiffAdded\" : isRemove ? \"toolDiffRemoved\" : \"dim\";\n\t\tconst gutterColor = visualKind === \"context\" ? \"dim\" : isAdd ? \"toolDiffAdded\" : \"toolDiffRemoved\";\n\t\tconst gutter = line.lineNumber.trim().padStart(this.ctx.lineNumberWidth, \" \");\n\n\t\tconst firstPrefixAnsi = `${this.ctx.fg(markerColor, markerChar)} ${this.ctx.fg(gutterColor, gutter)} `;\n\t\tconst firstPrefixPlain = `${markerChar} ${gutter} `;\n\t\tconst contPrefixAnsi = `${this.ctx.fg(\"dim\", \" \")} ${this.ctx.fg(\"dim\", \" \".repeat(this.ctx.lineNumberWidth))} `;\n\t\tconst contPrefixPlain = ` ${\" \".repeat(1 + this.ctx.lineNumberWidth)} `;\n\n\t\tconst rowBg =\n\t\t\tvisualKind === \"add\"\n\t\t\t\t? this.ctx.palette.addRowBgAnsi\n\t\t\t\t: visualKind === \"remove\"\n\t\t\t\t\t? this.ctx.palette.removeRowBgAnsi\n\t\t\t\t\t: undefined;\n\n\t\tconst plainSegments = wrapPlainText(line.line, codeWidth);\n\t\tconst out: string[] = [];\n\n\t\tfor (let i = 0; i < plainSegments.length; i++) {\n\t\t\tconst prefixAnsi = i === 0 ? firstPrefixAnsi : contPrefixAnsi;\n\t\t\tconst prefixPlain = i === 0 ? firstPrefixPlain : contPrefixPlain;\n\t\t\tconst plainSegment = plainSegments[i] ?? \"\";\n\t\t\tlet segment = this.ctx.syntaxHighlight(plainSegment);\n\t\t\tsegment = fitToWidth(segment, codeWidth);\n\n\t\t\tlet rendered = prefixAnsi + segment;\n\t\t\tconst expectedWidth = safeVisibleWidth(prefixPlain) + codeWidth;\n\t\t\tconst currentWidth = safeVisibleWidth(stripAnsi(rendered));\n\t\t\tif (currentWidth < expectedWidth) {\n\t\t\t\trendered += \" \".repeat(expectedWidth - currentWidth);\n\t\t\t}\n\n\t\t\tif (rowBg) {\n\t\t\t\trendered = `${rowBg}${keepBackgroundAcrossResets(rendered, rowBg)}${this.ctx.containerBgAnsi}`;\n\t\t\t}\n\t\t\tout.push(padRenderedLineWidth(rendered, width));\n\t\t}\n\n\t\treturn out;\n\t}\n}\n\n// ── Split (side-by-side) diff renderer ─────────────────────────────\n\nclass SplitDiffRenderer {\n\tconstructor(\n\t\tprivate readonly ctx: DiffRenderContext,\n\t\tprivate readonly entries: DiffEntry[],\n\t) {}\n\n\tprivate getCellLineKind(kind: SplitDiffRow[\"kind\"], side: \"left\" | \"right\"): CellLineKind {\n\t\tif (kind === \"changed\") return side === \"left\" ? \"remove\" : \"add\";\n\t\tif (kind === \"removed\" && side === \"left\") return \"remove\";\n\t\tif (kind === \"added\" && side === \"right\") return \"add\";\n\t\treturn \"context\";\n\t}\n\n\tprivate getVisualLineKind(kind: SplitDiffRow[\"kind\"], side: \"left\" | \"right\", line?: DiffLine): CellLineKind {\n\t\tconst base = this.getCellLineKind(kind, side);\n\t\tif ((kind === \"added\" || kind === \"removed\") && (line?.line ?? \"\") === \"\") {\n\t\t\treturn \"context\";\n\t\t}\n\t\treturn base;\n\t}\n\n\tprivate getNumberColor(lineKind: CellLineKind): \"toolDiffRemoved\" | \"toolDiffAdded\" | \"dim\" {\n\t\tif (lineKind === \"remove\") return \"toolDiffRemoved\";\n\t\tif (lineKind === \"add\") return \"toolDiffAdded\";\n\t\treturn \"dim\";\n\t}\n\n\tprivate getRowBackground(lineKind: CellLineKind): string | undefined {\n\t\tif (lineKind === \"add\") return this.ctx.palette.addRowBgAnsi;\n\t\tif (lineKind === \"remove\") return this.ctx.palette.removeRowBgAnsi;\n\t\treturn undefined;\n\t}\n\n\tprivate getEmphasisBackground(lineKind: CellLineKind): string | undefined {\n\t\tif (lineKind === \"add\") return this.ctx.palette.addEmphasisBgAnsi;\n\t\tif (lineKind === \"remove\") return this.ctx.palette.removeEmphasisBgAnsi;\n\t\treturn undefined;\n\t}\n\n\tprivate getCellFillBackground(kind: SplitDiffRow[\"kind\"], side: \"left\" | \"right\"): string | undefined {\n\t\tswitch (kind) {\n\t\t\tcase \"changed\":\n\t\t\t\treturn side === \"left\" ? this.ctx.palette.removeRowBgAnsi : this.ctx.palette.addRowBgAnsi;\n\t\t\tcase \"removed\":\n\t\t\t\treturn side === \"left\" ? this.ctx.palette.removeRowBgAnsi : undefined;\n\t\t\tcase \"added\":\n\t\t\t\treturn side === \"right\" ? this.ctx.palette.addRowBgAnsi : undefined;\n\t\t\tdefault:\n\t\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate blankCell(kind: SplitDiffRow[\"kind\"], side: \"left\" | \"right\", columnWidth: number): string {\n\t\tconst lineKind = this.getCellLineKind(kind, side);\n\t\tconst markerChar = lineKind === \"add\" || lineKind === \"remove\" ? \"▌\" : \" \";\n\t\tconst markerColor =\n\t\t\tlineKind === \"add\" ? \"toolDiffAdded\" : lineKind === \"remove\" ? \"toolDiffRemoved\" : \"borderMuted\";\n\t\tconst marker = this.ctx.fg(markerColor, markerChar);\n\t\tconst lineNumber = this.ctx.fg(\"dim\", \" \".repeat(this.ctx.lineNumberWidth));\n\t\tconst divider = this.ctx.fg(\"borderMuted\", \" │ \");\n\t\tconst prefix = `${marker} ${lineNumber}${divider}`;\n\t\tconst prefixPlain = `${markerChar} ${\" \".repeat(this.ctx.lineNumberWidth)} │ `;\n\t\tconst tailWidth = Math.max(0, columnWidth - safeVisibleWidth(prefixPlain));\n\t\tlet rendered = prefix + \" \".repeat(tailWidth);\n\n\t\tconst bg = this.getCellFillBackground(kind, side);\n\t\tif (!bg) return padRenderedLineWidth(rendered, columnWidth);\n\t\trendered = `${bg}${keepBackgroundAcrossResets(rendered, bg)}${this.ctx.containerBgAnsi}`;\n\t\treturn padRenderedLineWidth(rendered, columnWidth);\n\t}\n\n\tprivate formatCellLines(\n\t\tkind: SplitDiffRow[\"kind\"],\n\t\tside: \"left\" | \"right\",\n\t\tline: DiffLine | undefined,\n\t\tcolumnWidth: number,\n\t): string[] {\n\t\tif (!line) return [this.blankCell(kind, side, columnWidth)];\n\n\t\tconst lineKind = this.getVisualLineKind(kind, side, line);\n\t\tconst markerChar = lineKind === \"add\" || lineKind === \"remove\" ? \"▌\" : \" \";\n\t\tconst markerColor =\n\t\t\tlineKind === \"add\" ? \"toolDiffAdded\" : lineKind === \"remove\" ? \"toolDiffRemoved\" : \"borderMuted\";\n\t\tconst lineNumber = line.lineNumber.trim().padStart(this.ctx.lineNumberWidth, \" \");\n\n\t\tconst firstPrefixAnsi =\n\t\t\tthis.ctx.fg(markerColor, markerChar) +\n\t\t\t\" \" +\n\t\t\tthis.ctx.fg(this.getNumberColor(lineKind), lineNumber) +\n\t\t\tthis.ctx.fg(\"borderMuted\", \" │ \");\n\t\tconst firstPrefixPlain = `${markerChar} ${lineNumber} │ `;\n\n\t\tconst contPrefixAnsi =\n\t\t\tthis.ctx.fg(markerColor, markerChar) +\n\t\t\t\" \" +\n\t\t\tthis.ctx.fg(\"dim\", \" \".repeat(this.ctx.lineNumberWidth)) +\n\t\t\tthis.ctx.fg(\"borderMuted\", \" │ \");\n\t\tconst contPrefixPlain = `${markerChar} ${\" \".repeat(this.ctx.lineNumberWidth)} │ `;\n\n\t\tconst codeWidth = Math.max(1, columnWidth - safeVisibleWidth(firstPrefixPlain));\n\t\tconst rowBg = this.getRowBackground(lineKind);\n\t\tconst emphasisBg = this.getEmphasisBackground(lineKind);\n\n\t\tconst plainSegments = wrapPlainText(line.line, codeWidth);\n\t\tconst lines: string[] = [];\n\t\tconst spans = this.ctx.inlineSpans(line);\n\n\t\tlet consumed = 0;\n\t\tfor (let i = 0; i < plainSegments.length; i++) {\n\t\t\tconst prefixAnsi = i === 0 ? firstPrefixAnsi : contPrefixAnsi;\n\t\t\tconst prefixPlain = i === 0 ? firstPrefixPlain : contPrefixPlain;\n\t\t\tconst plainSegment = plainSegments[i] ?? \"\";\n\t\t\tlet segment = this.ctx.syntaxHighlight(plainSegment);\n\n\t\t\tif (spans.length > 0 && emphasisBg) {\n\t\t\t\tconst segmentStart = consumed;\n\t\t\t\tfor (let si = spans.length - 1; si >= 0; si--) {\n\t\t\t\t\tconst span = spans[si];\n\t\t\t\t\tif (!span) continue;\n\t\t\t\t\tconst localStart = Math.max(0, span.start - segmentStart);\n\t\t\t\t\tconst localEnd = Math.min(plainSegment.length, span.end - segmentStart);\n\t\t\t\t\tif (localEnd > localStart) {\n\t\t\t\t\t\tsegment = applyBackgroundToVisibleRange(\n\t\t\t\t\t\t\tsegment,\n\t\t\t\t\t\t\tlocalStart,\n\t\t\t\t\t\t\tlocalEnd,\n\t\t\t\t\t\t\temphasisBg,\n\t\t\t\t\t\t\trowBg ?? this.ctx.containerBgAnsi,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsegment = fitToWidth(segment, codeWidth);\n\t\t\tlet rendered = prefixAnsi + segment;\n\n\t\t\t// Defensive pad if prefix widths diverge because of unicode widths\n\t\t\tconst expectedWidth = safeVisibleWidth(prefixPlain) + codeWidth;\n\t\t\tconst currentWidth = safeVisibleWidth(stripAnsi(rendered));\n\t\t\tif (currentWidth < expectedWidth) {\n\t\t\t\trendered += \" \".repeat(expectedWidth - currentWidth);\n\t\t\t}\n\n\t\t\tif (rowBg) {\n\t\t\t\trendered = `${rowBg}${keepBackgroundAcrossResets(rendered, rowBg)}${this.ctx.containerBgAnsi}`;\n\t\t\t}\n\t\t\tlines.push(padRenderedLineWidth(rendered, columnWidth));\n\t\t\tconsumed += plainSegment.length;\n\t\t}\n\n\t\treturn lines;\n\t}\n\n\tprivate gapLine(entry: { hidden: number }, width: number): string {\n\t\treturn padRenderedLineWidth(this.ctx.fg(\"muted\", formatGapLabel(entry.hidden)), width);\n\t}\n\n\tprivate omittedLine(entry: { count: number }, width: number): string {\n\t\treturn padRenderedLineWidth(this.ctx.fg(\"muted\", formatOmittedLabel(entry.count)), width);\n\t}\n\n\trender(width: number): string[] {\n\t\tconst safeWidth = Math.max(20, width);\n\t\tconst columnSeparator = this.ctx.fg(\"borderMuted\", \" │ \");\n\t\tconst separatorWidth = safeVisibleWidth(stripAnsi(columnSeparator));\n\t\tconst leftWidth = Math.max(20, Math.floor((safeWidth - separatorWidth) / 2));\n\t\tconst rightWidth = Math.max(20, safeWidth - separatorWidth - leftWidth);\n\n\t\tconst formatBorderCell = (columnWidth: number, junction: string): string => {\n\t\t\tconst safeColumnWidth = Math.max(1, columnWidth);\n\t\t\tconst chars = \"─\".repeat(safeColumnWidth).split(\"\");\n\t\t\tconst dividerIndex = this.ctx.lineNumberWidth + 3;\n\t\t\tif (dividerIndex >= 0 && dividerIndex < chars.length) {\n\t\t\t\tchars[dividerIndex] = junction;\n\t\t\t}\n\t\t\treturn this.ctx.fg(\"borderMuted\", chars.join(\"\"));\n\t\t};\n\n\t\tconst formatHeaderCell = (label: string, columnWidth: number): string => {\n\t\t\t// Keep marker+space columns, then place label inside the line-number column.\n\t\t\tconst markerPad = \" \";\n\t\t\tconst lineNumberLabel = fitToWidth(label, this.ctx.lineNumberWidth);\n\t\t\tconst prefixAnsi =\n\t\t\t\tthis.ctx.fg(\"borderMuted\", markerPad) + this.ctx.fg(\"dim\", lineNumberLabel) + this.ctx.fg(\"borderMuted\", \" │ \");\n\t\t\tconst prefixPlain = `${markerPad}${stripAnsi(lineNumberLabel)} │ `;\n\t\t\tconst codeWidth = Math.max(0, columnWidth - safeVisibleWidth(prefixPlain));\n\t\t\treturn padRenderedLineWidth(prefixAnsi + \" \".repeat(codeWidth), columnWidth);\n\t\t};\n\n\t\tconst lines: string[] = [];\n\t\tlines.push(\n\t\t\tpadRenderedLineWidth(\n\t\t\t\tformatBorderCell(leftWidth, \"┬\") + this.ctx.fg(\"borderMuted\", \"─┬─\") + formatBorderCell(rightWidth, \"┬\"),\n\t\t\t\tsafeWidth,\n\t\t\t),\n\t\t);\n\t\tlines.push(\n\t\t\tpadRenderedLineWidth(\n\t\t\t\tformatHeaderCell(\"old\", leftWidth) + columnSeparator + formatHeaderCell(\"new\", rightWidth),\n\t\t\t\tsafeWidth,\n\t\t\t),\n\t\t);\n\n\t\tfor (const entry of this.entries) {\n\t\t\tif (entry.kind === \"gap\") {\n\t\t\t\tlines.push(this.gapLine(entry, safeWidth));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (entry.kind === \"omitted\") {\n\t\t\t\tlines.push(this.omittedLine(entry, safeWidth));\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst row = entry.row;\n\t\t\tconst leftCellLines = this.formatCellLines(row.kind, \"left\", row.left, leftWidth);\n\t\t\tconst rightCellLines = this.formatCellLines(row.kind, \"right\", row.right, rightWidth);\n\t\t\tconst rowHeight = Math.max(leftCellLines.length, rightCellLines.length);\n\n\t\t\tfor (let i = 0; i < rowHeight; i++) {\n\t\t\t\tconst fallbackKind: SplitDiffRow[\"kind\"] = row.kind === \"changed\" ? \"context\" : row.kind;\n\t\t\t\tconst leftCell = leftCellLines[i] ?? this.blankCell(fallbackKind, \"left\", leftWidth);\n\t\t\t\tconst rightCell = rightCellLines[i] ?? this.blankCell(fallbackKind, \"right\", rightWidth);\n\t\t\t\tconst joined = padRenderedLineWidth(leftCell + columnSeparator + rightCell, safeWidth);\n\t\t\t\tlines.push(joined);\n\t\t\t}\n\t\t}\n\n\t\tlines.push(\n\t\t\tpadRenderedLineWidth(\n\t\t\t\tformatBorderCell(leftWidth, \"┴\") + this.ctx.fg(\"borderMuted\", \"─┴─\") + formatBorderCell(rightWidth, \"┴\"),\n\t\t\t\tsafeWidth,\n\t\t\t),\n\t\t);\n\t\treturn lines;\n\t}\n}\n\n// ── AdaptiveDiffComponent ──────────────────────────────────────────\n\n/**\n * Boxed diff component that picks unified vs split layout per render width\n * (see `pickDiffMode`) and collapses long unchanged context instead of\n * truncating arbitrarily.\n */\nexport class AdaptiveDiffComponent implements Component {\n\tprivate cacheWidth: number | undefined;\n\tprivate cacheLines: string[] | undefined;\n\tprivate readonly ctx: DiffRenderContext;\n\tprivate readonly stats: { additions: number; removals: number };\n\tprivate readonly unified: UnifiedDiffRenderer;\n\tprivate readonly split: SplitDiffRenderer;\n\tprivate readonly collapsed: boolean;\n\n\tconstructor(\n\t\ttheme: SplitDiffTheme,\n\t\tprivate readonly rows: SplitDiffRow[],\n\t\tmaxRows: number,\n\t\tlanguage?: string,\n\t) {\n\t\tthis.ctx = new DiffRenderContext(theme, rows, language);\n\t\tthis.stats = { additions: 0, removals: 0 };\n\t\tfor (const row of rows) {\n\t\t\tif (row.kind === \"added\" || row.kind === \"changed\") this.stats.additions++;\n\t\t\tif (row.kind === \"removed\" || row.kind === \"changed\") this.stats.removals++;\n\t\t}\n\t\tconst entries = planEntries(rows, maxRows);\n\t\tthis.collapsed = entries.some((entry) => entry.kind !== \"row\");\n\t\tthis.unified = new UnifiedDiffRenderer(this.ctx, entries);\n\t\tthis.split = new SplitDiffRenderer(this.ctx, entries);\n\t}\n\n\t/** True when any unchanged context was collapsed or rows were omitted. */\n\thasCollapsed(): boolean {\n\t\treturn this.collapsed;\n\t}\n\n\tmodeForWidth(width: number): DiffMode {\n\t\treturn pickDiffMode(this.stats, this.rows, Math.max(20, width));\n\t}\n\n\trender(width: number): string[] {\n\t\tif (this.cacheWidth === width && this.cacheLines) return this.cacheLines;\n\n\t\tconst safeWidth = Math.max(20, width);\n\t\tconst mode = this.modeForWidth(safeWidth);\n\t\tconst lines = mode === \"split\" ? this.split.render(safeWidth) : this.unified.render(safeWidth);\n\n\t\tthis.cacheWidth = width;\n\t\tthis.cacheLines = lines;\n\t\treturn lines;\n\t}\n\n\tinvalidate(): void {\n\t\tthis.cacheWidth = undefined;\n\t\tthis.cacheLines = undefined;\n\t}\n}\n","// Boxed fallback for tools without a dedicated renderer.\n// (component side only; no ToolExecutionComponent prototype patching).\n\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport type { BoxTheme, MetricResultLike } from \"../../../shared/box.js\";\nimport {\n\tformatBoxedRunningStatus,\n\tformatBoxedWords,\n\tformatToolName,\n\tformatToolOutputLine,\n\tformatToolParamLines,\n\tgetTextOutput,\n\trenderBoxedToolCall,\n\trenderBoxedToolResult,\n\tselectRenderLines,\n} from \"../../../shared/box.js\";\nimport { getStateElapsedMs, getToolsRenderConfig, isResultSeen } from \"./session-config.js\";\nimport { type BoxedToolContext, noteBoxedCallState, noteBoxedResultPhase, noteExecutionStart } from \"./shared.js\";\n\nconst MAX_FALLBACK_PREVIEW_LINES = 10;\n\nexport function renderFallbackCall(\n\ttoolName: unknown,\n\targs: Record<string, unknown>,\n\ttheme: BoxTheme,\n\tcontext: BoxedToolContext,\n): Component {\n\tnoteExecutionStart(context);\n\tnoteBoxedCallState(context);\n\treturn renderBoxedToolCall(theme, formatToolName(String(toolName ?? \"Tool\")), formatToolParamLines(args, theme), {\n\t\tisError: Boolean(context.isError),\n\t\tisPartial: Boolean(context.isPartial),\n\t\tisPending: Boolean(context.isPartial),\n\t\trunning: Boolean(context.executionStarted),\n\t\tresultSeen: isResultSeen(context.state),\n\t});\n}\n\nexport function renderFallbackResult(\n\t_toolName: unknown,\n\tresult: MetricResultLike,\n\toptions: { expanded: boolean; isPartial: boolean },\n\ttheme: BoxTheme,\n\tcontext: BoxedToolContext,\n): Component {\n\tconst firstResultPass = noteBoxedResultPhase(context, options.isPartial);\n\tconst isError = Boolean(context.isError);\n\tconst expanded = Boolean(options.expanded);\n\tconst maxLines = expanded ? getToolsRenderConfig().maxExpandedLines : MAX_FALLBACK_PREVIEW_LINES;\n\tconst output = getTextOutput(result);\n\tconst elapsedMs = getStateElapsedMs(context.state);\n\tconst { lines, omitted } = selectRenderLines(output, maxLines);\n\n\tif (options.isPartial) {\n\t\t// Streaming continuation into the open call box: no Response divider and\n\t\t// no metrics footer until the tool settles. The first partial pass renders\n\t\t// nothing so the pending/running call card stands alone.\n\t\tif (firstResultPass) return EMPTY_FALLBACK_RESULT;\n\t\tconst hasOutput = output.trim().length > 0;\n\t\treturn renderBoxedToolResult(\n\t\t\ttheme,\n\t\t\t() => {\n\t\t\t\tconst body = lines.map((line) => formatToolOutputLine(theme, line, \"toolOutput\"));\n\t\t\t\tif (!hasOutput) body.push(theme.fg(\"dim\", \"No output received yet\"));\n\t\t\t\treturn body;\n\t\t\t},\n\t\t\t{\n\t\t\t\tdividerLabel: \"Output\",\n\t\t\t\tshowDivider: hasOutput,\n\t\t\t\tfooterLines: [formatBoxedRunningStatus(theme, elapsedMs)],\n\t\t\t\tisPartial: true,\n\t\t\t},\n\t\t);\n\t}\n\n\treturn renderBoxedToolResult(\n\t\ttheme,\n\t\t() => {\n\t\t\tconst body = lines.map((line) => formatToolOutputLine(theme, line, isError ? \"error\" : \"toolOutput\"));\n\t\t\tif (expanded && omitted > 0) {\n\t\t\t\tbody.push(theme.fg(\"muted\", `… ${omitted} more lines omitted by render budget`));\n\t\t\t}\n\t\t\treturn body;\n\t\t},\n\t\t{\n\t\t\tfooterLines: [formatBoxedFooterWithElapsed(theme, elapsedMs, output)],\n\t\t\trenderLineBudget: maxLines,\n\t\t\t...(expanded || omitted <= 0 ? {} : { expandHint: \"Ctrl+O for more\" }),\n\t\t\tisError,\n\t\t\tisPartial: Boolean(options.isPartial),\n\t\t},\n\t);\n}\n\n/** First-partial-pass result: the pending/running call card stands alone. */\nconst EMPTY_FALLBACK_RESULT: Component = Object.freeze({\n\tinvalidate() {},\n\trender() {\n\t\treturn [];\n\t},\n});\n\nfunction formatBoxedFooterWithElapsed(theme: BoxTheme, elapsedMs: number | undefined, output: string): string {\n\tconst elapsed = elapsedMs === undefined ? \"--\" : `${(elapsedMs / 1000).toFixed(2)}s`;\n\tconst words = output.trim() ? formatBoxedWords(output) : \"\";\n\tconst parts = [theme.fg(\"text\", elapsed)];\n\tif (words) parts.push(theme.fg(\"dim\", words));\n\treturn parts.join(theme.fg(\"dim\", \" · \"));\n}\n\n// Re-exported for callers that need the tool-name label normalization.\nexport { formatToolName };\n","// Boxed find tool renderer.\n//\n// find calls render as a boxless tree panel — a lone find shows its parsed\n// output as a flat `Glob: <pattern> <N> files · in <path>` tree; consecutive\n// find calls group into one panel with per-member nested subtrees (see\n// batch.ts). Pending/failed calls without output fall back to a path row.\n\nimport { stripAnsi } from \"../../../shared/ansi.js\";\nimport { getTextOutput, shortenPath } from \"../../../shared/box.js\";\nimport {\n\ttype BatchToolMeta,\n\tEMPTY_BATCH_COMPONENT,\n\temptyBatchResult,\n\tregisterBatchCall,\n\tregisterBatchResult,\n\trenderBatchAwareCall,\n} from \"./batch.js\";\nimport { parseFindOutput } from \"./output-tree.js\";\nimport { type BoxedToolDefinition, noteExecutionStart } from \"./shared.js\";\n\nconst FIND_META: BatchToolMeta = Object.freeze({\n\ttoolName: \"find\",\n\tlabel: \"Find\",\n\theaderLabel: \"Glob\",\n});\n\nfunction pathLabel(rawPath: string): string {\n\tconst displayPath = String(rawPath ?? \".\");\n\treturn displayPath === \".\" || displayPath === \"\" ? \"current directory\" : shortenPath(displayPath);\n}\n\nfunction queryDetail(pattern: string, rawPath: string): string {\n\tconst path = pathLabel(rawPath);\n\treturn pattern ? `${pattern} in ${path}` : path;\n}\n\nexport const findTool: BoxedToolDefinition = {\n\tcall(args, theme, context) {\n\t\tnoteExecutionStart(context);\n\t\tconst pattern = String(args?.pattern ?? \"\");\n\t\tconst rawPath = String(args?.path ?? \".\");\n\t\tconst detail = queryDetail(pattern, rawPath);\n\t\tconst { isLeader, batch } = registerBatchCall(FIND_META, detail, context, {\n\t\t\tpattern,\n\t\t\tpathLabel: pathLabel(rawPath),\n\t\t});\n\t\tif (!isLeader) return EMPTY_BATCH_COMPONENT;\n\t\treturn renderBatchAwareCall(theme, batch);\n\t},\n\tresult(result, options, _theme, context) {\n\t\tconst output = stripAnsi(getTextOutput(result)).trimEnd();\n\t\tconst entries = context.isError ? undefined : parseFindOutput(output);\n\t\tregisterBatchResult(\n\t\t\tFIND_META,\n\t\t\t{\n\t\t\t\tisPartial: Boolean(options.isPartial),\n\t\t\t\tisError: Boolean(context.isError),\n\t\t\t\terrorText: context.isError ? output || undefined : undefined,\n\t\t\t\t...(entries !== undefined ? { entries } : {}),\n\t\t\t},\n\t\t\tcontext,\n\t\t);\n\t\treturn emptyBatchResult();\n\t},\n};\n","// Boxed ls tool renderer.\n//\n// ls calls render as a boxless tree panel — a lone ls shows its parsed output as\n// a flat `List: <N> files · in <path>` tree; consecutive ls calls group into one\n// panel with per-member nested subtrees (see batch.ts). Pending/failed calls\n// without output fall back to a path row.\n\nimport { stripAnsi } from \"../../../shared/ansi.js\";\nimport { getTextOutput, shortenPath } from \"../../../shared/box.js\";\nimport {\n\ttype BatchToolMeta,\n\tEMPTY_BATCH_COMPONENT,\n\temptyBatchResult,\n\tregisterBatchCall,\n\tregisterBatchResult,\n\trenderBatchAwareCall,\n} from \"./batch.js\";\nimport { parseLsOutput } from \"./output-tree.js\";\nimport { type BoxedToolDefinition, noteExecutionStart } from \"./shared.js\";\n\nconst LIST_META: BatchToolMeta = Object.freeze({\n\ttoolName: \"ls\",\n\tlabel: \"List\",\n\theaderLabel: \"List\",\n});\n\nfunction displayPath(rawPath: string): string {\n\tconst path = String(rawPath ?? \".\");\n\tif (path === \".\" || path === \"\") return \"current directory\";\n\treturn shortenPath(path);\n}\n\nexport const lsTool: BoxedToolDefinition = {\n\tcall(args, theme, context) {\n\t\tnoteExecutionStart(context);\n\t\tconst rawPath = String(args?.path ?? \".\");\n\t\tconst detail = displayPath(rawPath);\n\t\tconst { isLeader, batch } = registerBatchCall(LIST_META, detail, context, { pathLabel: detail });\n\t\tif (!isLeader) return EMPTY_BATCH_COMPONENT;\n\t\treturn renderBatchAwareCall(theme, batch);\n\t},\n\tresult(result, options, _theme, context) {\n\t\tconst output = stripAnsi(getTextOutput(result)).trimEnd();\n\t\tconst entries = context.isError ? undefined : parseLsOutput(output);\n\t\tregisterBatchResult(\n\t\t\tLIST_META,\n\t\t\t{\n\t\t\t\tisPartial: Boolean(options.isPartial),\n\t\t\t\tisError: Boolean(context.isError),\n\t\t\t\terrorText: context.isError ? output || undefined : undefined,\n\t\t\t\t...(entries !== undefined ? { entries } : {}),\n\t\t\t},\n\t\t\tcontext,\n\t\t);\n\t\treturn emptyBatchResult();\n\t},\n};\n","// Boxed quick-edit / substitute-edit / target-edit renderer.\n\nimport { getLanguageFromPath } from \"@earendil-works/pi-coding-agent\";\nimport { stripAnsi } from \"../../../shared/ansi.js\";\nimport {\n\ttype BoxTheme,\n\tformatBoxedRunningStatus,\n\tgetTextOutput,\n\trenderBoxedToolCall,\n\trenderBoxedToolResult,\n} from \"../../../shared/box.js\";\nimport { formatElapsedMs, getElapsedMs } from \"../../../shared/elapsed.js\";\nimport { AdaptiveDiffComponent, buildSplitRows, countDiffStats } from \"../../../shared/split-diff.js\";\nimport { getStateElapsedMs, isResultSeen } from \"./session-config.js\";\nimport {\n\ttype BoxedToolContext,\n\ttype BoxedToolDefinition,\n\tdisplayPath,\n\tnoteBoxedCallState,\n\tnoteBoxedResultPhase,\n\tnoteExecutionStart,\n\tstateElapsedMs,\n} from \"./shared.js\";\n\nconst MAX_HIGHLIGHT_DIFF_CHARS = 12000;\nconst MAX_HIGHLIGHT_DIFF_ROWS = 120;\n\n/** First-partial-pass result: the pending/running call card stands alone. */\nconst EMPTY_QUICK_EDIT_RESULT = Object.freeze({\n\tinvalidate() {},\n\trender() {\n\t\treturn [];\n\t},\n});\n\ninterface QuickEditToolConfig {\n\ttoolLabel: string;\n\tapplyingLabel: string;\n\tfallbackLabel: string;\n}\n\nconst QUICK_EDIT_TOOLS: Readonly<Record<string, QuickEditToolConfig>> = {\n\tquick_edit: {\n\t\ttoolLabel: \"Quick Edit\",\n\t\tapplyingLabel: \"quick-edit\",\n\t\tfallbackLabel: \"Quick edit applied\",\n\t},\n\tsubstitute_edit: {\n\t\ttoolLabel: \"Substitute Edit\",\n\t\tapplyingLabel: \"substitute-edit\",\n\t\tfallbackLabel: \"Substitute edit applied\",\n\t},\n\ttarget_edit: {\n\t\ttoolLabel: \"Target Edit\",\n\t\tapplyingLabel: \"target-edit\",\n\t\tfallbackLabel: \"Target edit applied\",\n\t},\n};\n\nexport function getQuickEditToolConfig(toolName: unknown): QuickEditToolConfig | undefined {\n\treturn typeof toolName === \"string\" ? QUICK_EDIT_TOOLS[toolName] : undefined;\n}\n\nfunction extractQuickEditDiff(text: string): string | undefined {\n\tconst lines = stripAnsi(text).replace(/\\r/g, \"\").split(\"\\n\");\n\tconst start = lines.indexOf(\"── diff ──\");\n\tif (start < 0) return undefined;\n\n\tconst diffLines: string[] = [];\n\tlet cumulativeDelta = 0;\n\tlet oldLine: number | undefined;\n\tlet newLine: number | undefined;\n\tlet chunkAdditions = 0;\n\tlet chunkRemovals = 0;\n\n\tconst finishChunk = () => {\n\t\tcumulativeDelta += chunkAdditions - chunkRemovals;\n\t\toldLine = undefined;\n\t\tnewLine = undefined;\n\t\tchunkAdditions = 0;\n\t\tchunkRemovals = 0;\n\t};\n\n\tfor (const line of lines.slice(start + 1)) {\n\t\tif (line === \"\") {\n\t\t\tfinishChunk();\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst headerMatch = line.match(/^:(\\d+)(?:-\\d+)?$/);\n\t\tif (headerMatch) {\n\t\t\tfinishChunk();\n\t\t\tconst startLine = Number.parseInt(headerMatch[1] ?? \"\", 10);\n\t\t\toldLine = startLine;\n\t\t\tnewLine = startLine + cumulativeDelta;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst match = line.match(/^([+-]) (.*)$/);\n\t\tif (match) {\n\t\t\tconst [, sign, content = \"\"] = match;\n\t\t\tlet gutter = \"\";\n\t\t\tif (sign === \"-\" && oldLine !== undefined) gutter = String(oldLine++);\n\t\t\tif (sign === \"+\" && newLine !== undefined) gutter = String(newLine++);\n\t\t\tif (!gutter) continue;\n\t\t\tif (sign === \"-\") chunkRemovals++;\n\t\t\tif (sign === \"+\") chunkAdditions++;\n\t\t\tdiffLines.push(`${sign} ${gutter} ${content}`);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (line === \"---\") break;\n\t}\n\n\treturn diffLines.length > 0 ? diffLines.join(\"\\n\") : undefined;\n}\n\n/** `Diff · +3 -0` divider label. */\nfunction quickEditDividerLabel(theme: BoxTheme, stats: { additions: number; removals: number }): string {\n\tconst plus = stats.additions > 0 ? theme.fg(\"toolDiffAdded\", `+${stats.additions}`) : theme.fg(\"dim\", \"+0\");\n\tconst minus = stats.removals > 0 ? theme.fg(\"toolDiffRemoved\", `-${stats.removals}`) : theme.fg(\"dim\", \"-0\");\n\treturn `Diff · ${plus} ${minus}`;\n}\n\n/** Quick-edit footer: `1 file · +3 -0`, prefixed with elapsed time when known. */\nfunction quickEditDiffFooter(\n\ttheme: BoxTheme,\n\tresult: { content?: readonly unknown[]; details?: unknown },\n\tcontext: BoxedToolContext,\n\tstats: { additions: number; removals: number },\n): string {\n\tconst elapsedMs = getElapsedMs(result) ?? getStateElapsedMs(context.state);\n\tconst parts: string[] = [];\n\tif (elapsedMs !== undefined) parts.push(theme.fg(\"text\", formatElapsedMs(elapsedMs)));\n\tconst plus = stats.additions > 0 ? theme.fg(\"toolDiffAdded\", `+${stats.additions}`) : theme.fg(\"dim\", \"+0\");\n\tconst minus = stats.removals > 0 ? theme.fg(\"toolDiffRemoved\", `-${stats.removals}`) : theme.fg(\"dim\", \"-0\");\n\tparts.push(theme.fg(\"dim\", \"1 file\"), `${plus} ${minus}`);\n\treturn parts.join(theme.fg(\"dim\", \" · \"));\n}\n\nfunction renderQuickEditResult(\n\t_toolName: string,\n\tresult: { content?: readonly unknown[]; details?: unknown },\n\toptions: { expanded: boolean; isPartial: boolean },\n\ttheme: BoxTheme,\n\tcontext: BoxedToolContext,\n\tconfig: QuickEditToolConfig,\n) {\n\tif (options.isPartial) {\n\t\tconst firstResultPass = noteBoxedResultPhase(context, options.isPartial);\n\t\tif (firstResultPass) return EMPTY_QUICK_EDIT_RESULT;\n\t\treturn renderBoxedToolResult(\n\t\t\ttheme,\n\t\t\t() => [`${theme.fg(\"dim\", \"↳\")} ${theme.fg(\"muted\", `Applying ${config.applyingLabel}...`)}`],\n\t\t\t{ showDivider: false, footerLines: [formatBoxedRunningStatus(theme, stateElapsedMs(context))], isPartial: true },\n\t\t);\n\t}\n\n\tconst output = getTextOutput(result);\n\tif (context.isError) {\n\t\treturn renderBoxedToolResult(theme, () => [theme.fg(\"error\", stripAnsi(output).trim() || \"Error\")], {\n\t\t\tfooterLines: [quickEditFooter(theme, context)],\n\t\t\tisError: true,\n\t\t});\n\t}\n\n\tconst diff = extractQuickEditDiff(output);\n\tif (!diff) {\n\t\tconst fallback = stripAnsi(output).trim() || config.fallbackLabel;\n\t\treturn renderBoxedToolResult(theme, () => [`${theme.fg(\"dim\", \"↳\")} ${theme.fg(\"muted\", fallback)}`], {\n\t\t\tfooterLines: [quickEditFooter(theme, context)],\n\t\t});\n\t}\n\n\tconst rows = buildSplitRows(diff);\n\tconst expanded = options.expanded;\n\tconst argPath = String(context?.args?.path ?? \"\");\n\tconst language = argPath ? getLanguageFromPath(argPath) : undefined;\n\tconst shouldHighlight =\n\t\tBoolean(language) && diff.length <= MAX_HIGHLIGHT_DIFF_CHARS && rows.length <= MAX_HIGHLIGHT_DIFF_ROWS;\n\tconst stats = countDiffStats(diff);\n\n\tconst maxRows = expanded ? 160 : 36;\n\tconst diffView = new AdaptiveDiffComponent(theme, rows, maxRows, shouldHighlight ? language : undefined);\n\tconst expandHint = !expanded && diffView.hasCollapsed() ? \"Ctrl+O more\" : undefined;\n\n\treturn renderBoxedToolResult(\n\t\ttheme,\n\t\t{\n\t\t\trender(width: number): string[] {\n\t\t\t\treturn diffView.render(width);\n\t\t\t},\n\t\t\tinvalidate(): void {\n\t\t\t\tdiffView.invalidate();\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdividerLabel: quickEditDividerLabel(theme, stats),\n\t\t\t...(expandHint ? { dividerRightLabel: expandHint } : {}),\n\t\t\tfooterLines: [quickEditDiffFooter(theme, result, context, stats)],\n\t\t},\n\t);\n}\n\nfunction quickEditFooter(theme: BoxTheme, context: BoxedToolContext): string {\n\tconst elapsedMs = getStateElapsedMs(context.state);\n\tconst parts: string[] = [];\n\tif (elapsedMs !== undefined) parts.push(theme.fg(\"text\", formatElapsedMs(elapsedMs)));\n\tparts.push(theme.fg(\"dim\", \"1 file\"));\n\treturn parts.join(theme.fg(\"dim\", \" · \"));\n}\n\nexport function quickEditTool(config: QuickEditToolConfig): BoxedToolDefinition {\n\treturn {\n\t\tcall(args, theme, context) {\n\t\t\tnoteExecutionStart(context);\n\t\t\tnoteBoxedCallState(context);\n\t\t\tconst detail = displayPath(String(args?.path ?? \"\"), context);\n\t\t\treturn renderBoxedToolCall(theme, config.toolLabel, [], {\n\t\t\t\theaderDetail: detail,\n\t\t\t\tisError: Boolean(context.isError),\n\t\t\t\tisPartial: Boolean(context.isPartial),\n\t\t\t\tisPending: Boolean(context.isPartial),\n\t\t\t\trunning: Boolean(context.executionStarted),\n\t\t\t\tresultSeen: isResultSeen(context.state),\n\t\t\t});\n\t\t},\n\t\tresult(result, options, theme, context) {\n\t\t\treturn renderQuickEditResult(config.toolLabel, result, options, theme, context, config);\n\t\t},\n\t};\n}\n","// Boxed read tool renderer\n// (renderCall/renderResult only; no tool re-registration).\n//\n// Read calls render as a boxless tree panel — a lone read is a batch of one,\n// consecutive reads group into one panel (see batch.ts). There is no boxed\n// single-call special case.\n\nimport { stripAnsi } from \"../../../shared/ansi.js\";\nimport { getTextOutput } from \"../../../shared/box.js\";\nimport {\n\ttype BatchToolMeta,\n\tEMPTY_BATCH_COMPONENT,\n\temptyBatchResult,\n\tregisterBatchCall,\n\tregisterBatchResult,\n\trenderBatchAwareCall,\n} from \"./batch.js\";\nimport { type BoxedToolDefinition, noteExecutionStart, pathRangeDetail } from \"./shared.js\";\n\nconst READ_META: BatchToolMeta = Object.freeze({\n\ttoolName: \"read\",\n\tlabel: \"Read\",\n});\n\nexport const readTool: BoxedToolDefinition = {\n\tcall(args, theme, context) {\n\t\tnoteExecutionStart(context);\n\t\tconst rawPath = String(args?.path ?? args?.file_path ?? \"\");\n\t\tconst detail = pathRangeDetail(rawPath, args?.offset, args?.limit, context);\n\t\tconst { isLeader, batch } = registerBatchCall(READ_META, detail, context);\n\t\tif (!isLeader) return EMPTY_BATCH_COMPONENT;\n\t\treturn renderBatchAwareCall(theme, batch);\n\t},\n\tresult(result, options, _theme, context) {\n\t\tconst output = stripAnsi(getTextOutput(result)).trimEnd();\n\t\tregisterBatchResult(\n\t\t\tREAD_META,\n\t\t\t{\n\t\t\t\tisPartial: Boolean(options.isPartial),\n\t\t\t\tisError: Boolean(context.isError),\n\t\t\t\terrorText: context.isError ? output || undefined : undefined,\n\t\t\t},\n\t\t\tcontext,\n\t\t);\n\t\treturn emptyBatchResult();\n\t},\n};\n","// Boxed write tool renderer\n// (renderCall/renderResult only).\n//\n// The write call renders a compact preview box: the file path in the top\n// border, the written content as numbered lines in the body (cat -n style),\n// and the metrics footer in the bottom border. The footer lives in the shared\n// renderer state — the result renderer stores it (elapsed + words), the call\n// component reads it at paint time and closes the box. The preview is capped\n// at the collapsed line budget with a `Ctrl+O for more` hint on the bottom\n// border when truncated; expanded shows the expanded budget. Errors keep the\n// plain open call box so the boxed error result never duplicates a box.\n\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport { stripAnsi } from \"../../../shared/ansi.js\";\nimport {\n\ttype BoxTheme,\n\tboxedToolWidthKey,\n\tgetTextOutput,\n\trenderBoxedToolResult,\n\trenderCompactBoxedToolCall,\n\treplaceTabs,\n} from \"../../../shared/box.js\";\nimport { getToolsRenderConfig } from \"./session-config.js\";\nimport {\n\ttype BoxedToolDefinition,\n\tclearFooterState,\n\tcompactCall,\n\tcompactFooterWithState,\n\tdisplayPath,\n\tnoteExecutionStart,\n\tresultFooterLines,\n} from \"./shared.js\";\n\n/** Right-side bottom-border hint shown when the compact preview is truncated. */\nconst WRITE_EXPAND_HINT = \"Ctrl+O for more\";\n\n/** Partial-pass result: the compact call keeps its `◌ Running` card. */\nconst EMPTY_WRITE_RESULT: Component = Object.freeze({\n\tinvalidate() {},\n\trender() {\n\t\treturn [];\n\t},\n});\n\ntype NumberedLine = { number: string; content: string };\n\n/**\n * Numbered preview lines for the written content, `cat -n` style: every split\n * line keeps its number (including a trailing empty line produced by a final\n * newline), right-aligned to the widest line number.\n */\nfunction numberedPreviewLines(content: string): NumberedLine[] {\n\tconst normalized = replaceTabs(String(content ?? \"\")).replace(/\\r/g, \"\");\n\tif (!normalized) return [];\n\tconst lines = normalized.split(\"\\n\");\n\tconst gutterWidth = Math.max(1, String(lines.length).length);\n\treturn lines.map((line, index) => ({\n\t\tnumber: String(index + 1).padStart(gutterWidth),\n\t\tcontent: line,\n\t}));\n}\n\n/** One boxed preview row: dim gutter + toolOutput content. */\nfunction formatNumberedLine(theme: BoxTheme, line: NumberedLine): string {\n\treturn `${theme.fg(\"borderMuted\", `${line.number} `)}${theme.fg(\"toolOutput\", line.content)}`;\n}\n\n/** Compact write box: path header, numbered content preview, metrics footer. */\nfunction renderWritePreviewBox(\n\ttheme: BoxTheme,\n\tdetailLine: string,\n\tcontent: string,\n\toptions: {\n\t\tstate?: Record<string, unknown>;\n\t\tisError: boolean;\n\t\tisPending: boolean;\n\t\trunning?: boolean;\n\t\texpanded: boolean;\n\t},\n): Component {\n\tconst preview = numberedPreviewLines(content);\n\tconst config = getToolsRenderConfig();\n\tconst budget = options.expanded ? config.maxExpandedLines : config.maxCollapsedLines;\n\tconst truncated = preview.length > budget;\n\n\treturn renderCompactBoxedToolCall(theme, \"Write\", detailLine, {\n\t\t...(options.state ? { state: options.state } : {}),\n\t\tisError: options.isError,\n\t\tisPending: options.isPending,\n\t\trunning: Boolean(options.running),\n\t\tbodyLines: () => {\n\t\t\tif (preview.length === 0) return [];\n\t\t\tconst shown = preview.slice(0, budget).map((line) => formatNumberedLine(theme, line));\n\t\t\tif (!truncated) return shown;\n\t\t\tconst omitted = preview.length - budget;\n\t\t\tconst note = options.expanded ? `… ${omitted} more lines omitted by render budget` : `… ${omitted} more lines`;\n\t\t\treturn [...shown, theme.fg(\"muted\", note)];\n\t\t},\n\t\t...(options.expanded || options.isPending || !truncated ? {} : { bottomRightLabel: WRITE_EXPAND_HINT }),\n\t});\n}\n\nexport const writeTool: BoxedToolDefinition = {\n\tcall(args, theme, context) {\n\t\tnoteExecutionStart(context);\n\t\tconst detail = displayPath(String(args?.path ?? args?.file_path ?? \"\"), context);\n\t\tconst detailLine = `${theme.fg(\"dim\", \"Path: \")}${detail}`;\n\t\t// On error keep the plain open box: the result renderer continues it with\n\t\t// the boxed error body, so call and result never duplicate a box.\n\t\tif (context.isError) {\n\t\t\treturn compactCall(theme, \"Write\", detailLine, {\n\t\t\t\tdetailKey: detail,\n\t\t\t\tcontext,\n\t\t\t});\n\t\t}\n\t\treturn renderWritePreviewBox(theme, detailLine, String(args?.content ?? \"\"), {\n\t\t\tstate: context.state,\n\t\t\tisError: Boolean(context.isError),\n\t\t\tisPending: Boolean(context.isPartial),\n\t\t\trunning: Boolean(context.executionStarted),\n\t\t\texpanded: Boolean(context.expanded),\n\t\t});\n\t},\n\tresult(result, options, theme, context) {\n\t\tclearFooterState(context);\n\t\tconst output = getTextOutput(result);\n\t\tconst detail = displayPath(String(context?.args?.path ?? context?.args?.file_path ?? \"\"), context);\n\t\tconst widthKey = boxedToolWidthKey(\"Write\", detail);\n\n\t\tif (context.isError) {\n\t\t\treturn renderBoxedToolResult(theme, () => [theme.fg(\"error\", stripAnsi(output).trim() || \"Error\")], {\n\t\t\t\twidthKey,\n\t\t\t\tfooterLines: resultFooterLines(theme, result, context),\n\t\t\t\tisError: true,\n\t\t\t});\n\t\t}\n\n\t\t// While the result is still streaming, don't stamp a metrics footer into\n\t\t// the shared state: the compact call keeps its `◌ Running` card and only\n\t\t// closes with `elapsed · words` once the tool settles.\n\t\tif (options.isPartial) return EMPTY_WRITE_RESULT;\n\n\t\t// Success (compact and expanded): the preview box closes with the metrics\n\t\t// footer stored into the shared renderer state; the result adds nothing.\n\t\treturn compactFooterWithState(theme, result, context);\n\t},\n};\n","// Boxed tool renderer dispatcher.\n//\n// Maps Pi tool names to their boxed call/result renderers and falls back to a\n// boxed generic renderer for unknown tools. The dispatcher is invoked from the\n// tool decoration owner when tools.style === \"compact-box\".\n\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport type { BoxTheme } from \"../../../shared/box.js\";\nimport { bashTool } from \"./bash.js\";\nimport { closeActiveBatch, isBatchableTool } from \"./batch.js\";\nimport { editTool } from \"./edit.js\";\nimport { renderFallbackCall, renderFallbackResult } from \"./fallback.js\";\nimport { findTool } from \"./find.js\";\nimport { grepTool } from \"./grep.js\";\nimport { lsTool } from \"./ls.js\";\nimport { getQuickEditToolConfig, quickEditTool } from \"./quick-edit.js\";\nimport { readTool } from \"./read.js\";\nimport type { BoxedToolContext, BoxedToolDefinition } from \"./shared.js\";\nimport { writeTool } from \"./write.js\";\n\nfunction quickEditToolFor(toolName: string): BoxedToolDefinition {\n\tconst config = getQuickEditToolConfig(toolName);\n\tif (!config) throw new Error(`missing quick-edit config for ${toolName}`);\n\treturn quickEditTool(config);\n}\n\nconst REGISTRY: Readonly<Record<string, BoxedToolDefinition>> = {\n\tread: readTool,\n\twrite: writeTool,\n\tedit: editTool,\n\tbash: bashTool,\n\tls: lsTool,\n\tfind: findTool,\n\tgrep: grepTool,\n\tquick_edit: quickEditToolFor(\"quick_edit\"),\n\tsubstitute_edit: quickEditToolFor(\"substitute_edit\"),\n\ttarget_edit: quickEditToolFor(\"target_edit\"),\n};\n\nexport function hasBoxedRenderer(toolName: unknown): boolean {\n\treturn typeof toolName === \"string\" && Object.hasOwn(REGISTRY, toolName);\n}\n\nexport function renderBoxedToolCall(\n\ttoolName: unknown,\n\targs: Record<string, unknown>,\n\ttheme: BoxTheme,\n\tcontext: BoxedToolContext,\n): Component {\n\t// Any non-batchable tool call is a batch boundary: the next quiet call starts\n\t// a fresh batch instead of joining the previous one.\n\tif (!isBatchableTool(toolName)) closeActiveBatch();\n\tconst tool = typeof toolName === \"string\" ? REGISTRY[toolName] : undefined;\n\tif (tool) return tool.call(args, theme, context);\n\treturn renderFallbackCall(toolName, args, theme, context);\n}\n\nexport function renderBoxedToolResult(\n\ttoolName: unknown,\n\tresult: { content?: readonly unknown[]; details?: unknown },\n\toptions: { expanded: boolean; isPartial: boolean },\n\ttheme: BoxTheme,\n\tcontext: BoxedToolContext,\n): Component {\n\tconst tool = typeof toolName === \"string\" ? REGISTRY[toolName] : undefined;\n\tif (tool) return tool.result(result, options, theme, context);\n\treturn renderFallbackResult(toolName, result, options, theme, context);\n}\n","export type CompatibilitySubtype =\n\t| \"native-assistant-message\"\n\t| \"native-compaction-message\"\n\t| \"native-branch-message\"\n\t| \"native-skill-message\"\n\t| \"native-custom-message\"\n\t| \"tool-call-renderer\"\n\t| \"tool-result-renderer\";\n\ntype CompatibilityShape = \"supported\" | \"unsupported\" | \"conflict\" | \"installed\" | \"skipped\";\n\nexport interface CompatibilityRecord {\n\tfeature: \"messages\" | \"tools\";\n\tsubtype: CompatibilitySubtype;\n\ttarget: object;\n\towner: object;\n\tmethod: PropertyKey;\n\toriginalIdentity: unknown;\n\toriginalDescriptor?: PropertyDescriptor;\n\tinstalledIdentity?: unknown;\n\tpiVersion: string;\n\tversionRange: string;\n\tshape: CompatibilityShape;\n\tdiagnostic?: string | undefined;\n\tgeneration: number;\n\tdisposed: boolean;\n\tdisposer: () => void;\n}\n\nexport interface InstallResult {\n\tstatus: \"installed\" | \"already-installed\" | \"skipped\";\n\trecord: CompatibilityRecord;\n\treason?: string | undefined;\n}\n\nconst recordsByOwner = new WeakMap<object, Map<PropertyKey, CompatibilityRecord>>();\nlet generation = 0;\nlet registryTestHooks: {\n\tafterWrite?: () => void;\n\tdefineProperty?: (target: object, key: PropertyKey, descriptor: PropertyDescriptor) => boolean;\n} = {};\nexport function __setCompatibilityRegistryTestHooks(hooks: typeof registryTestHooks): () => void {\n\tconst previous = registryTestHooks;\n\tregistryTestHooks = hooks;\n\treturn () => {\n\t\tregistryTestHooks = previous;\n\t};\n}\n\nfunction ownerRecords(owner: object): Map<PropertyKey, CompatibilityRecord> {\n\tlet records = recordsByOwner.get(owner);\n\tif (!records) {\n\t\trecords = new Map();\n\t\trecordsByOwner.set(owner, records);\n\t}\n\treturn records;\n}\n\nexport function currentGeneration(): number {\n\treturn generation;\n}\nexport function nextGeneration(): number {\n\treturn ++generation;\n}\nexport function getCompatibilityRecords(owner: object): readonly CompatibilityRecord[] {\n\treturn [...(recordsByOwner.get(owner)?.values() ?? [])];\n}\n\nfunction safeRead(target: object, method: PropertyKey): unknown {\n\ttry {\n\t\treturn Reflect.get(target, method);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction skippedRecord(options: {\n\tfeature: CompatibilityRecord[\"feature\"];\n\tsubtype: CompatibilitySubtype;\n\ttarget: object;\n\tmethod: PropertyKey;\n\tpiVersion: string;\n\tversionRange: string;\n\tshape: CompatibilityShape;\n\tdiagnostic: string;\n\tgeneration: number;\n\toriginalIdentity?: unknown;\n}): CompatibilityRecord {\n\treturn {\n\t\t...options,\n\t\towner: options.target,\n\t\toriginalIdentity: Object.hasOwn(options, \"originalIdentity\")\n\t\t\t? options.originalIdentity\n\t\t\t: safeRead(options.target, options.method),\n\t\tdisposed: true,\n\t\tdisposer: () => {},\n\t};\n}\n\nfunction descriptorMatches(actual: PropertyDescriptor | undefined, expected: PropertyDescriptor | undefined): boolean {\n\tif (!actual || !expected) return actual === expected;\n\treturn (\n\t\tactual.value === expected.value &&\n\t\tactual.get === expected.get &&\n\t\tactual.set === expected.set &&\n\t\tactual.writable === expected.writable &&\n\t\tactual.enumerable === expected.enumerable &&\n\t\tactual.configurable === expected.configurable\n\t);\n}\n\nfunction restoreExact(record: CompatibilityRecord): { ok: boolean; diagnostic?: string } {\n\ttry {\n\t\tconst current = Object.getOwnPropertyDescriptor(record.target, record.method);\n\t\tconst installed = current?.value === record.installedIdentity;\n\t\tif (!installed) return { ok: false, diagnostic: \"current owner changed; native/later owner preserved\" };\n\t\tconst defineProperty = registryTestHooks.defineProperty ?? Reflect.defineProperty;\n\t\tconst wrote = record.originalDescriptor\n\t\t\t? defineProperty(record.target, record.method, record.originalDescriptor)\n\t\t\t: Reflect.deleteProperty(record.target, record.method);\n\t\tif (!wrote) return { ok: false, diagnostic: \"exact descriptor restoration was rejected\" };\n\t\tif (!descriptorMatches(Object.getOwnPropertyDescriptor(record.target, record.method), record.originalDescriptor))\n\t\t\treturn { ok: false, diagnostic: \"post-restore descriptor validation failed\" };\n\t\treturn { ok: true };\n\t} catch (error) {\n\t\treturn { ok: false, diagnostic: `restore failed: ${error instanceof Error ? error.message : String(error)}` };\n\t}\n}\n\nfunction inspectCurrent(\n\ttarget: object,\n\tmethod: PropertyKey,\n): { current?: unknown; descriptor?: PropertyDescriptor; error?: string } {\n\ttry {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(target, method);\n\t\treturn {\n\t\t\tcurrent: descriptor && \"value\" in descriptor ? descriptor.value : undefined,\n\t\t\t...(descriptor ? { descriptor } : {}),\n\t\t};\n\t} catch (error) {\n\t\treturn { error: `cannot inspect target: ${error instanceof Error ? error.message : String(error)}` };\n\t}\n}\n\nfunction skippedResult(\n\toptions: Parameters<typeof installDelegatingPatch>[0],\n\tshape: CompatibilityShape,\n\treason: string,\n\toriginalIdentity?: unknown,\n): InstallResult {\n\treturn {\n\t\tstatus: \"skipped\",\n\t\treason,\n\t\trecord: skippedRecord({ ...options, shape, diagnostic: reason, originalIdentity }),\n\t};\n}\n\nfunction expectedIdentityMatches(options: Parameters<typeof installDelegatingPatch>[0], current: unknown): boolean {\n\tconst expected =\n\t\toptions.hasExpectedIdentity === true ||\n\t\t(options.hasExpectedIdentity === undefined && options.expectedIdentity !== undefined);\n\treturn !expected || current === options.expectedIdentity;\n}\n\nfunction validateInstall(\n\toptions: Parameters<typeof installDelegatingPatch>[0],\n\tcurrent: unknown,\n\texisting: CompatibilityRecord | undefined,\n\townDescriptor: PropertyDescriptor | undefined,\n): InstallResult | undefined {\n\tif (!options.shape) return skippedResult(options, \"unsupported\", options.diagnostic ?? \"unsupported shape\", current);\n\tconst conflict = existing && activeConflict(existing, current, options.generation);\n\tif (conflict) return conflict;\n\tif (typeof current !== \"function\")\n\t\treturn skippedResult(\n\t\t\toptions,\n\t\t\townDescriptor ? \"unsupported\" : \"skipped\",\n\t\t\t\"target property is not callable\",\n\t\t\tcurrent,\n\t\t);\n\tif (!expectedIdentityMatches(options, current))\n\t\treturn skippedResult(options, \"conflict\", \"current owner is not the captured pristine native identity\", current);\n\treturn undefined;\n}\n\nfunction activeConflict(\n\texisting: CompatibilityRecord,\n\tcurrent: unknown,\n\tgeneration: number,\n): InstallResult | undefined {\n\tif (existing.disposed) return undefined;\n\tif (existing.installedIdentity === current && existing.generation === generation)\n\t\treturn { status: \"already-installed\", record: existing };\n\tconst reason =\n\t\texisting.installedIdentity === current\n\t\t\t? \"active wrapper belongs to a different generation\"\n\t\t\t: \"owner changed after pi-style installation\";\n\treturn {\n\t\tstatus: \"skipped\",\n\t\treason,\n\t\trecord: skippedRecord({\n\t\t\tfeature: existing.feature,\n\t\t\tsubtype: existing.subtype,\n\t\t\ttarget: existing.target,\n\t\t\tmethod: existing.method,\n\t\t\tpiVersion: existing.piVersion,\n\t\t\tversionRange: existing.versionRange,\n\t\t\tshape: \"conflict\",\n\t\t\tdiagnostic: reason,\n\t\t\tgeneration,\n\t\t\toriginalIdentity: current,\n\t\t}),\n\t};\n}\n\nexport function installDelegatingPatch(options: {\n\tfeature: CompatibilityRecord[\"feature\"];\n\tsubtype: CompatibilitySubtype;\n\ttarget: object;\n\tmethod: PropertyKey;\n\tpiVersion: string;\n\tversionRange: string;\n\tshape: boolean;\n\tgeneration: number;\n\texpectedIdentity?: unknown;\n\thasExpectedIdentity?: boolean;\n\tdiagnostic?: string | undefined;\n\tdelegate: (original: unknown, thisArg: object, args: unknown[]) => unknown;\n}): InstallResult {\n\tconst { target, method } = options;\n\tconst inspection = inspectCurrent(target, method);\n\tif (inspection.error) return skippedResult(options, \"skipped\", inspection.error);\n\tconst current = inspection.current;\n\tconst records = ownerRecords(target);\n\tconst validation = validateInstall(options, current, records.get(method), inspection.descriptor);\n\tif (validation) return validation;\n\tconst originalDescriptor = Object.getOwnPropertyDescriptor(target, method);\n\tconst originalIdentity = current;\n\tlet active = true;\n\tconst installed = function (this: object, ...args: unknown[]): unknown {\n\t\tif (!active) return Reflect.apply(originalIdentity as (...values: unknown[]) => unknown, this, args);\n\t\treturn options.delegate(originalIdentity, this, args);\n\t};\n\tconst record: CompatibilityRecord = {\n\t\tfeature: options.feature,\n\t\tsubtype: options.subtype,\n\t\ttarget,\n\t\towner: target,\n\t\tmethod,\n\t\toriginalIdentity,\n\t\t...(originalDescriptor ? { originalDescriptor } : {}),\n\t\tinstalledIdentity: installed,\n\t\tpiVersion: options.piVersion,\n\t\tversionRange: options.versionRange,\n\t\tshape: \"installed\",\n\t\tdiagnostic: options.diagnostic,\n\t\tgeneration: options.generation,\n\t\tdisposed: false,\n\t\tdisposer: () => {},\n\t};\n\ttry {\n\t\tObject.defineProperty(installed, \"__piStyleCompatibilityRecord\", { value: record, configurable: false });\n\t\tconst descriptor = { ...originalDescriptor, value: installed };\n\t\tconst wrote = Reflect.defineProperty(target, method, descriptor);\n\t\tregistryTestHooks.afterWrite?.();\n\t\tconst currentDescriptor = Object.getOwnPropertyDescriptor(target, method);\n\t\tif (!wrote) return skippedResult(options, \"skipped\", \"installation write was rejected\");\n\t\tif (!descriptorMatches(currentDescriptor, descriptor)) {\n\t\t\tif (currentDescriptor?.value === installed) {\n\t\t\t\tconst rollback = restoreExact({ ...record, installedIdentity: installed });\n\t\t\t\tif (!rollback.ok) {\n\t\t\t\t\trecord.diagnostic = rollback.diagnostic;\n\t\t\t\t\trecords.set(method, record);\n\t\t\t\t\treturn { status: \"skipped\", reason: rollback.diagnostic, record };\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst reason =\n\t\t\t\tcurrentDescriptor?.value === installed\n\t\t\t\t\t? \"wrapper-owned descriptor mismatch rolled back\"\n\t\t\t\t\t: \"later owner preserved after post-write mismatch\";\n\t\t\treturn {\n\t\t\t\tstatus: \"skipped\",\n\t\t\t\treason,\n\t\t\t\trecord: skippedRecord({\n\t\t\t\t\t...options,\n\t\t\t\t\tshape: \"conflict\",\n\t\t\t\t\tdiagnostic: reason,\n\t\t\t\t\toriginalIdentity: currentDescriptor?.value,\n\t\t\t\t}),\n\t\t\t};\n\t\t}\n\t\trecords.set(method, record);\n\t\trecord.disposer = () => {\n\t\t\tif (record.disposed) return;\n\t\t\tconst restored = restoreExact(record);\n\t\t\tif (!restored.ok) {\n\t\t\t\trecord.diagnostic = restored.diagnostic;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tactive = false;\n\t\t\trecord.disposed = true;\n\t\t\trecords.delete(method);\n\t\t};\n\t\treturn { status: \"installed\", record };\n\t} catch (error) {\n\t\tconst currentDescriptor = Object.getOwnPropertyDescriptor(target, method);\n\t\tconst rollback =\n\t\t\tcurrentDescriptor?.value === installed ? restoreExact({ ...record, installedIdentity: installed }) : { ok: true };\n\t\tconst reason = `installation rolled back (${rollback.diagnostic ?? \"ok\"}): ${error instanceof Error ? error.message : String(error)}`;\n\t\tif (currentDescriptor?.value === installed && !rollback.ok) {\n\t\t\trecord.diagnostic = reason;\n\t\t\trecords.set(method, record);\n\t\t\trecord.disposer = () => {\n\t\t\t\tif (record.disposed) return;\n\t\t\t\tconst retry = restoreExact(record);\n\t\t\t\tif (!retry.ok) {\n\t\t\t\t\trecord.diagnostic = retry.diagnostic;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tactive = false;\n\t\t\t\trecord.disposed = true;\n\t\t\t\trecords.delete(method);\n\t\t\t};\n\t\t\treturn { status: \"installed\", reason, record };\n\t\t}\n\t\treturn { status: \"skipped\", reason, record: skippedRecord({ ...options, shape: \"skipped\", diagnostic: reason }) };\n\t}\n}\n","import { isTierCAuthorized } from \"../domain/config-authorization.js\";\nimport type { NormalizedPiStyleConfig } from \"../domain/config-types.js\";\nimport {\n\ttype CompatibilityCleanupResult,\n\ttype CompatibilityProbeReport,\n\tdetectPiVersion,\n\tdisposePiCompatibilityProbe,\n\tprobePiCompatibility,\n} from \"./compatibility-probe.js\";\n\nexport interface CompatibilityCoordinator {\n\tcaptureAuthorization(\n\t\tcoreFlag: boolean,\n\t\tassistantFlag: boolean,\n\t\tspecialBlocksFlag: boolean,\n\t\ttoolsFlag: boolean,\n\t\tasciiFlag: boolean,\n\t): void;\n\tstate(config: NormalizedPiStyleConfig): Readonly<Record<string, unknown>>;\n\tinstall(\n\t\tconfig: NormalizedPiStyleConfig,\n\t\ttui: boolean,\n\t\tproductGate?: \"omitted\" | \"allow\" | \"deny\",\n\t): CompatibilityProbeReport | undefined;\n\tdispose(): CompatibilityCleanupResult;\n\treadonly report: CompatibilityProbeReport | undefined;\n}\n\nexport function createCompatibilityCoordinator(dispose = disposePiCompatibilityProbe): CompatibilityCoordinator {\n\tlet report: CompatibilityProbeReport | undefined;\n\tlet cleanupPending = false;\n\tlet authorization:\n\t\t| {\n\t\t\t\tcore: boolean;\n\t\t\t\tassistant: boolean;\n\t\t\t\tspecialBlocks: boolean;\n\t\t\t\ttools: boolean;\n\t\t\t\tascii: boolean;\n\t\t }\n\t\t| undefined;\n\treturn {\n\t\tget report() {\n\t\t\treturn report;\n\t\t},\n\t\tcaptureAuthorization(core, assistant, specialBlocks, tools, ascii) {\n\t\t\tauthorization = { core, assistant, specialBlocks, tools, ascii };\n\t\t},\n\t\tstate(config) {\n\t\t\tconst version = detectPiVersion();\n\t\t\tconst messagesConfigured =\n\t\t\t\tconfig.enabled && config.messages.enabled && (config.messages.assistantPrefix || config.messages.specialBlocks);\n\t\t\tconst toolsConfigured = config.enabled && config.tools.enabled;\n\t\t\tconst surface = (\n\t\t\t\tfeature: \"messages\" | \"tools\",\n\t\t\t\tconfigured: boolean,\n\t\t\t\tsurfaceAuthorized: boolean,\n\t\t\t\tsubtype?: string,\n\t\t\t) => {\n\t\t\t\tconst records =\n\t\t\t\t\treport?.unsupported.filter((item) =>\n\t\t\t\t\t\tfeature === \"messages\" ? item.subtype.includes(\"message\") : item.subtype.includes(\"tool\"),\n\t\t\t\t\t) ?? [];\n\t\t\t\tconst failed = records.some((item) => /identity|failed|unsupported shape/i.test(item.reason));\n\t\t\t\tconst fallback = records.some((item) => /fallback|authorization|disabled/i.test(item.reason));\n\t\t\t\tconst authorized = Boolean(authorization?.core && surfaceAuthorized);\n\t\t\t\tconst installedRecord = report?.recordSnapshots.some(\n\t\t\t\t\t(item) => item.feature === feature && !item.disposed && (subtype === undefined || item.subtype === subtype),\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tconfigured,\n\t\t\t\t\tauthorized,\n\t\t\t\t\tinstalled: Boolean(installedRecord && !failed && authorized && configured),\n\t\t\t\t\tconflicted: records.some((item) => item.reason.includes(\"owner\")),\n\t\t\t\t\tfailed,\n\t\t\t\t\tcleanupPending,\n\t\t\t\t\tnativeFallback: fallback,\n\t\t\t\t\t...(authorized ? {} : { awaitingAuthorization: true }),\n\t\t\t\t};\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tconfigured: messagesConfigured || toolsConfigured,\n\t\t\t\tauthorized: authorization?.core ?? false,\n\t\t\t\tinstalled: report !== undefined,\n\t\t\t\tconflicted: report?.unsupported.some((item) => item.reason.includes(\"identity\")) ?? false,\n\t\t\t\tfailed: report?.unsupported.some((item) => item.reason.includes(\"failed\")) ?? false,\n\t\t\t\tcleanupPending,\n\t\t\t\tnativeFallbacks: report?.unsupported.filter((item) => item.reason.includes(\"fallback\")).length ?? 0,\n\t\t\t\tpiVersion: version.version ?? report?.piVersion ?? \"unknown\",\n\t\t\t\tversionRange: report?.versionRange ?? \">=0.83.0 <0.84.0\",\n\t\t\t\tassistantMessage: surface(\n\t\t\t\t\t\"messages\",\n\t\t\t\t\tconfig.enabled && config.messages.enabled && config.messages.assistantPrefix,\n\t\t\t\t\tBoolean(authorization?.assistant),\n\t\t\t\t\t\"native-assistant-message\",\n\t\t\t\t),\n\t\t\t\ttools: surface(\"tools\", config.enabled && config.tools.enabled, Boolean(authorization?.tools)),\n\t\t\t\tspecialBlocks: surface(\n\t\t\t\t\t\"messages\",\n\t\t\t\t\tconfig.enabled && config.messages.enabled && config.messages.specialBlocks,\n\t\t\t\t\tBoolean(authorization?.core),\n\t\t\t\t),\n\t\t\t};\n\t\t},\n\t\tinstall(config, tui, productGate = \"omitted\") {\n\t\t\tconst productDenied = productGate === \"deny\";\n\t\t\tif (cleanupPending && !report) cleanupPending = false;\n\t\t\tif (cleanupPending || !tui || !config.enabled || !authorization?.core || productDenied) return undefined;\n\t\t\tconst certifiedHost = detectPiVersion().version === \"0.83.0\";\n\t\t\tconst assistantEnabled =\n\t\t\t\tauthorization.assistant &&\n\t\t\t\tisTierCAuthorized({\n\t\t\t\t\tcertifiedHost,\n\t\t\t\t\tcoreFlag: authorization.core,\n\t\t\t\t\tsurfaceFlag: true,\n\t\t\t\t\tsurface: \"assistantMessage\",\n\t\t\t\t\tconfig,\n\t\t\t\t});\n\t\t\tconst specialBlocksEnabled =\n\t\t\t\tauthorization.specialBlocks &&\n\t\t\t\tisTierCAuthorized({\n\t\t\t\t\tcertifiedHost,\n\t\t\t\t\tcoreFlag: authorization.core,\n\t\t\t\t\tsurfaceFlag: true,\n\t\t\t\t\tsurface: \"specialBlocks\",\n\t\t\t\t\tconfig,\n\t\t\t\t});\n\t\t\tconst messagesEnabled = (assistantEnabled || specialBlocksEnabled) && config.messages.enabled;\n\t\t\tconst toolsEnabled =\n\t\t\t\tauthorization.tools &&\n\t\t\t\tisTierCAuthorized({ certifiedHost, coreFlag: authorization.core, surfaceFlag: true, surface: \"tools\", config });\n\t\t\tif (!messagesEnabled && !toolsEnabled) return undefined;\n\t\t\tconst detected = detectPiVersion();\n\t\t\treport = probePiCompatibility(detected.version, {\n\t\t\t\tconfig: {\n\t\t\t\t\t...config,\n\t\t\t\t\tmessages: {\n\t\t\t\t\t\t...config.messages,\n\t\t\t\t\t\tenabled: messagesEnabled,\n\t\t\t\t\t\tassistantPrefix: assistantEnabled,\n\t\t\t\t\t\tspecialBlocks: messagesEnabled && config.messages.specialBlocks && specialBlocksEnabled,\n\t\t\t\t\t},\n\t\t\t\t\ttools: {\n\t\t\t\t\t\t...config.tools,\n\t\t\t\t\t\tenabled: toolsEnabled,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tmessageSnapshot: {\n\t\t\t\t\tassistantPrefix: authorization.ascii ? \"[assistant] \" : \"│ \",\n\t\t\t\t\tassistantEnabled,\n\t\t\t\t},\n\t\t\t\ttoolSnapshot: {\n\t\t\t\t\tcallMarker: authorization.ascii ? \"[tool] \" : \"[tool] \",\n\t\t\t\t\tresultMarker: authorization.ascii ? \"[result] \" : \"[tool:result] \",\n\t\t\t\t\tstyle: config.tools.style === \"compact-box\" ? \"compact-box\" : \"marker\",\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn report;\n\t\t},\n\t\tdispose() {\n\t\t\tif (!report) {\n\t\t\t\tcleanupPending = false;\n\t\t\t\treturn { complete: true, retryablePrototypeRecords: 0, retryableToolRecords: 0 };\n\t\t\t}\n\t\t\tconst result = dispose(report);\n\t\t\tcleanupPending = !result.complete;\n\t\t\tif (result.complete) {\n\t\t\t\treport = undefined;\n\t\t\t\tcleanupPending = false;\n\t\t\t}\n\t\t\treturn result;\n\t\t},\n\t};\n}\n","import type { ConfigFilePort } from \"../app/config-storage.js\";\nimport { readScopedConfig } from \"../app/config-storage.js\";\nimport type { ConfigDiagnostic } from \"../domain/config-diagnostics.js\";\nimport { resolveConfigDetailed } from \"../domain/config-normalization.js\";\n\nexport interface SessionFlagReader {\n\tgetFlag(name: string): unknown;\n}\nexport interface SessionAuthorization {\n\tcore: boolean;\n\tassistant: boolean;\n\tspecialBlocks: boolean;\n\ttools: boolean;\n\tascii: boolean;\n}\nexport interface ProductPolicy {\n\treadonly corePatchGate: \"omitted\" | \"allow\" | \"deny\";\n}\nexport interface ConfigSourceAdapter {\n\tsetSession(cwd: string, trusted: boolean): void;\n\tload(): Promise<{\n\t\tconfig: unknown;\n\t\tdiagnostics: readonly ConfigDiagnostic[];\n\t\tsources: Readonly<Record<string, string>>;\n\t\trawSources?: {\n\t\t\tdefaults?: unknown;\n\t\t\tglobal?: unknown;\n\t\t\tproject?: unknown;\n\t\t\tenvironment?: Record<string, string | undefined>;\n\t\t};\n\t\tproductPolicy?: ProductPolicy;\n\t}>;\n}\n\nfunction sessionOverrides(_pi: SessionFlagReader): Record<string, unknown> {\n\treturn {};\n}\n\n/** Product policy is deny-only: any explicit false wins; true never grants Tier C. */\nexport function resolveProductGate(\n\tglobal: unknown,\n\tproject: unknown,\n\tsession: unknown,\n\tprojectTrusted: boolean,\n): ProductPolicy {\n\tconst values = [global, projectTrusted ? project : undefined, session];\n\tfor (const value of values) {\n\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) continue;\n\t\tconst compatibility = (value as Record<string, unknown>).compatibility;\n\t\tif (!compatibility || typeof compatibility !== \"object\" || Array.isArray(compatibility)) continue;\n\t\tif (!Object.hasOwn(compatibility, \"allowCorePatches\")) continue;\n\t\tconst leaf = (compatibility as Record<string, unknown>).allowCorePatches;\n\t\tif (leaf === false) return { corePatchGate: \"deny\" };\n\t}\n\treturn { corePatchGate: \"omitted\" };\n}\n\nexport function readSessionAuthorization(pi: SessionFlagReader): SessionAuthorization {\n\treturn {\n\t\tcore: pi.getFlag(\"pi-style-core-patches\") === true,\n\t\tassistant: pi.getFlag(\"pi-style-message-assistant\") === true,\n\t\tspecialBlocks: pi.getFlag(\"pi-style-message-special-blocks\") === true,\n\t\ttools: pi.getFlag(\"pi-style-tools\") === true,\n\t\tascii: pi.getFlag(\"pi-style-ascii\") === true,\n\t};\n}\n\nexport function createConfigSourceAdapter(\n\tpi: SessionFlagReader,\n\tport: ConfigFilePort,\n\tpaths: (cwd: string) => { globalPath: string; projectPath: string },\n): ConfigSourceAdapter {\n\tlet trusted = true;\n\tlet currentCwd = process.cwd();\n\treturn {\n\t\tsetSession(nextCwd, nextTrusted) {\n\t\t\tcurrentCwd = nextCwd;\n\t\t\ttrusted = nextTrusted;\n\t\t},\n\t\tasync load() {\n\t\t\tconst storage = paths(currentCwd);\n\t\t\tconst global = await readScopedConfig(port, storage.globalPath);\n\t\t\tconst project = trusted ? await readScopedConfig(port, storage.projectPath) : undefined;\n\t\t\tconst resolved = resolveConfigDetailed({\n\t\t\t\tglobal: global.value,\n\t\t\t\tproject: project?.value,\n\t\t\t\tprojectTrusted: trusted,\n\t\t\t\tenvironment: process.env,\n\t\t\t\tsession: sessionOverrides(pi),\n\t\t\t});\n\t\t\tconst productPolicy = resolveProductGate(global.value, project?.value, sessionOverrides(pi), trusted);\n\t\t\treturn {\n\t\t\t\tconfig: resolved.config,\n\t\t\t\tdiagnostics: [...global.diagnostics, ...(project?.diagnostics ?? []), ...resolved.diagnostics],\n\t\t\t\tsources: resolved.sources,\n\t\t\t\trawSources: { global: global.value, project: project?.value, environment: process.env },\n\t\t\t\tproductPolicy,\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport { sessionOverrides };\n","import type { RuntimeInstallationState } from \"../app/runtime.js\";\nimport type { NormalizedPiStyleConfig } from \"../domain/config-types.js\";\nimport type { CompatibilityCoordinator } from \"./compatibility-coordinator.js\";\n\nexport function buildOperationalState(\n\tconfig: NormalizedPiStyleConfig,\n\tauthorization: { core: boolean; productCorePatchGate?: string },\n\tcompatibility: CompatibilityCoordinator,\n\tinstallationState?: RuntimeInstallationState,\n\tproductCorePatchGate?: string,\n): Readonly<Record<string, unknown>> {\n\treturn {\n\t\tcompatibility: {\n\t\t\t...compatibility.state(config),\n\t\t\tconfiguredByProduct: config.messages.enabled || config.tools.enabled,\n\t\t},\n\t\tinstallations: installationState ?? {\n\t\t\tstatus: config.enabled && config.statusLine.enabled ? \"active\" : \"disabled\",\n\t\t\teditor: config.enabled && config.editor.enabled ? \"active\" : \"disabled\",\n\t\t\tstartup: config.enabled && config.startup.mode !== \"off\" ? \"active\" : \"disabled\",\n\t\t},\n\t\tprovider: { status: \"unavailable\", recovery: \"inject a capability-safe provider\" },\n\t\tauthorization: {\n\t\t\tcore: authorization.core,\n\t\t\t...(authorization.productCorePatchGate ? { productCorePatchGate: authorization.productCorePatchGate } : {}),\n\t\t\t...(productCorePatchGate ? { productCorePatchGate } : {}),\n\t\t},\n\t};\n}\n","import type { SourceInfo, ToolInfo } from \"@earendil-works/pi-coding-agent\";\n\n/**\n * Startup resource collection for the pi/ adapter layer. Runs once at session\n * start, outside any render path, and produces the bounded tool details that\n * the startup surface renders.\n */\n\nconst CORE_TOOL_SOURCE_LABEL = \"core\";\n\nfunction stripKnownExtension(name: string): string {\n\treturn name.replace(/\\.(?:mjs|cjs|js|jsx|ts|tsx)$/i, \"\");\n}\n\nfunction compactSourcePathLabel(path: string): string {\n\tconst trimmed = path.trim();\n\tif (!trimmed) return \"\";\n\tconst synthetic = /^<([^:>]+)(?::[^>]*)?>$/.exec(trimmed);\n\tif (synthetic?.[1]) return synthetic[1];\n\tconst segments = trimmed\n\t\t.replace(/\\\\/g, \"/\")\n\t\t.split(\"/\")\n\t\t.filter((segment) => segment.length > 0 && segment !== \".\" && segment !== \"~\");\n\tconst last = segments.at(-1) ?? trimmed;\n\tif (/^index\\.(?:mjs|cjs|js|jsx|ts|tsx)$/i.test(last) && segments.length > 1) {\n\t\treturn segments[segments.length - 2] ?? last;\n\t}\n\treturn stripKnownExtension(last);\n}\n\nfunction compactPackageSourceLabel(source: string): string {\n\tif (source.startsWith(\"npm:\")) return source.slice(\"npm:\".length) || source;\n\tif (source.startsWith(\"git:\")) return compactSourcePathLabel(source.replace(/\\.git(?:#.*)?$/i, \"\")) || source;\n\treturn source;\n}\n\n/** Compact display label for a tool's source. */\nexport function toolSourceLabel(sourceInfo: SourceInfo | undefined): string {\n\tif (!sourceInfo || typeof sourceInfo !== \"object\") return CORE_TOOL_SOURCE_LABEL;\n\tconst source = typeof sourceInfo.source === \"string\" ? sourceInfo.source : \"\";\n\tif (source === \"builtin\") return CORE_TOOL_SOURCE_LABEL;\n\tif (source === \"sdk\") return \"sdk\";\n\tif (source.startsWith(\"npm:\") || source.startsWith(\"git:\")) return compactPackageSourceLabel(source);\n\tconst baseDir = typeof sourceInfo.baseDir === \"string\" ? sourceInfo.baseDir : \"\";\n\tif (baseDir) return compactSourcePathLabel(baseDir) || source || \"extension\";\n\tconst path = typeof sourceInfo.path === \"string\" ? sourceInfo.path : \"\";\n\tif (path) return compactSourcePathLabel(path) || source || \"extension\";\n\treturn source || \"extension\";\n}\n\n/**\n * Map registered tools to the bounded `{ source, name }` shape used by the\n * startup tools panel. When Pi reports active tool names, only those are kept;\n * an empty/absent active list keeps all registered tools so the panel is not\n * silently empty. Returns undefined when there is nothing to show.\n */\nexport function collectToolDetails(\n\tactiveNames: readonly string[] | undefined,\n\ttools: readonly ToolInfo[] | undefined,\n): { source: string; name: string }[] | undefined {\n\tif (!tools || tools.length === 0) return undefined;\n\tconst activeSet = activeNames && activeNames.length > 0 ? new Set(activeNames) : undefined;\n\tconst details: { source: string; name: string }[] = [];\n\tfor (const tool of tools) {\n\t\tif (typeof tool?.name !== \"string\" || tool.name.trim().length === 0) continue;\n\t\tif (activeSet && !activeSet.has(tool.name)) continue;\n\t\tdetails.push({ source: toolSourceLabel(tool.sourceInfo), name: tool.name.trim() });\n\t}\n\treturn details.length > 0 ? details : undefined;\n}\n","import type { SessionEntry } from \"@earendil-works/pi-coding-agent\";\nimport type { UsageSnapshot } from \"../domain/status.js\";\n\n/**\n * Minimal structural view of Pi's session manager: only the entry iteration\n * needed to aggregate cumulative usage. `ExtensionContext.sessionManager`\n * satisfies this shape.\n */\nexport interface SessionUsageSource {\n\tgetEntries(): readonly SessionEntry[];\n}\n\ninterface UsageTotals {\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\tcost: number;\n}\n\n/**\n * Aggregate cumulative token/cost usage from all session entries, mirroring\n * Pi's native footer: assistant messages always carry usage, tool results and\n * compaction/branch summaries carry it when available.\n */\nexport function usageFromSession(session: SessionUsageSource): UsageSnapshot | undefined {\n\tconst totals: UsageTotals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };\n\tlet sawUsage = false;\n\tfor (const entry of session.getEntries()) {\n\t\tif (entry.type === \"message\") {\n\t\t\tif (entry.message.role !== \"assistant\" && entry.message.role !== \"toolResult\") continue;\n\t\t\tconst usage = \"usage\" in entry.message ? entry.message.usage : undefined;\n\t\t\tif (!usage) continue;\n\t\t\taddUsage(totals, usage);\n\t\t\tsawUsage = true;\n\t\t} else if ((entry.type === \"branch_summary\" || entry.type === \"compaction\") && entry.usage) {\n\t\t\taddUsage(totals, entry.usage);\n\t\t\tsawUsage = true;\n\t\t}\n\t}\n\tif (!sawUsage) return undefined;\n\treturn {\n\t\tinputTokens: totals.input,\n\t\toutputTokens: totals.output,\n\t\tcacheReadTokens: totals.cacheRead,\n\t\tcacheWriteTokens: totals.cacheWrite,\n\t\tcost: totals.cost,\n\t\tsubscriptionMode: \"unknown\",\n\t\tstreaming: false,\n\t};\n}\n\nfunction addUsage(\n\ttotals: UsageTotals,\n\tusage: { input: number; output: number; cacheRead: number; cacheWrite: number; cost: { total: number } },\n): void {\n\ttotals.input += usage.input;\n\ttotals.output += usage.output;\n\ttotals.cacheRead += usage.cacheRead;\n\ttotals.cacheWrite += usage.cacheWrite;\n\ttotals.cost += usage.cost.total;\n}\n","import type { ExtensionAPI, ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport type { StatusSnapshot } from \"../domain/status.js\";\nimport { closeActiveBatch } from \"../features/tools/boxed/batch.js\";\nimport { registerPiStyleCommand } from \"./commands.js\";\nimport { type CompatibilityTestHooks, createPiStyleSessionCoordinator } from \"./session-coordinator.js\";\nimport { usageFromSession } from \"./session-usage.js\";\n\n/** Usage patch that omits the key when no session usage exists (exact optional types). */\nfunction usagePatch(ctx: ExtensionContext): StatusSnapshot {\n\tconst usage = usageFromSession(ctx.sessionManager);\n\treturn usage ? { usage } : {};\n}\n\n/**\n * Add Pi's read-only tools (grep/find/ls) to the active tool set if they are\n * registered. Preserves any other active tools (e.g. extension tools).\n * Only calls setActiveTools when something actually changed.\n */\nfunction activateReadOnlyTools(pi: ExtensionAPI): void {\n\tconst available = new Set(pi.getAllTools().map((tool) => tool.name));\n\tconst active = new Set(pi.getActiveTools());\n\tlet changed = false;\n\tfor (const name of [\"grep\", \"find\", \"ls\"] as const) {\n\t\tif (available.has(name) && !active.has(name)) {\n\t\t\tactive.add(name);\n\t\t\tchanged = true;\n\t\t}\n\t}\n\tif (changed) pi.setActiveTools([...active]);\n}\n\nlet compatibilityTestHooks: CompatibilityTestHooks = {};\nexport function __setCompatibilityTestHooks(hooks: CompatibilityTestHooks): () => void {\n\tconst previous = compatibilityTestHooks;\n\tcompatibilityTestHooks = hooks;\n\treturn () => {\n\t\tcompatibilityTestHooks = previous;\n\t};\n}\n\n/** Thin Pi adapter: register flags, commands, and forward lifecycle events. */\nexport default function piStyleExtension(pi: ExtensionAPI): void {\n\t// The core/message/tool surfaces are default-on (safe: fingerprint-certified against\n\t// exact Pi 0.83.0, fail-closed elsewhere, conflict-preserving). The OFF switch is the\n\t// product gate `compatibility.allowCorePatches: false` (or `enabled: false`) in config.\n\tfor (const [name, description] of [\n\t\t[\"pi-style-core-patches\", \"Enable pi-style message/tool core patches\"],\n\t\t[\"pi-style-message-assistant\", \"Enable pi-style assistant message prefix\"],\n\t\t[\"pi-style-message-special-blocks\", \"Enable pi-style boxed compaction/skill/branch/custom message blocks\"],\n\t\t[\"pi-style-tools\", \"Enable pi-style tool renderer decoration\"],\n\t\t[\"pi-style-readonly-tools\", \"Enable grep/find/ls read-only tools in the active tool set\"],\n\t] as const)\n\t\tpi.registerFlag(name, { type: \"boolean\", description, default: true });\n\t// ASCII markers stay opt-in; unicode markers are the default.\n\tpi.registerFlag(\"pi-style-ascii\", { type: \"boolean\", description: \"Use ASCII pi-style markers\" });\n\tconst coordinator = createPiStyleSessionCoordinator(pi, compatibilityTestHooks);\n\tregisterPiStyleCommand(pi, coordinator.app);\n\tpi.on(\"session_start\", async (event, ctx) => {\n\t\t// Pi only activates read/bash/edit/write by default; grep/find/ls are\n\t\t// registered but inactive (kept out of the model's tool list to keep the\n\t\t// core small). Activate them so the TUI shows them and the model can call\n\t\t// them directly, mirroring Claude Code's glob/grep/read tool set.\n\t\tif (pi.getFlag(\"pi-style-readonly-tools\") === true) {\n\t\t\tactivateReadOnlyTools(pi);\n\t\t}\n\t\tawait coordinator.start(event, ctx);\n\t});\n\tpi.on(\"agent_start\", () => coordinator.app.runtime.current?.dismissStartup());\n\tpi.on(\"input\", () => coordinator.app.runtime.current?.dismissStartup());\n\tpi.on(\"tool_execution_start\", () => coordinator.app.runtime.current?.dismissStartup());\n\tpi.on(\"model_select\", (event) =>\n\t\tcoordinator.app.update(\n\t\t\t{\n\t\t\t\tmodel: event.model.name || event.model.id,\n\t\t\t\t...(event.model.provider ? { provider: event.model.provider } : {}),\n\t\t\t\t...(event.model.reasoning !== undefined ? { reasoning: event.model.reasoning } : {}),\n\t\t\t},\n\t\t\t\"immediate\",\n\t\t),\n\t);\n\tpi.on(\"thinking_level_select\", (event) => coordinator.app.update({ thinkingLevel: event.level }, \"immediate\"));\n\tpi.on(\"session_info_changed\", (event) => coordinator.app.update({ sessionName: event.name }, \"coalesced\"));\n\tpi.on(\"message_start\", () => {\n\t\t// A new message is a batch boundary: quiet-tool (read/ls/find) calls of the\n\t\t// new message start a fresh batch instead of joining the previous one.\n\t\tcloseActiveBatch();\n\t\t// grep/bash tree panels are NOT cleared here: historical panels must keep\n\t\t// their state so Pi re-renders of previous messages (scroll/resume) stay\n\t\t// intact. Only session boundaries reset them (session-coordinator).\n\t});\n\tpi.on(\"message_update\", () => coordinator.app.update({}, \"coalesced\"));\n\t// Usage (tokens + cost) is aggregated from finalized session entries at\n\t// message/turn boundaries, mirroring Pi's native footer; per-chunk updates\n\t// stay usage-free to keep streaming cheap.\n\tpi.on(\"message_end\", (_event, ctx) => coordinator.app.update({ ...usagePatch(ctx) }, \"coalesced\"));\n\tpi.on(\"turn_end\", (_event, ctx) => coordinator.app.update({ ...usagePatch(ctx) }, \"deferred\"));\n\tpi.on(\"agent_settled\", (_event, ctx) => coordinator.app.update({ ...usagePatch(ctx) }, \"coalesced\"));\n\tpi.on(\"session_tree\", (_event, ctx) => coordinator.app.update({ ...usagePatch(ctx) }, \"deferred\"));\n\tpi.on(\"session_compact\", (_event, ctx) => coordinator.app.update({ ...usagePatch(ctx) }, \"deferred\"));\n\tpi.on(\"tool_result\", (event, ctx) => {\n\t\tif ([\"write\", \"edit\", \"bash\"].includes(event.toolName)) {\n\t\t\tcoordinator.app.runtime.current?.invalidateGit();\n\t\t\tcoordinator.app.update({ ...usagePatch(ctx) }, \"delayed-retry\");\n\t\t}\n\t});\n\tpi.on(\"user_bash\", (_event, ctx) => {\n\t\tcoordinator.app.runtime.current?.invalidateGit();\n\t\tcoordinator.app.update({ ...usagePatch(ctx) }, \"delayed-retry\");\n\t});\n\tpi.on(\"session_shutdown\", () => coordinator.shutdown());\n}\n"],"mappings":";AAAA,SAAS,QAAQ,MAAuB;AACvC,SAAO,QAAQ,OAAO,QAAQ;AAC/B;AAEA,IAAM,aAAa,CAAC,GAAG,IAAI,KAAK,KAAK,KAAK,GAAG;AAE7C,SAAS,cAAc,OAAgE;AACtF,MAAI,SAAS,KAAK,QAAQ,IAAI;AAE7B,UAAM,OAAO;AAAA,MACZ,CAAC,GAAG,GAAG,CAAC;AAAA,MACR,CAAC,KAAK,GAAG,CAAC;AAAA,MACV,CAAC,GAAG,KAAK,CAAC;AAAA,MACV,CAAC,KAAK,KAAK,CAAC;AAAA,MACZ,CAAC,GAAG,GAAG,GAAG;AAAA,MACV,CAAC,KAAK,GAAG,GAAG;AAAA,MACZ,CAAC,GAAG,KAAK,GAAG;AAAA,MACZ,CAAC,KAAK,KAAK,GAAG;AAAA,MACd,CAAC,KAAK,KAAK,GAAG;AAAA,MACd,CAAC,KAAK,GAAG,CAAC;AAAA,MACV,CAAC,GAAG,KAAK,CAAC;AAAA,MACV,CAAC,KAAK,KAAK,CAAC;AAAA,MACZ,CAAC,GAAG,GAAG,GAAG;AAAA,MACV,CAAC,KAAK,GAAG,GAAG;AAAA,MACZ,CAAC,GAAG,KAAK,GAAG;AAAA,MACZ,CAAC,KAAK,KAAK,GAAG;AAAA,IACf;AACA,UAAM,QAAQ,KAAK,KAAK,KAAK,CAAC,GAAG,GAAG,CAAC;AACrC,UAAM,CAAC,GAAG,GAAG,CAAC,IAAI;AAClB,WAAO,EAAE,GAAG,GAAG,EAAE;AAAA,EAClB;AACA,MAAI,SAAS,MAAM,QAAQ,KAAK;AAC/B,UAAM,OAAO,QAAQ;AACrB,WAAO;AAAA,MACN,GAAG,WAAW,KAAK,MA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AAG,GAAG,YAAY,CAAC,QAAQ,QAAQ,YAAY,IAAI,OAAO,EAAE,GAAG,WAAW,GAAG,EAAE,GAAG,UAAU,CAAC;AAC7F,KAAG,GAAG,iBAAiB,CAAC,QAAQ,QAAQ,YAAY,IAAI,OAAO,EAAE,GAAG,WAAW,GAAG,EAAE,GAAG,WAAW,CAAC;AACnG,KAAG,GAAG,gBAAgB,CAAC,QAAQ,QAAQ,YAAY,IAAI,OAAO,EAAE,GAAG,WAAW,GAAG,EAAE,GAAG,UAAU,CAAC;AACjG,KAAG,GAAG,mBAAmB,CAAC,QAAQ,QAAQ,YAAY,IAAI,OAAO,EAAE,GAAG,WAAW,GAAG,EAAE,GAAG,UAAU,CAAC;AACpG,KAAG,GAAG,eAAe,CAAC,OAAO,QAAQ;AACpC,QAAI,CAAC,SAAS,QAAQ,MAAM,EAAE,SAAS,MAAM,QAAQ,GAAG;AACvD,kBAAY,IAAI,QAAQ,SAAS,cAAc;AAC/C,kBAAY,IAAI,OAAO,EAAE,GAAG,WAAW,GAAG,EAAE,GAAG,eAAe;AAAA,IAC/D;AAAA,EACD,CAAC;AACD,KAAG,GAAG,aAAa,CAAC,QAAQ,QAAQ;AACnC,gBAAY,IAAI,QAAQ,SAAS,cAAc;AAC/C,gBAAY,IAAI,OAAO,EAAE,GAAG,WAAW,GAAG,EAAE,GAAG,eAAe;AAAA,EAC/D,CAAC;AACD,KAAG,GAAG,oBAAoB,MAAM,YAAY,SAAS,CAAC;AACvD;","names":["r","g","b","homedir","resolve","visibleWidth","truncated","record","homedir","resolve","fill","member","header","record","value","patch","dirname","join","formatElapsed","visibleWidth","visibleWidth","prompt","padding","promptWidth","prefix","continuation","body","renderedBody","marker","widthOf","segment","ownerMap","owners","snapshot","generation","generation","generation","generation","countWords","mergePatch","block","ESC","preview","pathLabel","displayPath","bold","renderErrorLines","readFileSync","dirname","join","fileURLToPath","visibleWidth","visibleWidth","highlightCode","ESC","BG_ANSI_PATTERN","oldNum","newNum","highlightCode","segment","marker","expandHint","pathLabel","displayPath","displayPath","getLanguageFromPath","MAX_HIGHLIGHT_DIFF_CHARS","MAX_HIGHLIGHT_DIFF_ROWS","getLanguageFromPath","expandHint","note","renderBoxedToolCall","renderBoxedToolResult","visibleWidth","record","renderBoxedToolCall","renderBoxedToolResult","args","record","shape","generation","fileURLToPath","readFile","readFileSync","dirname","join","generation","record","segment"]}
1
+ {"version":3,"sources":["../../extension-src/pi-style/shared/ansi.ts","../../extension-src/pi-style/shared/box.ts","../../extension-src/pi-style/shared/elapsed.ts","../../extension-src/pi-style/shared/render-budget.ts","../../extension-src/pi-style/shared/theme-extras.ts","../../extension-src/pi-style/features/tools/boxed/output-tree.ts","../../extension-src/pi-style/features/tools/boxed/session-config.ts","../../extension-src/pi-style/features/tools/boxed/batch.ts","../../extension-src/pi-style/domain/config-diagnostics.ts","../../extension-src/pi-style/domain/config-presets.ts","../../extension-src/pi-style/domain/config-types.ts","../../extension-src/pi-style/domain/status-presets.ts","../../extension-src/pi-style/domain/config-normalization.ts","../../extension-src/pi-style/domain/config-migrations.ts","../../extension-src/pi-style/app/config-storage.ts","../../extension-src/pi-style/app/command-service.ts","../../extension-src/pi-style/app/commands.ts","../../extension-src/pi-style/pi/config-host.ts","../../extension-src/pi-style/pi/commands.ts","../../extension-src/pi-style/pi/session-coordinator.ts","../../extension-src/pi-style/app/doctor.ts","../../extension-src/pi-style/domain/config-diff.ts","../../extension-src/pi-style/domain/status.ts","../../extension-src/pi-style/features/editor/index.ts","../../extension-src/pi-style/domain/theme.ts","../../extension-src/pi-style/features/startup/logo.ts","../../extension-src/pi-style/features/startup/index.ts","../../extension-src/pi-style/domain/status-renderer.ts","../../extension-src/pi-style/features/status-line/index.ts","../../extension-src/pi-style/shared/disposable-store.ts","../../extension-src/pi-style/app/providers.ts","../../extension-src/pi-style/app/render-scheduler.ts","../../extension-src/pi-style/app/snapshot.ts","../../extension-src/pi-style/app/runtime.ts","../../extension-src/pi-style/app/index.ts","../../extension-src/pi-style/features/messages/special-blocks.ts","../../extension-src/pi-style/features/messages/boxed-block.ts","../../extension-src/pi-style/features/tools/bash-execution.ts","../../extension-src/pi-style/features/tools/boxed/bash.ts","../../extension-src/pi-style/features/tools/boxed/command-shape.ts","../../extension-src/pi-style/features/tools/boxed/gh.ts","../../extension-src/pi-style/features/tools/boxed/git.ts","../../extension-src/pi-style/shared/split-diff.ts","../../extension-src/pi-style/features/tools/boxed/shared.ts","../../extension-src/pi-style/features/tools/boxed/grep.ts","../../extension-src/pi-style/domain/config-authorization.ts","../../extension-src/pi-style/pi/compatibility-probe.ts","../../extension-src/pi-style/features/messages/index.ts","../../extension-src/pi-style/features/tools/index.ts","../../extension-src/pi-style/features/tools/boxed/edit.ts","../../extension-src/pi-style/features/tools/boxed/fallback.ts","../../extension-src/pi-style/features/tools/boxed/find.ts","../../extension-src/pi-style/features/tools/boxed/ls.ts","../../extension-src/pi-style/features/tools/boxed/quick-edit.ts","../../extension-src/pi-style/features/tools/boxed/read.ts","../../extension-src/pi-style/features/tools/boxed/write.ts","../../extension-src/pi-style/features/tools/boxed/index.ts","../../extension-src/pi-style/pi/compatibility-registry.ts","../../extension-src/pi-style/pi/compatibility-coordinator.ts","../../extension-src/pi-style/pi/config-session.ts","../../extension-src/pi-style/pi/operational-state.ts","../../extension-src/pi-style/pi/startup-resources.ts","../../extension-src/pi-style/pi/session-usage.ts","../../extension-src/pi-style/pi/index.ts"],"sourcesContent":["function isFinal(byte: string): boolean {\n\treturn byte >= \"@\" && byte <= \"~\";\n}\n\nconst CUBE_STEPS = [0, 95, 135, 175, 215, 255] as const;\n\nfunction xterm256ToRgb(index: number): { r: number; g: number; b: number } | undefined {\n\tif (index >= 0 && index < 16) {\n\t\t// Base 16 palette approximation used by the gradient logic.\n\t\tconst base = [\n\t\t\t[0, 0, 0],\n\t\t\t[128, 0, 0],\n\t\t\t[0, 128, 0],\n\t\t\t[128, 128, 0],\n\t\t\t[0, 0, 128],\n\t\t\t[128, 0, 128],\n\t\t\t[0, 128, 128],\n\t\t\t[192, 192, 192],\n\t\t\t[128, 128, 128],\n\t\t\t[255, 0, 0],\n\t\t\t[0, 255, 0],\n\t\t\t[255, 255, 0],\n\t\t\t[0, 0, 255],\n\t\t\t[255, 0, 255],\n\t\t\t[0, 255, 255],\n\t\t\t[255, 255, 255],\n\t\t] as const;\n\t\tconst entry = base[index] ?? [0, 0, 0];\n\t\tconst [r, g, b] = entry;\n\t\treturn { r, g, b };\n\t}\n\tif (index >= 16 && index < 232) {\n\t\tconst cube = index - 16;\n\t\treturn {\n\t\t\tr: CUBE_STEPS[Math.floor(cube / 36)] ?? 0,\n\t\t\tg: CUBE_STEPS[Math.floor((cube % 36) / 6)] ?? 0,\n\t\t\tb: CUBE_STEPS[cube % 6] ?? 0,\n\t\t};\n\t}\n\tif (index >= 232 && index < 256) {\n\t\tconst gray = 8 + 10 * (index - 232);\n\t\treturn { r: gray, g: gray, b: gray };\n\t}\n\treturn undefined;\n}\n\n/**\n * Parse an ANSI foreground prefix into RGB. Supports 24-bit `38;2;r;g;b` and\n * 256-color `38;5;N` forms; returns undefined when the prefix is empty or not\n * a foreground color (e.g. `38;5;Nm` reset fragments).\n */\nexport function parseAnsiFgToRgb(prefix: string): { r: number; g: number; b: number } | undefined {\n\tconst esc = \"\\u001b\";\n\tconst direct = new RegExp(`^${esc}\\\\[38;2;(\\\\d{1,3});(\\\\d{1,3});(\\\\d{1,3})m$`).exec(prefix);\n\tif (direct) {\n\t\tconst r = Number.parseInt(direct[1] ?? \"0\", 10);\n\t\tconst g = Number.parseInt(direct[2] ?? \"0\", 10);\n\t\tconst b = Number.parseInt(direct[3] ?? \"0\", 10);\n\t\tif (r <= 255 && g <= 255 && b <= 255) return { r, g, b };\n\t}\n\tconst indexed = new RegExp(`^${esc}\\\\[38;5;(\\\\d{1,3})m$`).exec(prefix);\n\tif (indexed) {\n\t\tconst index = Number.parseInt(indexed[1] ?? \"0\", 10);\n\t\tif (index <= 255) return xterm256ToRgb(index);\n\t}\n\treturn undefined;\n}\nexport function stripAnsi(value: string): string {\n\tlet output = \"\";\n\tfor (let i = 0; i < value.length; i++) {\n\t\tif (value.charCodeAt(i) !== 27) {\n\t\t\toutput += value[i];\n\t\t\tcontinue;\n\t\t}\n\t\ti++;\n\t\tif (value[i] === \"[\") {\n\t\t\twhile (i + 1 < value.length && !isFinal(value[i + 1] ?? \"\")) i++;\n\t\t\ti++;\n\t\t} else if (value[i] === \"]\") {\n\t\t\twhile (i + 1 < value.length && value.charCodeAt(i + 1) !== 7) {\n\t\t\t\ti++;\n\t\t\t\tif (value.charCodeAt(i) === 27 && value[i + 1] === \"\\\\\") {\n\t\t\t\t\ti++;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Consume the OSC terminator (BEL, or the ESC\\\\ already consumed above)\n\t\t\t// so it is not emitted as a visible character.\n\t\t\tif (i + 1 < value.length && value.charCodeAt(i + 1) === 7) i++;\n\t\t}\n\t}\n\treturn output;\n}\nexport function visibleWidth(value: string): number {\n\treturn [...stripAnsi(value)].length;\n}\nexport function resetAnsi(value: string): string {\n\treturn `${value}\\x1b[0m`;\n}\n\n/** Return the value unchanged when it fits the width; truncate it otherwise. */\nexport function fitAnsiWidth(value: string, width: number, ellipsis = \"…\"): string {\n\treturn visibleWidth(value) <= width ? value : truncateAnsi(value, width, ellipsis);\n}\nexport function truncateAnsi(value: string, width: number, ellipsis = \"…\"): string {\n\tif (width <= 0) return \"\";\n\tif (visibleWidth(value) <= width) return resetAnsi(value);\n\tlet output = \"\";\n\tlet visible = 0;\n\tfor (let i = 0; i < value.length && visible < width - visibleWidth(ellipsis); i++) {\n\t\tif (value.charCodeAt(i) === 27) {\n\t\t\tconst start = i;\n\t\t\ti++;\n\t\t\twhile (i + 1 < value.length && !isFinal(value[i + 1] ?? \"\")) i++;\n\t\t\ti++;\n\t\t\toutput += value.slice(start, i + 1);\n\t\t\tcontinue;\n\t\t}\n\t\toutput += value[i];\n\t\tvisible++;\n\t}\n\treturn resetAnsi(output + ellipsis);\n}\nexport function wrapAnsi(value: string, width: number): string[] {\n\tif (width <= 0) return [\"\"];\n\tconst lines: string[] = [];\n\tlet line = \"\";\n\tfor (const word of value.split(/\\s+/)) {\n\t\tconst next = line ? `${line} ${word}` : word;\n\t\tif (visibleWidth(next) <= width) line = next;\n\t\telse {\n\t\t\tif (line) lines.push(resetAnsi(line));\n\t\t\tline = truncateAnsi(word, width);\n\t\t}\n\t}\n\tif (line || lines.length === 0) lines.push(resetAnsi(line));\n\treturn lines;\n}\n\n// ── Hex color + background helpers ──\n\nexport const RESET_BACKGROUND = \"\\x1b[49m\";\nexport const ERASE_TO_END_OF_LINE = \"\\x1b[K\";\nconst ESC = \"\\x1b\";\n\nexport function isHexColor(value: string): boolean {\n\tconst cleaned = value.replace(\"#\", \"\");\n\treturn cleaned.length === 3\n\t\t? /^[0-9a-fA-F]{3}$/.test(cleaned)\n\t\t: (cleaned.length === 6 || cleaned.length === 8) && /^[0-9a-fA-F]+$/.test(cleaned);\n}\n\nexport function hexToRgb(hex: string): { r: number; g: number; b: number } {\n\tconst cleaned = hex.replace(\"#\", \"\");\n\tif (cleaned.length === 3) {\n\t\tconst r = Number.parseInt((cleaned[0] ?? \"\") + (cleaned[0] ?? \"\"), 16);\n\t\tconst g = Number.parseInt((cleaned[1] ?? \"\") + (cleaned[1] ?? \"\"), 16);\n\t\tconst b = Number.parseInt((cleaned[2] ?? \"\") + (cleaned[2] ?? \"\"), 16);\n\t\treturn { r, g, b };\n\t}\n\tif ((cleaned.length !== 6 && cleaned.length !== 8) || !/^[0-9a-fA-F]+$/.test(cleaned)) {\n\t\treturn { r: 0, g: 0, b: 0 };\n\t}\n\tconst r = Number.parseInt(cleaned.slice(0, 2), 16);\n\tconst g = Number.parseInt(cleaned.slice(2, 4), 16);\n\tconst b = Number.parseInt(cleaned.slice(4, 6), 16);\n\treturn { r, g, b };\n}\n\nfunction channelToHex(value: number): string {\n\treturn Math.max(0, Math.min(255, Math.round(value)))\n\t\t.toString(16)\n\t\t.padStart(2, \"0\");\n}\n\nexport function rgbToHex(rgb: { r: number; g: number; b: number }): string {\n\treturn `#${channelToHex(rgb.r)}${channelToHex(rgb.g)}${channelToHex(rgb.b)}`;\n}\n\nconst CUBE_VALUES = [0, 95, 135, 175, 215, 255] as const;\nconst GRAY_VALUES = Array.from({ length: 24 }, (_, i) => 8 + i * 10);\n\nfunction _ansi256ToRgb(index: number): { r: number; g: number; b: number } {\n\tif (index >= 232) {\n\t\tconst gray = 8 + (index - 232) * 10;\n\t\treturn { r: gray, g: gray, b: gray };\n\t}\n\tconst cubeIndex = Math.max(0, index - 16);\n\tconst redIndex = Math.floor(cubeIndex / 36);\n\tconst greenIndex = Math.floor((cubeIndex % 36) / 6);\n\tconst blueIndex = cubeIndex % 6;\n\treturn { r: CUBE_VALUES[redIndex] ?? 0, g: CUBE_VALUES[greenIndex] ?? 0, b: CUBE_VALUES[blueIndex] ?? 0 };\n}\n\nconst _ANSI_16_RGB: ReadonlyArray<readonly [number, number, number]> = [\n\t[0, 0, 0],\n\t[128, 0, 0],\n\t[0, 128, 0],\n\t[128, 128, 0],\n\t[0, 0, 128],\n\t[128, 0, 128],\n\t[0, 128, 128],\n\t[192, 192, 192],\n\t[128, 128, 128],\n\t[255, 0, 0],\n\t[0, 255, 0],\n\t[255, 255, 0],\n\t[0, 0, 255],\n\t[255, 0, 255],\n\t[0, 255, 255],\n\t[255, 255, 255],\n] as const;\n\nfunction colorDistance(r1: number, g1: number, b1: number, r2: number, g2: number, b2: number): number {\n\tconst dr = r1 - r2;\n\tconst dg = g1 - g2;\n\tconst db = b1 - b2;\n\treturn dr * dr * 0.299 + dg * dg * 0.587 + db * db * 0.114;\n}\n\nfunction findClosestCubeIndex(value: number): number {\n\tlet minDist = Number.POSITIVE_INFINITY;\n\tlet minIdx = 0;\n\tfor (let i = 0; i < CUBE_VALUES.length; i++) {\n\t\tconst dist = Math.abs(value - (CUBE_VALUES[i] ?? 0));\n\t\tif (dist < minDist) {\n\t\t\tminDist = dist;\n\t\t\tminIdx = i;\n\t\t}\n\t}\n\treturn minIdx;\n}\n\nfunction findClosestGrayIndex(gray: number): number {\n\tlet minDist = Number.POSITIVE_INFINITY;\n\tlet minIdx = 0;\n\tfor (let i = 0; i < GRAY_VALUES.length; i++) {\n\t\tconst dist = Math.abs(gray - (GRAY_VALUES[i] ?? 0));\n\t\tif (dist < minDist) {\n\t\t\tminDist = dist;\n\t\t\tminIdx = i;\n\t\t}\n\t}\n\treturn minIdx;\n}\n\nfunction rgbTo256(r: number, g: number, b: number): number {\n\tconst rIdx = findClosestCubeIndex(r);\n\tconst gIdx = findClosestCubeIndex(g);\n\tconst bIdx = findClosestCubeIndex(b);\n\tconst cubeR = CUBE_VALUES[rIdx] ?? 0;\n\tconst cubeG = CUBE_VALUES[gIdx] ?? 0;\n\tconst cubeB = CUBE_VALUES[bIdx] ?? 0;\n\tconst cubeIndex = 16 + 36 * rIdx + 6 * gIdx + bIdx;\n\tconst cubeDist = colorDistance(r, g, b, cubeR, cubeG, cubeB);\n\n\tconst gray = Math.round(0.299 * r + 0.587 * g + 0.114 * b);\n\tconst grayIdx = findClosestGrayIndex(gray);\n\tconst grayValue = GRAY_VALUES[grayIdx] ?? 0;\n\tconst grayIndex = 232 + grayIdx;\n\tconst grayDist = colorDistance(r, g, b, grayValue, grayValue, grayValue);\n\n\tconst spread = Math.max(r, g, b) - Math.min(r, g, b);\n\tif (spread < 10 && grayDist < cubeDist) return grayIndex;\n\treturn cubeIndex;\n}\n\n/** Color-mode-aware escape prefix/suffix pairs for a hex color (cached per mode+hex). */\nfunction colorEscapes(mode: string, hex: string, kind: \"fg\" | \"bg\"): { prefix: string; suffix: string } | undefined {\n\tif (!isHexColor(hex)) return undefined;\n\tconst { r, g, b } = hexToRgb(hex);\n\tconst cacheKey = `${mode}:${kind}:${hex}`;\n\tconst cache = kind === \"fg\" ? fgEscapeCache : bgEscapeCache;\n\tlet cached = cache.get(cacheKey);\n\tif (!cached) {\n\t\tif (mode === \"256color\") {\n\t\t\tconst idx = rgbTo256(r, g, b);\n\t\t\tcached = {\n\t\t\t\tprefix: `\\x1b[${kind === \"fg\" ? 38 : 48};5;${idx}m`,\n\t\t\t\tsuffix: kind === \"fg\" ? \"\\x1b[39m\" : RESET_BACKGROUND,\n\t\t\t};\n\t\t} else {\n\t\t\tcached = {\n\t\t\t\tprefix: `\\x1b[${kind === \"fg\" ? 38 : 48};2;${r};${g};${b}m`,\n\t\t\t\tsuffix: kind === \"fg\" ? \"\\x1b[39m\" : RESET_BACKGROUND,\n\t\t\t};\n\t\t}\n\t\tcache.set(cacheKey, cached);\n\t}\n\treturn cached;\n}\n\nconst fgEscapeCache = new Map<string, { prefix: string; suffix: string }>();\nconst bgEscapeCache = new Map<string, { prefix: string; suffix: string }>();\n\n/** Foreground-styling helper: accepts a theme (for getColorMode) or \"truecolor\". */\nexport function fgHex(theme: { getColorMode?: () => string } | undefined, hex: string, text: string): string {\n\tconst mode = typeof theme?.getColorMode === \"function\" ? theme.getColorMode() : \"truecolor\";\n\tconst escapes = colorEscapes(mode, hex, \"fg\");\n\tif (!escapes) return text;\n\treturn `${escapes.prefix}${text}${escapes.suffix}`;\n}\n\n/** Background ANSI prefix for a hex color, or \"\" when not a hex color. */\nexport function bgHexAnsi(theme: { getColorMode?: () => string } | undefined, hex: string): string {\n\tconst mode = typeof theme?.getColorMode === \"function\" ? theme.getColorMode() : \"truecolor\";\n\treturn colorEscapes(mode, hex, \"bg\")?.prefix ?? \"\";\n}\n\nexport function bgHex(theme: { getColorMode?: () => string } | undefined, hex: string, text: string): string {\n\tconst mode = typeof theme?.getColorMode === \"function\" ? theme.getColorMode() : \"truecolor\";\n\tconst escapes = colorEscapes(mode, hex, \"bg\");\n\tif (!escapes) return text;\n\treturn `${escapes.prefix}${text}${escapes.suffix}`;\n}\n\n/** Whether an SGR code sequence contains a background-affecting action (set/reset). */\nfunction finalBackgroundAction(rawCodes: string): \"none\" | \"reset\" | \"set\" {\n\tconst codes = rawCodes.split(\";\").filter(Boolean);\n\tif (codes.length === 0) return \"reset\";\n\tlet action: \"none\" | \"reset\" | \"set\" = \"none\";\n\tconst sgrColorParameterEnd = (index: number): number => {\n\t\tconst code = Number(codes[index]);\n\t\tif (code !== 38 && code !== 48) return index;\n\t\tconst mode = Number(codes[index + 1]);\n\t\tif (mode === 2) return Math.min(codes.length - 1, index + 4);\n\t\tif (mode === 5) return Math.min(codes.length - 1, index + 2);\n\t\treturn index;\n\t};\n\tfor (let i = 0; i < codes.length; i++) {\n\t\tconst code = Number(codes[i]);\n\t\tif (code === 0 || code === 49) {\n\t\t\taction = \"reset\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (code === 48) {\n\t\t\taction = \"set\";\n\t\t\ti = sgrColorParameterEnd(i);\n\t\t\tcontinue;\n\t\t}\n\t\tif (code === 38) {\n\t\t\ti = sgrColorParameterEnd(i);\n\t\t\tcontinue;\n\t\t}\n\t\tif ((code >= 40 && code <= 47) || (code >= 100 && code <= 107)) action = \"set\";\n\t}\n\treturn action;\n}\n\nfunction removeStandaloneBackgroundReset(rawCodes: string): string {\n\tconst codes = rawCodes.split(\";\").filter(Boolean);\n\tif (codes.length === 0) return \"0\";\n\tconst rebuilt: string[] = [];\n\tconst sgrColorParameterEnd = (index: number): number => {\n\t\tconst code = Number(codes[index]);\n\t\tif (code !== 38 && code !== 48) return index;\n\t\tconst mode = Number(codes[index + 1]);\n\t\tif (mode === 2) return Math.min(codes.length - 1, index + 4);\n\t\tif (mode === 5) return Math.min(codes.length - 1, index + 2);\n\t\treturn index;\n\t};\n\tfor (let i = 0; i < codes.length; i++) {\n\t\tconst code = Number(codes[i]);\n\t\tif (code === 49) continue;\n\t\tconst end = sgrColorParameterEnd(i);\n\t\tfor (let j = i; j <= end; j++) rebuilt.push(codes[j] ?? \"\");\n\t\ti = end;\n\t}\n\treturn rebuilt.join(\";\");\n}\n\n/** Re-apply a background after reset sequences so a fill survives nested resets. */\nexport function keepAnsiBackgroundAcrossResets(text: string, bgAnsi: string): string {\n\tif (!text) return text;\n\treturn text.replace(new RegExp(`${ESC}\\\\[([0-9;]*)m`, \"g\"), (sequence, rawCodes) => {\n\t\tconst codes = String(rawCodes ?? \"\");\n\t\tif (finalBackgroundAction(codes) !== \"reset\") return sequence;\n\t\tconst rebuilt = removeStandaloneBackgroundReset(codes);\n\t\treturn `${rebuilt ? `\\x1b[${rebuilt}m` : \"\"}${bgAnsi}`;\n\t});\n}\n\n/** Wrap text in a background fill that survives nested resets; optional fill-to-end-of-line. */\nexport function wrapAnsiBackground(text: string, bgAnsi: string, options: { fillToEnd?: boolean } = {}): string {\n\tif (!bgAnsi || bgAnsi === RESET_BACKGROUND) return text;\n\tconst body = keepAnsiBackgroundAcrossResets(text, bgAnsi);\n\tconst fill = options.fillToEnd ? `${bgAnsi}${ERASE_TO_END_OF_LINE}` : \"\";\n\treturn `${bgAnsi}${body}${fill}${RESET_BACKGROUND}`;\n}\n","// Boxed tool-call/result rendering primitives.\n//\n// Two deliberate design points:\n//\n// 1. Background painting is removed. Boxed lines are foreground-only; the\n// enclosing native ToolExecutionComponent container applies the semantic\n// status background (toolPendingBg / toolErrorBg / toolSuccessBg), and the\n// message-block Box applies customMessageBg. This avoids double-background\n// conflicts and keeps pi-style's patches renderer-scoped.\n//\n// 2. Theme functions are accessed through a minimal structural interface\n// (BoxTheme) instead of `any`.\n\nimport { homedir } from \"node:os\";\nimport { relative, resolve } from \"node:path\";\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport { fgHex, isHexColor, stripAnsi } from \"./ansi.js\";\nimport { formatToolMetrics, getElapsedMs, type MetricResultLike } from \"./elapsed.js\";\nimport {\n\tboxedResultRenderBudget,\n\tclampRenderLine,\n\tDEFAULT_COLLAPSED_RENDER_LINES,\n\tfastBoxLineContent,\n\tsafeTruncateToWidth,\n\tsafeVisibleWidth,\n\tsafeWrapTextWithAnsi,\n} from \"./render-budget.js\";\nimport { getThemeExtra } from \"./theme-extras.js\";\n\n/** Minimal structural view of Pi's Theme as used by the boxed renderers. */\nexport interface BoxTheme {\n\tfg(color: string, text: string): string;\n\tbold?(text: string): string;\n\titalic?(text: string): string;\n\tinverse?(text: string): string;\n\tgetColorMode?(): string;\n}\n\nexport interface BoxedRenderOptions {\n\twidthKey?: string;\n\t/** Detail embedded in the top-border title after the tool name (e.g. the path). */\n\theaderDetail?: string;\n\tisError?: boolean;\n\tisPartial?: boolean;\n\tisPending?: boolean;\n\t/** Execution has started but the tool is still running (title `◌` instead of `✓`). */\n\trunning?: boolean;\n\t/** A result renderer already produced a continuation for this call, so the call\n\t * leaves the box open instead of closing it with a pending label. */\n\tresultSeen?: boolean;\n\tpendingText?: string;\n\t/** Verbatim bottom-border label for the pending/running card (overrides the\n\t * `… ${pendingText}` default, e.g. a live `◌ Running · 12.4s` status). */\n\tpendingLabel?: string;\n\tstate?: Record<string, unknown>;\n\t/** Wall-clock elapsed override (used when metrics are not in result.details). */\n\telapsedMs?: number;\n\t/** Width-dependent content lines rendered between the top border and the\n\t * footer border of a compact box (replaces the blank breathing line).\n\t * Each returned line is truncated to the box inner width by the renderer.\n\t * Returns an empty array for no body (blank line preserved). */\n\tbodyLines?: (contentWidth: number) => string[];\n\t/** Right-side label embedded in the compact box bottom border before the\n\t * corner (e.g. an expand hint such as `Ctrl+O for more`). */\n\tbottomRightLabel?: string;\n}\n\nexport function isExpanded(options: { expanded?: boolean } | undefined): boolean {\n\treturn typeof options?.expanded === \"boolean\" ? options.expanded : false;\n}\n\nexport function shortenPath(path: string): string {\n\tconst home = homedir();\n\tif (path.startsWith(home)) return `~${path.slice(home.length)}`;\n\treturn path;\n}\n\nexport function resolveAbsolutePath(rawPath: string, cwd: string): string {\n\tconst path = rawPath.trim();\n\tif (!path) return \"\";\n\n\tconst home = process.env.HOME;\n\tif (home && (path === \"~\" || path.startsWith(\"~/\"))) {\n\t\treturn path === \"~\" ? home : resolve(home, path.slice(2));\n\t}\n\n\treturn resolve(cwd, path);\n}\n\nexport function resolveRelativePath(rawPath: string, cwd: string): string {\n\tconst absPath = resolveAbsolutePath(rawPath, cwd);\n\tif (!absPath) return \"(unknown)\";\n\tconst relPath = relative(cwd, absPath).replace(/\\\\/g, \"/\");\n\treturn relPath || \".\";\n}\n\nexport function replaceTabs(text: string): string {\n\treturn text.replace(/\\t/g, \" \");\n}\n\nexport function getTextOutput(result: MetricResultLike | undefined): string {\n\tif (!result?.content) return \"\";\n\tconst textBlocks = result.content.filter((contentBlock) => {\n\t\tif (!contentBlock || typeof contentBlock !== \"object\") return false;\n\t\treturn (contentBlock as { type?: unknown }).type === \"text\";\n\t});\n\treturn textBlocks\n\t\t.map((contentBlock) => String((contentBlock as { text?: unknown }).text ?? \"\"))\n\t\t.join(\"\\n\")\n\t\t.replace(/\\r/g, \"\");\n}\n\nexport function stripTrailingNotice(text: string): string {\n\tconst normalized = (text ?? \"\").replace(/\\r/g, \"\").trimEnd();\n\tif (!normalized) return \"\";\n\tif (normalized.startsWith(\"[\") && normalized.endsWith(\"]\")) return \"\";\n\tconst noticeStart = normalized.lastIndexOf(\"\\n\\n[\");\n\tif (noticeStart >= 0 && normalized.endsWith(\"]\")) {\n\t\treturn normalized.slice(0, noticeStart).trimEnd();\n\t}\n\treturn normalized;\n}\n\nexport function extractTrailingNotice(text: string): string | null {\n\tconst normalized = (text ?? \"\").replace(/\\r/g, \"\").trimEnd();\n\tif (!normalized) return null;\n\tif (normalized.startsWith(\"[\") && normalized.endsWith(\"]\")) return normalized;\n\tconst noticeStart = normalized.lastIndexOf(\"\\n\\n[\");\n\tif (noticeStart >= 0 && normalized.endsWith(\"]\")) {\n\t\treturn normalized.slice(noticeStart + 2).trimEnd();\n\t}\n\treturn null;\n}\n\nexport function countLines(text: string): number {\n\tconst normalized = (text ?? \"\").replace(/\\r/g, \"\").replace(/\\n+$/g, \"\");\n\tif (!normalized) return 0;\n\treturn normalized.split(\"\\n\").length;\n}\n\nexport function countWords(text: string): number {\n\tlet count = 0;\n\tlet inWord = false;\n\tfor (const char of text) {\n\t\tconst isWord = /[\\p{L}\\p{N}_'-]/u.test(char);\n\t\tif (isWord && !inWord) count++;\n\t\tinWord = isWord;\n\t}\n\treturn count;\n}\n\nexport function formatCompactCount(value: number): string {\n\tif (value < 1000) return `${Math.round(value)}`;\n\tif (value < 10000) return `${(value / 1000).toFixed(1)}k`;\n\tif (value < 1000000) return `${Math.round(value / 1000)}k`;\n\tif (value < 10000000) return `${(value / 1000000).toFixed(1)}M`;\n\treturn `${Math.round(value / 1000000)}M`;\n}\n\nexport function formatBoxedWords(text: string): string {\n\treturn `~${formatCompactCount(countWords(text))} words`;\n}\n\nexport function badge(theme: BoxTheme, label: string): string {\n\tconst tagBg = getThemeExtra(theme, \"tagBgColor\");\n\tif (tagBg && isHexColor(tagBg)) {\n\t\treturn theme.inverse\n\t\t\t? theme.inverse(fgHex(theme, tagBg, theme.bold ? theme.bold(` ${label} `) : ` ${label} `))\n\t\t\t: fgHex(theme, tagBg, theme.bold ? theme.bold(` ${label} `) : ` ${label} `);\n\t}\n\treturn theme.inverse ? theme.inverse(theme.bold ? theme.bold(` ${label} `) : ` ${label} `) : ` ${label} `;\n}\n\nexport function parens(theme: BoxTheme, text: string, skipTextColor?: boolean): string {\n\tconst bracketColor = getThemeExtra(theme, \"parensBracketColor\");\n\tconst openParen = bracketColor && isHexColor(bracketColor) ? fgHex(theme, bracketColor, \"(\") : \"(\";\n\tconst closeParen = bracketColor && isHexColor(bracketColor) ? fgHex(theme, bracketColor, \")\") : \")\";\n\tlet innerBase: string;\n\tif (skipTextColor) {\n\t\tinnerBase = text;\n\t} else {\n\t\tconst textColor = getThemeExtra(theme, \"parensTextColor\");\n\t\tinnerBase = textColor && isHexColor(textColor) ? fgHex(theme, textColor, text) : text;\n\t}\n\tconst inner = typeof theme?.bold === \"function\" ? theme.bold(innerBase) : `\\x1b[1m${innerBase}\\x1b[22m`;\n\treturn `${openParen}${inner}${closeParen}`;\n}\n\nconst BOX_HORIZONTAL = \"─\";\nconst BOX_VERTICAL = \"│\";\nconst BOX_SIDE_PADDING = 2;\nconst BOX_MIN_WIDTH = 12;\nconst BOX_ROUND_TOP_LEFT = \"╭\";\nconst BOX_ROUND_TOP_RIGHT = \"╮\";\nconst BOX_ROUND_BOTTOM_LEFT = \"╰\";\nconst BOX_ROUND_BOTTOM_RIGHT = \"╯\";\nconst BOX_DIVIDER_LEFT = \"├\";\nconst BOX_DIVIDER_RIGHT = \"┤\";\n/** Dash run before the right corner when a right-side border label is present. */\nconst BOX_LABELED_RIGHT_DASH_MIN = 3;\nconst BOX_WIDTH_CACHE = new Map<string, number>();\n\nexport function boxWidth(width: number): number {\n\treturn Math.max(BOX_MIN_WIDTH, width);\n}\n\nexport function boxInnerWidth(width: number): number {\n\treturn Math.max(1, boxWidth(width) - 2 - BOX_SIDE_PADDING * 2);\n}\n\nfunction _tightBoxWidth(\n\tavailableWidth: number,\n\tcontentLines: string[],\n\tlabelWidths: number[] = [],\n\twidthKey?: string,\n): number {\n\tconst contentWidth = contentLines.reduce((max, line) => Math.max(max, safeVisibleWidth(line)), 0);\n\tconst labelWidth = labelWidths.reduce((max, width) => Math.max(max, width), 0);\n\tconst neededWidth = Math.max(\n\t\tBOX_MIN_WIDTH,\n\t\tcontentWidth + 2 + BOX_SIDE_PADDING * 2,\n\t\tlabelWidth + 2 + BOX_SIDE_PADDING * 2,\n\t);\n\tconst measuredWidth = Math.min(boxWidth(availableWidth), neededWidth);\n\tif (!widthKey) return measuredWidth;\n\tconst cachedWidth = BOX_WIDTH_CACHE.get(widthKey) ?? 0;\n\tconst nextWidth = Math.min(boxWidth(availableWidth), Math.max(cachedWidth, measuredWidth));\n\tBOX_WIDTH_CACHE.set(widthKey, nextWidth);\n\treturn nextWidth;\n}\n\nexport function boxedToolWidthKey(toolName: string, detail: string): string {\n\treturn `${toolName}:${detail}`;\n}\n\nexport function formatToolName(toolName: string): string {\n\tconst spaced = toolName\n\t\t.replace(/[_-]+/g, \" \")\n\t\t.replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n\t\t.replace(/([A-Z]+)([A-Z][a-z])/g, \"$1 $2\")\n\t\t.trim();\n\treturn spaced.replace(/\\b\\w/g, (char) => char.toUpperCase()) || toolName;\n}\n\nfunction formatToolParamName(name: string): string {\n\tconst spaced = name\n\t\t.replace(/[_-]+/g, \" \")\n\t\t.replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n\t\t.replace(/([A-Z]+)([A-Z][a-z])/g, \"$1 $2\")\n\t\t.trim();\n\treturn spaced ? spaced[0]?.toUpperCase() + spaced.slice(1) : name;\n}\n\nconst MAX_PARAM_VALUE_LENGTH = 120;\n\nfunction formatOperationSummary(value: unknown): string | undefined {\n\tif (!Array.isArray(value) || value.length === 0) return undefined;\n\tif (!value.every((item) => item && typeof item === \"object\" && !Array.isArray(item))) return undefined;\n\tconst types = Array.from(new Set(value.map((item) => String((item as { type?: unknown }).type ?? \"operation\"))));\n\tconst typeSummary =\n\t\ttypes.length === 1\n\t\t\t? ` (${types[0]})`\n\t\t\t: types.length > 1\n\t\t\t\t? ` (${types.slice(0, 3).join(\", \")}${types.length > 3 ? \", …\" : \"\"})`\n\t\t\t\t: \"\";\n\treturn `${value.length} ${value.length === 1 ? \"operation\" : \"operations\"}${typeSummary}`;\n}\n\nfunction formatToolParamValue(value: unknown): string {\n\tif (value === undefined) return \"\";\n\tif (value === null) return \"null\";\n\tif (typeof value === \"string\") {\n\t\tif (value.length <= MAX_PARAM_VALUE_LENGTH) return value;\n\t\treturn `${value.slice(0, MAX_PARAM_VALUE_LENGTH)}…`;\n\t}\n\tif (typeof value === \"number\" || typeof value === \"boolean\" || typeof value === \"bigint\") return String(value);\n\tif (Array.isArray(value)) {\n\t\tif (value.length === 0) return \"[]\";\n\t\treturn formatOperationSummary(value) ?? `${value.length} ${value.length === 1 ? \"item\" : \"items\"}`;\n\t}\n\tif (typeof value === \"object\" && value !== null) {\n\t\tconst keys = Object.keys(value);\n\t\tif (keys.length === 0) return \"{}\";\n\t\treturn `{${keys.length} ${keys.length === 1 ? \"key\" : \"keys\"}}`;\n\t}\n\ttry {\n\t\tconst json = JSON.stringify(value);\n\t\tif (json.length <= MAX_PARAM_VALUE_LENGTH) return json;\n\t\treturn `${json.slice(0, MAX_PARAM_VALUE_LENGTH)}…`;\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n\nexport function formatToolParamLines(args: unknown, theme?: BoxTheme): string[] {\n\tif (args === undefined || args === null) return [];\n\tif (typeof args !== \"object\" || Array.isArray(args)) {\n\t\tconst value = formatToolParamValue(args);\n\t\treturn value ? [`Params: ${value}`] : [];\n\t}\n\n\tconst entries = Object.entries(args as Record<string, unknown>).filter(([, value]) => value !== undefined);\n\tif (entries.length === 0) return [];\n\n\tconst lines: string[] = [];\n\tfor (const [key, value] of entries) {\n\t\tconst formattedValue = formatToolParamValue(value);\n\t\tif (!formattedValue) continue;\n\t\tconst [firstLine = \"\", ...restLines] = formattedValue.replace(/\\r/g, \"\").split(\"\\n\");\n\t\tconst keyLabel = formatToolParamName(key);\n\t\tif (theme) {\n\t\t\tlines.push(`${theme.fg(\"dim\", `${keyLabel}:`)} ${theme.fg(\"text\", firstLine)}`);\n\t\t\tlines.push(...restLines.map((line) => ` ${theme.fg(\"text\", line)}`));\n\t\t} else {\n\t\t\tlines.push(`${keyLabel}: ${firstLine}`);\n\t\t\tlines.push(...restLines.map((line) => ` ${line}`));\n\t\t}\n\t}\n\treturn lines;\n}\n\nfunction colorFromExtra(theme: BoxTheme, extraKey: string, fallbackColor: string, text: string): string {\n\tconst color = getThemeExtra(theme, extraKey);\n\tif (color) {\n\t\tif (isHexColor(color)) return fgHex(theme, color, text);\n\t\ttry {\n\t\t\treturn theme.fg(color, text);\n\t\t} catch {\n\t\t\t// Fall back to semantic theme color below.\n\t\t}\n\t}\n\treturn theme.fg(fallbackColor, text);\n}\n\nfunction formatBoxedStatusIcon(theme: BoxTheme, isError?: boolean): string {\n\tconst icon = isError ? \"✗\" : \"✓\";\n\treturn theme.fg(isError ? \"error\" : \"success\", icon);\n}\n\n/**\n * Colored `➔ Name` prefix for tool titles (identity color). The status glyph\n * (✓/◌/✗) is appended separately by formatBoxedToolTitle.\n */\nexport function formatToolTitlePrefix(theme: BoxTheme, name: string): string {\n\treturn colorFromExtra(theme, \"bashPromptColor\", \"bashMode\", `➔ ${name}`);\n}\n\nexport type BoxedTitleStatus = \"running\" | \"pending\";\n\n/**\n * Boxed tool title: `➔ Name ✓` when settled, `➔ Name ◌` while running, plain\n * `➔ Name` while pending, and a fully error-colored `➔ Name ✗` on failure.\n * The ✓/◌ glyphs are never shown before the tool settles, so a card that is\n * still executing never reads as finished.\n */\nexport function formatBoxedToolTitle(\n\ttheme: BoxTheme,\n\tname: string,\n\tisError?: boolean,\n\tstatus?: BoxedTitleStatus,\n): string {\n\t// On failure the whole title turns error-colored (not just the ✗) so a failed\n\t// tool reads instantly; on success the tool keeps its identity color and only\n\t// the ✓ carries the success color.\n\tconst coloredTitle = isError\n\t\t? theme.fg(\"error\", `➔ ${name} ✗`)\n\t\t: status === \"running\"\n\t\t\t? `${formatToolTitlePrefix(theme, name)} ${theme.fg(\"text\", \"◌\")}`\n\t\t\t: status === \"pending\"\n\t\t\t\t? formatToolTitlePrefix(theme, name)\n\t\t\t\t: `${formatToolTitlePrefix(theme, name)} ${formatBoxedStatusIcon(theme, false)}`;\n\treturn typeof theme?.bold === \"function\" ? theme.bold(coloredTitle) : coloredTitle;\n}\n\n/** Live running status label for pending/running cards and streaming footers. */\nexport function formatBoxedRunningStatus(theme: BoxTheme, elapsedMs: number | undefined): string {\n\tconst elapsed = elapsedMs === undefined ? \"\" : `${theme.fg(\"text\", ` · ${(elapsedMs / 1000).toFixed(1)}s`)}`;\n\treturn `${theme.fg(\"dim\", \"◌ Running\")}${elapsed}`;\n}\n\n/** Structural line — box frame, tree branch, divider, gutter — wrapped in\n * dim terminal-default intensity. Visible in every theme; matches omp. */\nexport function dimLine(text: string): string {\n\treturn `\\x1b[2m${text}\\x1b[22m`;\n}\n\nfunction boxText(theme: BoxTheme, text: string): string {\n\treturn dimLine(text);\n}\nfunction boxFrameText(theme: BoxTheme, text: string): string {\n\treturn dimLine(text);\n}\n\nexport function boxedToolBgName(isError?: boolean, isPartial?: boolean): string {\n\treturn isPartial ? \"toolPendingBg\" : isError ? \"toolErrorBg\" : \"toolSuccessBg\";\n}\n\nexport function boxBorder(theme: BoxTheme, left: string, right: string, width: number): string {\n\tconst renderedWidth = boxWidth(width);\n\tconst innerWidth = renderedWidth - 2;\n\treturn boxFrameText(theme, `${left}${BOX_HORIZONTAL.repeat(innerWidth)}${right}`);\n}\n\n/**\n * Border line with an optional label embedded after the left corner and an\n * optional right-side label before the right corner, e.g.:\n *\n * ╭─ ➔ Bash ✓ ────────────╮\n * ├─ Response ────────────┤\n * ╰─ 0.00s · ~45 words ──── Ctrl+O for more ───╯\n */\nexport function boxLabeledBorder(\n\ttheme: BoxTheme,\n\tstart: string,\n\tend: string,\n\tleftLabel: string,\n\trightLabel: string | undefined,\n\twidth: number,\n): string {\n\tconst renderedWidth = boxWidth(width);\n\tlet left = leftLabel ?? \"\";\n\tconst right = rightLabel ?? \"\";\n\tlet leftWidth = safeVisibleWidth(left);\n\tconst rightWidth = safeVisibleWidth(right);\n\tconst leftOverhead = left ? 3 : 0; // \"─ \" prefix + \" \" suffix\n\tconst rightOverhead = right ? 2 : 0; // \" \" prefix + \" \" suffix\n\tlet rightFill = right ? BOX_LABELED_RIGHT_DASH_MIN : 0;\n\tlet fill =\n\t\trenderedWidth - start.length - end.length - leftOverhead - leftWidth - rightOverhead - rightWidth - rightFill;\n\n\tif (right && fill < 0) {\n\t\trightFill = 1;\n\t\tfill =\n\t\t\trenderedWidth - start.length - end.length - leftOverhead - leftWidth - rightOverhead - rightWidth - rightFill;\n\t}\n\n\tif (fill < 0) {\n\t\t// Too narrow for the labels: truncate the left label, keeping at least one\n\t\t// filler dash so the border stays closed.\n\t\tconst reserved =\n\t\t\tstart.length + end.length + leftOverhead + (right ? rightOverhead + rightWidth + rightFill : 0) + 1;\n\t\tconst maxLeft = renderedWidth - reserved;\n\t\tleft = maxLeft > 0 ? safeTruncateToWidth(left, maxLeft, \"…\") : \"\";\n\t\tleftWidth = safeVisibleWidth(left);\n\t\tfill =\n\t\t\trenderedWidth -\n\t\t\tstart.length -\n\t\t\tend.length -\n\t\t\t(left ? leftWidth + leftOverhead : 0) -\n\t\t\t(right ? rightOverhead + rightWidth + rightFill : 0);\n\t}\n\n\t// Style each border segment separately. Embedded labels carry their own\n\t// foreground escapes that end in \\x1b[39m (reset to the terminal default);\n\t// applying the border color to the whole line in one wrap would leave every\n\t// dash after a label in the default color, making one border render with\n\t// mixed brightness.\n\tconst parts: string[] = [boxFrameText(theme, `${start}${left ? \"─ \" : \"\"}`)];\n\tif (left) parts.push(left);\n\tparts.push(boxFrameText(theme, `${left ? \" \" : \"\"}${BOX_HORIZONTAL.repeat(Math.max(0, fill))}`));\n\tif (right) {\n\t\tparts.push(boxFrameText(theme, \" \"), right, boxFrameText(theme, ` ${BOX_HORIZONTAL.repeat(rightFill)}`));\n\t}\n\tparts.push(boxFrameText(theme, end));\n\treturn parts.join(\"\");\n}\n\n/** Empty content line used for breathing room inside a box. */\nexport function boxBlankLine(theme: BoxTheme, width: number): string {\n\tconst renderedWidth = boxWidth(width);\n\tconst contentWidth = boxInnerWidth(renderedWidth);\n\tconst sidePad = \" \".repeat(BOX_SIDE_PADDING);\n\treturn `${boxFrameText(theme, BOX_VERTICAL)}${sidePad}${\" \".repeat(contentWidth)}${sidePad}${boxFrameText(theme, BOX_VERTICAL)}`;\n}\n\nexport function boxLineAligned(theme: BoxTheme, left: string, right: string, width: number): string {\n\tconst renderedWidth = boxWidth(width);\n\tconst contentWidth = boxInnerWidth(renderedWidth);\n\tconst rightWidth = safeVisibleWidth(right);\n\tconst sidePad = \" \".repeat(BOX_SIDE_PADDING);\n\n\tif (!right || rightWidth >= contentWidth) {\n\t\treturn boxLine(theme, right || left, renderedWidth);\n\t}\n\n\tconst maxLeftWidth = Math.max(1, contentWidth - rightWidth - 1);\n\tconst truncatedLeft = safeTruncateToWidth(left, maxLeftWidth, \"…\");\n\tconst gap = \" \".repeat(Math.max(1, contentWidth - safeVisibleWidth(truncatedLeft) - rightWidth));\n\treturn `${boxFrameText(theme, BOX_VERTICAL)}${sidePad}${truncatedLeft}${gap}${right}${sidePad}${boxFrameText(theme, BOX_VERTICAL)}`;\n}\n\nexport function boxLineWithRight(theme: BoxTheme, left: string, right: string, width: number): string {\n\tconst renderedWidth = boxWidth(width);\n\tconst contentWidth = boxInnerWidth(renderedWidth);\n\tconst divider = ` ${boxText(theme, \"|\")} `;\n\tconst dividerWidth = safeVisibleWidth(divider);\n\tconst rightWidth = safeVisibleWidth(right);\n\tconst sidePad = \" \".repeat(BOX_SIDE_PADDING);\n\n\tif (!right || rightWidth + dividerWidth >= contentWidth) {\n\t\treturn boxLine(theme, right || left, renderedWidth);\n\t}\n\n\tconst maxLeftWidth = Math.max(1, contentWidth - dividerWidth - rightWidth - 1);\n\tconst truncatedLeft = safeTruncateToWidth(left, maxLeftWidth, \"…\");\n\tconst gap = \" \".repeat(Math.max(1, contentWidth - safeVisibleWidth(truncatedLeft) - dividerWidth - rightWidth));\n\treturn `${boxFrameText(theme, BOX_VERTICAL)}${sidePad}${truncatedLeft}${gap}${divider}${right}${sidePad}${boxFrameText(theme, BOX_VERTICAL)}`;\n}\n\nexport function boxLine(theme: BoxTheme, content: string, width: number): string {\n\tconst renderedWidth = boxWidth(width);\n\tconst contentWidth = boxInnerWidth(renderedWidth);\n\tconst fastContent = fastBoxLineContent(content, contentWidth);\n\tconst sidePad = \" \".repeat(BOX_SIDE_PADDING);\n\tif (fastContent) {\n\t\tconst fill = \" \".repeat(Math.max(0, contentWidth - fastContent.visibleWidth));\n\t\treturn `${boxFrameText(theme, BOX_VERTICAL)}${sidePad}${fastContent.text}${fill}${sidePad}${boxFrameText(theme, BOX_VERTICAL)}`;\n\t}\n\n\tconst truncated = safeTruncateToWidth(content, contentWidth, \"…\");\n\tconst fill = \" \".repeat(Math.max(0, contentWidth - safeVisibleWidth(truncated)));\n\treturn `${boxFrameText(theme, BOX_VERTICAL)}${sidePad}${truncated}${fill}${sidePad}${boxFrameText(theme, BOX_VERTICAL)}`;\n}\n\nexport function boxInsetDivider(theme: BoxTheme, width: number): string {\n\tconst renderedWidth = boxWidth(width);\n\tconst lineWidth = boxInnerWidth(renderedWidth);\n\tconst sidePad = \" \".repeat(BOX_SIDE_PADDING);\n\treturn `${boxFrameText(theme, BOX_VERTICAL)}${sidePad}${boxText(theme, BOX_HORIZONTAL.repeat(lineWidth))}${sidePad}${boxFrameText(theme, BOX_VERTICAL)}`;\n}\n\nexport function boxedWrappedLines(theme: BoxTheme, content: string, width: number): string[] {\n\treturn safeWrapTextWithAnsi(content, boxInnerWidth(width)).map((line) => boxLine(theme, line, width));\n}\n\nfunction boxedTruncatedLine(theme: BoxTheme, content: string, width: number): string {\n\treturn boxLine(theme, safeTruncateToWidth(content, boxInnerWidth(width), \"…\"), width);\n}\n\ntype RenderLinesCache = {\n\twidth: number;\n\tlines: string[];\n};\n\nfunction pushBoundedLines(target: string[], lines: string[], maxLines: number): boolean {\n\tconst slots = maxLines - target.length;\n\tif (slots <= 0) return false;\n\tif (lines.length > slots) {\n\t\ttarget.push(...lines.slice(0, slots));\n\t\treturn false;\n\t}\n\ttarget.push(...lines);\n\treturn true;\n}\n\nfunction renderBoxedOutputLines(\n\ttheme: BoxTheme,\n\toutputLines: string[],\n\twidth: number,\n\trawLineBudget = DEFAULT_COLLAPSED_RENDER_LINES,\n): string[] {\n\tconst budget = boxedResultRenderBudget(rawLineBudget);\n\tconst headLimit = Math.max(0, Math.min(budget.headLines, budget.maxRenderedLines));\n\tconst tailLimit = Math.max(0, Math.min(budget.tailLines, Math.max(0, budget.maxRenderedLines - headLimit - 1)));\n\tconst head: string[] = [];\n\tlet nextInputIndex = 0;\n\tlet truncated = false;\n\n\tfor (; nextInputIndex < outputLines.length; nextInputIndex++) {\n\t\tconst line = boxedTruncatedLine(theme, outputLines[nextInputIndex] ?? \"\", width);\n\t\tif (!pushBoundedLines(head, [line], headLimit)) {\n\t\t\ttruncated = true;\n\t\t\tnextInputIndex++;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!truncated && nextInputIndex >= outputLines.length) return head;\n\n\tconst tail: string[] = [];\n\tconst tailStart = Math.max(nextInputIndex, outputLines.length - tailLimit);\n\tfor (let i = tailStart; i < outputLines.length; i++) {\n\t\tconst line = boxedTruncatedLine(theme, outputLines[i] ?? \"\", width);\n\t\ttail.push(line);\n\t\tif (tail.length > tailLimit) tail.splice(0, tail.length - tailLimit);\n\t}\n\n\tconst skippedInputLines = Math.max(0, tailStart - nextInputIndex);\n\tconst skippedText =\n\t\tskippedInputLines > 0\n\t\t\t? `… rendered output truncated; ${skippedInputLines} input lines skipped before tail`\n\t\t\t: \"… rendered output truncated\";\n\treturn [...head, boxLine(theme, theme.fg(\"muted\", skippedText), width), ...tail];\n}\n\nexport function renderBoxedToolCall(\n\ttheme: BoxTheme,\n\ttoolName: string,\n\tdetailLines: string[],\n\toptions: BoxedRenderOptions = {},\n): Component {\n\tlet cache: RenderLinesCache | null = null;\n\treturn {\n\t\tinvalidate() {\n\t\t\tcache = null;\n\t\t},\n\t\trender(width: number): string[] {\n\t\t\tif (cache?.width === width) return cache.lines;\n\t\t\tconst title = formatBoxedToolTitle(\n\t\t\t\ttheme,\n\t\t\t\ttoolName,\n\t\t\t\toptions.isError,\n\t\t\t\toptions.isPending ? (options.running ? \"running\" : \"pending\") : undefined,\n\t\t\t);\n\t\t\tconst headerLabel = options.headerDetail ? `${title} · ${options.headerDetail}` : title;\n\t\t\tconst renderedWidth = boxWidth(width);\n\t\t\tconst lines = [\n\t\t\t\tboxLabeledBorder(theme, BOX_ROUND_TOP_LEFT, BOX_ROUND_TOP_RIGHT, headerLabel, undefined, renderedWidth),\n\t\t\t\tboxBlankLine(theme, renderedWidth),\n\t\t\t\t...detailLines.flatMap((line) => boxedWrappedLines(theme, line, renderedWidth)),\n\t\t\t];\n\t\t\tif (options.isPending && !options.resultSeen) {\n\t\t\t\t// Pending/running card: close the box with the status label. Once a\n\t\t\t\t// result renderer has produced a continuation, the box stays open and\n\t\t\t\t// that continuation closes it.\n\t\t\t\tconst pendingLabel =\n\t\t\t\t\toptions.pendingLabel ?? theme.fg(\"dim\", `… ${options.pendingText ?? \"Waiting for output…\"}`);\n\t\t\t\tlines.push(\n\t\t\t\t\tboxBlankLine(theme, renderedWidth),\n\t\t\t\t\tboxLabeledBorder(\n\t\t\t\t\t\ttheme,\n\t\t\t\t\t\tBOX_ROUND_BOTTOM_LEFT,\n\t\t\t\t\t\tBOX_ROUND_BOTTOM_RIGHT,\n\t\t\t\t\t\tpendingLabel,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t\trenderedWidth,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t// Leave the box open with trailing breathing room; the result renderer\n\t\t\t\t// continues it with the result divider.\n\t\t\t\tlines.push(boxBlankLine(theme, renderedWidth));\n\t\t\t}\n\t\t\tcache = { width, lines };\n\t\t\treturn lines;\n\t\t},\n\t};\n}\n\nconst COMPACT_FOOTER_KEY = \"__piStyleCompactFooter\";\nconst COMPACT_FOOTER_ERROR_KEY = \"__piStyleCompactFooterError\";\nconst COMPACT_FOOTER_PARTIAL_KEY = \"__piStyleCompactFooterPartial\";\n\nexport function clearCompactBoxedFooter(state: Record<string, unknown> | undefined): void {\n\tif (!state || typeof state !== \"object\") return;\n\tdelete state[COMPACT_FOOTER_KEY];\n\tdelete state[COMPACT_FOOTER_ERROR_KEY];\n\tdelete state[COMPACT_FOOTER_PARTIAL_KEY];\n}\n\nexport function renderCompactBoxedToolCall(\n\ttheme: BoxTheme,\n\ttoolName: string,\n\tdetailLine: string,\n\toptions: BoxedRenderOptions = {},\n): Component {\n\treturn {\n\t\tinvalidate() {},\n\t\trender(width: number): string[] {\n\t\t\tconst renderedWidth = boxWidth(width);\n\t\t\tconst title = formatBoxedToolTitle(\n\t\t\t\ttheme,\n\t\t\t\ttoolName,\n\t\t\t\toptions.isError,\n\t\t\t\toptions.isPending ? (options.running ? \"running\" : \"pending\") : undefined,\n\t\t\t);\n\t\t\tconst headerLabel = detailLine ? `${title} · ${detailLine}` : title;\n\t\t\tconst compactFooter =\n\t\t\t\ttypeof options.state?.[COMPACT_FOOTER_KEY] === \"string\" ? options.state[COMPACT_FOOTER_KEY] : \"\";\n\t\t\tconst _footerIsError = Boolean(options.state?.[COMPACT_FOOTER_ERROR_KEY]);\n\t\t\tconst _footerIsPartial = Boolean(options.state?.[COMPACT_FOOTER_PARTIAL_KEY]);\n\t\t\tconst bodyLines = options.bodyLines ? options.bodyLines(boxInnerWidth(renderedWidth)) : [];\n\t\t\tconst lines = [\n\t\t\t\tboxLabeledBorder(theme, BOX_ROUND_TOP_LEFT, BOX_ROUND_TOP_RIGHT, headerLabel, undefined, renderedWidth),\n\t\t\t\t...(bodyLines.length > 0\n\t\t\t\t\t? bodyLines.map((line) => boxLine(theme, line, renderedWidth))\n\t\t\t\t\t: [boxBlankLine(theme, renderedWidth)]),\n\t\t\t];\n\t\t\tif (compactFooter) {\n\t\t\t\tlines.push(\n\t\t\t\t\tboxLabeledBorder(\n\t\t\t\t\t\ttheme,\n\t\t\t\t\t\tBOX_ROUND_BOTTOM_LEFT,\n\t\t\t\t\t\tBOX_ROUND_BOTTOM_RIGHT,\n\t\t\t\t\t\tcompactFooter,\n\t\t\t\t\t\toptions.bottomRightLabel,\n\t\t\t\t\t\trenderedWidth,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else if (options.isPending) {\n\t\t\t\tconst pendingLabel =\n\t\t\t\t\toptions.pendingLabel ??\n\t\t\t\t\t(options.running\n\t\t\t\t\t\t? formatBoxedRunningStatus(theme, undefined)\n\t\t\t\t\t\t: theme.fg(\"dim\", `… ${options.pendingText ?? \"Waiting for output…\"}`));\n\t\t\t\tlines.push(\n\t\t\t\t\tboxLabeledBorder(\n\t\t\t\t\t\ttheme,\n\t\t\t\t\t\tBOX_ROUND_BOTTOM_LEFT,\n\t\t\t\t\t\tBOX_ROUND_BOTTOM_RIGHT,\n\t\t\t\t\t\tpendingLabel,\n\t\t\t\t\t\toptions.bottomRightLabel,\n\t\t\t\t\t\trenderedWidth,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t// No footer yet (transient, or the result opens the result divider):\n\t\t\t\t// leave the box open so the result renderer continues the same box.\n\t\t\t}\n\t\t\treturn lines;\n\t\t},\n\t};\n}\n\ntype BoxedResultBody = Component | ((contentWidth: number) => string[]);\n\nexport function renderBoxedToolResult(\n\ttheme: BoxTheme,\n\tbody: BoxedResultBody,\n\toptions: {\n\t\toutputLabel?: string;\n\t\tfooterLines?: string[];\n\t\temptyText?: string;\n\t\twidthKey?: string;\n\t\treferenceLines?: string[];\n\t\trenderLineBudget?: number;\n\t\t/** Left-side label embedded in the divider between the call and the result. May be a function of the box width (e.g. for width-dependent layout labels). */\n\t\tdividerLabel?: string | ((width: number) => string);\n\t\t/** Right-side label embedded in the divider between the call and the result. */\n\t\tdividerRightLabel?: string;\n\t\t/** Right-side label embedded in the bottom border (e.g. the expand hint). */\n\t\texpandHint?: string;\n\t\tisError?: boolean;\n\t\tisPartial?: boolean;\n\t\t/** Skip the result divider entirely (streaming continuation into an open call box). */\n\t\tshowDivider?: boolean;\n\t\t/** Error state marker prepended to the body (default `✗ Error`). */\n\t\terrorLabel?: string;\n\t} = {},\n): Component {\n\tlet cache: RenderLinesCache | null = null;\n\treturn {\n\t\tinvalidate() {\n\t\t\tcache = null;\n\t\t\tif (typeof body !== \"function\") body.invalidate();\n\t\t},\n\t\trender(width: number): string[] {\n\t\t\tif (cache?.width === width) return cache.lines;\n\t\t\tconst renderedWidth = boxWidth(width);\n\t\t\tconst maxContentWidth = boxInnerWidth(renderedWidth);\n\t\t\tconst bodyLines = typeof body === \"function\" ? body(maxContentWidth) : body.render(maxContentWidth);\n\t\t\tconst errorPrefix = options.isError ? [theme.fg(\"error\", options.errorLabel ?? \"✗ Error\")] : [];\n\t\t\tconst outputLines =\n\t\t\t\tbodyLines.length > 0\n\t\t\t\t\t? [...errorPrefix, ...bodyLines]\n\t\t\t\t\t: [theme.fg(\"muted\", `∅ ${options.emptyText ?? \"(no output)\"}`)];\n\t\t\tconst footerText = (options.footerLines ?? []).join(\" · \");\n\t\t\tconst dividerText =\n\t\t\t\ttypeof options.dividerLabel === \"function\"\n\t\t\t\t\t? options.dividerLabel(renderedWidth)\n\t\t\t\t\t: (options.dividerLabel ?? \"Response\");\n\t\t\tconst rendered = [\n\t\t\t\t...(options.showDivider === false\n\t\t\t\t\t? []\n\t\t\t\t\t: [\n\t\t\t\t\t\t\tboxLabeledBorder(\n\t\t\t\t\t\t\t\ttheme,\n\t\t\t\t\t\t\t\tBOX_DIVIDER_LEFT,\n\t\t\t\t\t\t\t\tBOX_DIVIDER_RIGHT,\n\t\t\t\t\t\t\t\ttheme.fg(\"dim\", dividerText),\n\t\t\t\t\t\t\t\toptions.dividerRightLabel ? theme.fg(\"dim\", options.dividerRightLabel) : undefined,\n\t\t\t\t\t\t\t\trenderedWidth,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t]),\n\t\t\t\tboxBlankLine(theme, renderedWidth),\n\t\t\t\t...renderBoxedOutputLines(theme, outputLines, renderedWidth, options.renderLineBudget ?? outputLines.length),\n\t\t\t\tboxBlankLine(theme, renderedWidth),\n\t\t\t\tboxLabeledBorder(\n\t\t\t\t\ttheme,\n\t\t\t\t\tBOX_ROUND_BOTTOM_LEFT,\n\t\t\t\t\tBOX_ROUND_BOTTOM_RIGHT,\n\t\t\t\t\tfooterText,\n\t\t\t\t\toptions.expandHint ? theme.fg(\"dim\", options.expandHint) : undefined,\n\t\t\t\t\trenderedWidth,\n\t\t\t\t),\n\t\t\t];\n\t\t\tcache = { width, lines: rendered };\n\t\t\treturn rendered;\n\t\t},\n\t};\n}\n\nexport function formatBoxedWallTime(result: MetricResultLike | undefined): string {\n\tconst elapsedMs = getElapsedMs(result);\n\tif (elapsedMs === undefined) return \"--\";\n\treturn `${(elapsedMs / 1000).toFixed(2)}s`;\n}\n\nexport function formatBoxedFooterFromValues(\n\ttheme: BoxTheme,\n\telapsedMs: number | undefined,\n\toutput: string,\n\textraParts: string[] = [],\n): string {\n\tconst wall = elapsedMs === undefined ? \"--\" : `${(elapsedMs / 1000).toFixed(2)}s`;\n\tconst elapsedPart = theme.fg(\"text\", wall);\n\tconst extraPartList = extraParts.filter(Boolean).map((part) => theme.fg(\"dim\", part));\n\tconst wordsPart = theme.fg(\"dim\", formatBoxedWords(output));\n\treturn [elapsedPart, ...extraPartList, wordsPart].join(theme.fg(\"dim\", \" · \"));\n}\n\nfunction formatBoxedFooterParts(\n\ttheme: BoxTheme,\n\tresult: MetricResultLike | undefined,\n\textraParts: string[] = [],\n\telapsedMs?: number,\n): string {\n\treturn formatBoxedFooterFromValues(theme, elapsedMs ?? getElapsedMs(result), getTextOutput(result), extraParts);\n}\n\nexport function formatBoxedFooter(\n\ttheme: BoxTheme,\n\tresult: MetricResultLike | undefined,\n\textraParts: string[] = [],\n\telapsedMs?: number,\n): string {\n\treturn formatBoxedFooterParts(theme, result, extraParts, elapsedMs);\n}\n\nexport function renderCompactBoxedFooter(\n\ttheme: BoxTheme,\n\tresult: MetricResultLike | undefined,\n\toptions: BoxedRenderOptions = {},\n): Component {\n\tif (options.state && typeof options.state === \"object\") {\n\t\toptions.state[COMPACT_FOOTER_KEY] = formatBoxedFooterParts(theme, result, [], options.elapsedMs);\n\t\toptions.state[COMPACT_FOOTER_ERROR_KEY] = Boolean(options.isError);\n\t\toptions.state[COMPACT_FOOTER_PARTIAL_KEY] = Boolean(options.isPartial);\n\t\treturn { invalidate() {}, render: () => [] };\n\t}\n\n\treturn {\n\t\tinvalidate() {},\n\t\trender(width: number): string[] {\n\t\t\tconst renderedWidth = boxWidth(width);\n\t\t\treturn [\n\t\t\t\tboxLabeledBorder(\n\t\t\t\t\ttheme,\n\t\t\t\t\tBOX_ROUND_BOTTOM_LEFT,\n\t\t\t\t\tBOX_ROUND_BOTTOM_RIGHT,\n\t\t\t\t\tformatBoxedFooterParts(theme, result, [], options.elapsedMs),\n\t\t\t\t\tundefined,\n\t\t\t\t\trenderedWidth,\n\t\t\t\t),\n\t\t\t];\n\t\t},\n\t};\n}\n\nconst TOOL_BODY_INDENT = 2;\nconst TOOL_RIGHT_MARGIN = 1;\n\nexport function renderToolCallHeader(\n\ttheme: BoxTheme,\n\tlabel: string,\n\tdetail: string,\n\tskipTextColor?: boolean,\n): Component {\n\treturn renderToolCallHeaderLines(theme, label, [parens(theme, detail, skipTextColor)]);\n}\n\nexport function getToolBodyWidth(width: number, spaces = TOOL_BODY_INDENT): number {\n\treturn Math.max(1, width - spaces - TOOL_RIGHT_MARGIN);\n}\n\nexport function renderToolCallHeaderLines(theme: BoxTheme, label: string, detailLines: string[]): Component {\n\tconst prefix = `${badge(theme, label)} `;\n\tconst indent = \" \".repeat(safeVisibleWidth(prefix));\n\treturn {\n\t\tinvalidate() {},\n\t\trender(width: number): string[] {\n\t\t\tconst bodyWidth = Math.max(1, width - safeVisibleWidth(prefix) - TOOL_RIGHT_MARGIN);\n\t\t\tconst output: string[] = [];\n\t\t\tfor (let i = 0; i < detailLines.length; i++) {\n\t\t\t\tconst wrapped = safeWrapTextWithAnsi(detailLines[i] ?? \"\", bodyWidth);\n\t\t\t\tif (i === 0) {\n\t\t\t\t\toutput.push(`${prefix}${wrapped[0] ?? \"\"}`);\n\t\t\t\t\toutput.push(...wrapped.slice(1).map((line) => `${indent}${line}`));\n\t\t\t\t} else {\n\t\t\t\t\toutput.push(...wrapped.map((line) => `${indent}${line}`));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn output.length > 0 ? output : [prefix.trimEnd()];\n\t\t},\n\t};\n}\n\nexport function indentToolBody(text: string, spaces = TOOL_BODY_INDENT): string {\n\tconst indent = \" \".repeat(spaces);\n\treturn text\n\t\t.split(\"\\n\")\n\t\t.map((line) => (line.length === 0 ? line : `${indent}${line}`))\n\t\t.join(\"\\n\");\n}\n\nexport function indentToolBodyLines(lines: string[], spaces = TOOL_BODY_INDENT): string[] {\n\tconst indent = \" \".repeat(spaces);\n\treturn lines.map((line) => (line.length === 0 ? line : `${indent}${line}`));\n}\n\nexport function formatToolOutputLine(\n\ttheme: BoxTheme,\n\tline: string,\n\tcolor: \"toolOutput\" | \"error\" | \"text\" = \"toolOutput\",\n): string {\n\tif (color === \"error\") return theme.fg(\"error\", line);\n\n\tconst clean = stripAnsi(line);\n\tif (/^##\\s/.test(clean)) return theme.fg(\"muted\", line);\n\tif (/^\\?\\?\\s/.test(clean))\n\t\treturn theme.bold ? theme.bold(theme.fg(\"syntaxVariable\", line)) : theme.fg(\"syntaxVariable\", line);\n\n\treturn theme.fg(color, line);\n}\n\nexport function selectRenderLines(text: string, maxLines: number, tail = false): { lines: string[]; omitted: number } {\n\tconst source = text ?? \"\";\n\tif (!source) return { lines: [], omitted: 0 };\n\tconst limit = Math.max(0, maxLines);\n\tconst selected: string[] = [];\n\tlet lineCount = 0;\n\tlet lineStart = 0;\n\n\tfor (let i = 0; i <= source.length; i++) {\n\t\tif (i < source.length && source[i] !== \"\\n\") continue;\n\t\tconst rawLine = source.slice(lineStart, i).replace(/\\r/g, \"\");\n\t\tlineCount++;\n\t\tif (limit > 0) {\n\t\t\tconst line = clampRenderLine(rawLine);\n\t\t\tif (tail) {\n\t\t\t\tselected.push(line);\n\t\t\t\tif (selected.length > limit) selected.shift();\n\t\t\t} else if (selected.length < limit) {\n\t\t\t\tselected.push(line);\n\t\t\t}\n\t\t}\n\t\tlineStart = i + 1;\n\t}\n\n\tif (selected.length === 1 && selected[0] === \"\") return { lines: [], omitted: 0 };\n\treturn { lines: selected, omitted: Math.max(0, lineCount - selected.length) };\n}\n\nexport function renderLines(\n\ttheme: BoxTheme,\n\ttext: string,\n\toptions: { expanded?: boolean },\n\tcfg: { maxLines: number; tail?: boolean; color?: \"toolOutput\" | \"error\"; width?: number } = { maxLines: 10 },\n): string {\n\tconst color = cfg.color ?? \"toolOutput\";\n\tconst { lines, omitted } = selectRenderLines(text, cfg.maxLines, cfg.tail);\n\tconst renderWidth = cfg.width ? getToolBodyWidth(cfg.width) : undefined;\n\tconst renderLine = (line: string) => {\n\t\tconst rendered = renderWidth ? safeTruncateToWidth(line, renderWidth, \"…\") : line;\n\t\treturn formatToolOutputLine(theme, rendered, color);\n\t};\n\n\tif (lines.length === 0) return \"\";\n\n\tlet output = lines.map(renderLine).join(\"\\n\");\n\tif (omitted <= 0) return output;\n\n\tconst hintText = isExpanded(options)\n\t\t? `... ${omitted} more lines omitted by render budget`\n\t\t: `... ${omitted} more lines, press Ctrl+o to expand`;\n\tconst hint = cfg.width ? safeTruncateToWidth(hintText, Math.max(1, cfg.width - 1), \"…\") : hintText;\n\toutput += theme.fg(\"muted\", `\\n\\n${hint}`);\n\n\treturn output;\n}\n\nexport function dimWithElapsed(theme: BoxTheme, summary: string, result: MetricResultLike | undefined): string {\n\tconst metrics = formatToolMetrics(result);\n\treturn metrics\n\t\t? `${theme.fg(\"dim\", summary)} ${theme.fg(\"dim\", \"–\")} ${theme.italic ? theme.italic(theme.fg(\"muted\", metrics)) : theme.fg(\"muted\", metrics)}`\n\t\t: theme.fg(\"dim\", summary);\n}\n\nexport function renderToolMetricsFooter(theme: BoxTheme, _width: number, metrics: string): string[] {\n\treturn metrics\n\t\t? [theme.italic ? theme.italic(theme.fg(\"muted\", `↳ ${metrics}`)) : theme.fg(\"muted\", `↳ ${metrics}`)]\n\t\t: [];\n}\n\nexport type { MetricResultLike };\n// Re-exported metric helpers so renderers import from a single box module.\nexport { getElapsedMs };\n","// Tool metrics: elapsed wall time + output size formatting and annotation.\n\nconst ELAPSED_KEY = \"__elapsedMs\";\nconst OUTPUT_CHARS_KEY = \"__outputChars\";\n\nexport interface MetricResultLike {\n\treadonly content?: readonly unknown[];\n\treadonly details?: unknown;\n}\n\nfunction getTextOutputLength(result: MetricResultLike): number {\n\tif (!Array.isArray(result.content)) return 0;\n\tlet length = 0;\n\tlet seenText = false;\n\tfor (const contentBlock of result.content) {\n\t\tif (!contentBlock || typeof contentBlock !== \"object\") continue;\n\t\tconst block = contentBlock as { type?: unknown; text?: unknown };\n\t\tif (block.type !== \"text\") continue;\n\t\tif (seenText) length += 1; // matches getTextOutput() joining text blocks with newlines\n\t\tlength += String(block.text ?? \"\").replace(/\\r/g, \"\").length;\n\t\tseenText = true;\n\t}\n\treturn length;\n}\n\nfunction formatCompactCount(value: number): string {\n\tif (value < 1000) return `${Math.round(value)}`;\n\tif (value < 10000) return `${(value / 1000).toFixed(1)}k`;\n\tif (value < 1000000) return `${Math.round(value / 1000)}k`;\n\tif (value < 10000000) return `${(value / 1000000).toFixed(1)}M`;\n\treturn `${Math.round(value / 1000000)}M`;\n}\n\nexport function formatElapsedMs(ms: number | undefined): string {\n\tif (typeof ms !== \"number\" || !Number.isFinite(ms)) return \"\";\n\tif (ms < 1000) return `${Math.round(ms)}ms`;\n\tconst s = ms / 1000;\n\treturn s < 10 ? `${s.toFixed(1)}s` : `${Math.round(s)}s`;\n}\n\nexport function formatOutputChars(chars: number | undefined): string {\n\tif (typeof chars !== \"number\" || !Number.isFinite(chars) || chars <= 0) return \"\";\n\treturn `${formatCompactCount(chars)} ${chars === 1 ? \"char\" : \"chars\"}`;\n}\n\nexport function formatToolMetricsFromValues(elapsedMs: number | undefined, outputChars: number | undefined): string {\n\treturn [formatElapsedMs(elapsedMs), formatOutputChars(outputChars)].filter(Boolean).join(\" · \");\n}\n\nexport function getElapsedMs(result: MetricResultLike | undefined): number | undefined {\n\tif (!result || typeof result.details !== \"object\" || result.details === null) return undefined;\n\tconst elapsed = (result.details as Record<string, unknown>)[ELAPSED_KEY];\n\treturn typeof elapsed === \"number\" && Number.isFinite(elapsed) ? elapsed : undefined;\n}\n\nexport function formatElapsed(result: MetricResultLike | undefined): string {\n\treturn formatElapsedMs(getElapsedMs(result));\n}\n\nexport function formatOutputSize(result: MetricResultLike | undefined): string {\n\treturn formatOutputChars(\n\t\t(result?.details as Record<string, unknown> | undefined)?.[OUTPUT_CHARS_KEY] as number | undefined,\n\t);\n}\n\nexport function formatToolMetrics(result: MetricResultLike | undefined): string {\n\treturn [formatElapsed(result), formatOutputSize(result)].filter(Boolean).join(\" · \");\n}\n\n/** Annotate elapsed/output metrics into a result's details (only when absent). */\nexport function annotateToolResultMetrics(result: MetricResultLike | undefined, elapsedMs?: number): void {\n\tif (!result || typeof result !== \"object\") return;\n\tif (!result.details || typeof result.details !== \"object\") {\n\t\t(result as { details?: unknown }).details = {};\n\t}\n\tconst details = result.details as Record<string, unknown>;\n\tconst existingElapsed = details[ELAPSED_KEY];\n\tif (\n\t\ttypeof elapsedMs === \"number\" &&\n\t\tNumber.isFinite(elapsedMs) &&\n\t\t(typeof existingElapsed !== \"number\" || !Number.isFinite(existingElapsed))\n\t) {\n\t\tdetails[ELAPSED_KEY] = elapsedMs;\n\t}\n\tif (typeof details[OUTPUT_CHARS_KEY] !== \"number\" || !Number.isFinite(details[OUTPUT_CHARS_KEY])) {\n\t\tdetails[OUTPUT_CHARS_KEY] = getTextOutputLength(result);\n\t}\n}\n","// Render budget + ANSI-safe width/truncation/wrapping helpers for boxed tool\n// presentation.\n\nimport {\n\ttruncateToWidth as tuiTruncateToWidth,\n\tvisibleWidth as tuiVisibleWidth,\n\twrapTextWithAnsi,\n} from \"@earendil-works/pi-tui\";\n\nexport const MAX_RENDER_LINE_CHARS = 2000;\nexport const DEFAULT_COLLAPSED_RENDER_LINES = 10;\nexport const MAX_BOXED_RESULT_RENDERED_HEAD_LINES = 40;\nexport const MAX_BOXED_RESULT_RENDERED_TAIL_LINES = 8;\nexport const MAX_BOXED_RESULT_RENDERED_LINES = 160;\n\nconst RENDER_TRUNCATION_SUFFIX = \"… (truncated)\";\nconst TRUNCATE_ELLIPSIS = \"…\";\nconst ANSI_RESET = \"\\x1b[0m\";\nconst ESC = \"\\x1b\";\nconst SGR_PREFIX_PATTERN = new RegExp(`^(?:${ESC}\\\\[[0-9;]*m)+`);\nconst SGR_SUFFIX_PATTERN = new RegExp(`(?:${ESC}\\\\[[0-9;]*m)+$`);\n\ntype SimpleSgrWrappedText = {\n\tprefix: string;\n\tbody: string;\n\tsuffix: string;\n\tkind: \"sgrAscii\" | \"sgrSimple\";\n};\n\ntype FastTextKind = \"ascii\" | \"sgrAscii\" | \"simple\" | \"sgrSimple\";\n\ntype FastTextWidth = {\n\tvisibleWidth: number;\n\tkind: FastTextKind;\n};\n\ntype FastTruncateResult = {\n\ttext: string;\n\tvisibleWidth: number;\n\tkind: FastTextKind;\n};\n\nexport type FastBoxLineContent = {\n\ttext: string;\n\tvisibleWidth: number;\n\tkind: FastTextKind;\n};\n\nexport type BoxedResultRenderBudget = {\n\theadLines: number;\n\ttailLines: number;\n\tmaxRenderedLines: number;\n};\n\n/**\n * Cut a string to a maximum UTF-16 length without splitting a surrogate pair\n * (emoji / supplementary-plane characters). A plain `slice` on a non-ASCII\n * boundary produces a lone surrogate that renders as the U+FFFD replacement\n * character (�).\n */\nexport function truncateAtCodePointBoundary(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\tconst code = text.charCodeAt(maxChars);\n\tconst end = code >= 0xdc00 && code <= 0xdfff ? maxChars - 1 : maxChars;\n\treturn text.slice(0, end);\n}\n\nexport function clampRenderLine(line: string, maxChars = MAX_RENDER_LINE_CHARS): string {\n\tif (line.length <= maxChars) return line;\n\treturn truncateAtCodePointBoundary(line, maxChars) + RENDER_TRUNCATION_SUFFIX;\n}\n\nfunction isPrintableAsciiCode(code: number): boolean {\n\treturn code >= 0x20 && code <= 0x7e;\n}\n\nfunction isSimpleWidthOneGlyphCode(code: number): boolean {\n\tif (code >= 0x2500 && code <= 0x257f) return true; // box drawing\n\tif (code >= 0x2580 && code <= 0x259f) return true; // block elements\n\tif (code >= 0x25a0 && code <= 0x25ff) return true; // geometric shapes used by UI status marks\n\tif (code >= 0x2800 && code <= 0x28ff) return true; // braille loader frames\n\treturn (\n\t\tcode === 0x00b2 || // ²\n\t\tcode === 0x00b7 || // ·\n\t\tcode === 0x03c0 || // π\n\t\tcode === 0x2013 || // –\n\t\tcode === 0x2014 || // —\n\t\tcode === 0x2022 || // •\n\t\tcode === 0x2026 || // …\n\t\tcode === 0x2191 || // ↑\n\t\tcode === 0x2192 || // →\n\t\tcode === 0x2193 || // ↓\n\t\tcode === 0x21b3 || // ↳\n\t\tcode === 0x2205 || // ∅\n\t\tcode === 0x2248 || // ≈\n\t\tcode === 0x22ef || // ⋯\n\t\tcode === 0x2387 || // ⎇\n\t\tcode === 0x23f9 || // ⏹\n\t\tcode === 0x270e || // ✎\n\t\tcode === 0x2713 || // ✓\n\t\tcode === 0x2717 || // ✗\n\t\tcode === 0x276f || // ❯\n\t\tcode === 0x2794 // ➔\n\t);\n}\n\nfunction isSimpleWidthOneCode(code: number): boolean {\n\treturn isPrintableAsciiCode(code) || isSimpleWidthOneGlyphCode(code);\n}\n\nfunction breakLongAsciiWord(word: string, width: number): string[] {\n\tconst lines: string[] = [];\n\tfor (let i = 0; i < word.length; i += width) {\n\t\tlines.push(word.slice(i, i + width));\n\t}\n\treturn lines.length > 0 ? lines : [\"\"];\n}\n\nfunction wrapPrintableAsciiLine(line: string, width: number): string[] {\n\tif (!line) return [\"\"];\n\tif (line.length <= width) return [line];\n\n\tconst wrapped: string[] = [];\n\tlet currentLine = \"\";\n\tlet currentVisibleLength = 0;\n\tlet tokenStart = 0;\n\n\twhile (tokenStart < line.length) {\n\t\tconst tokenIsSpace = line[tokenStart] === \" \";\n\t\tlet tokenEnd = tokenStart + 1;\n\t\twhile (tokenEnd < line.length && (line[tokenEnd] === \" \") === tokenIsSpace) tokenEnd++;\n\n\t\tconst token = line.slice(tokenStart, tokenEnd);\n\t\tconst tokenVisibleLength = token.length;\n\t\tif (tokenVisibleLength > width && !tokenIsSpace) {\n\t\t\tif (currentLine) {\n\t\t\t\twrapped.push(currentLine.trimEnd());\n\t\t\t\tcurrentLine = \"\";\n\t\t\t\tcurrentVisibleLength = 0;\n\t\t\t}\n\t\t\tconst broken = breakLongAsciiWord(token, width);\n\t\t\twrapped.push(...broken.slice(0, -1));\n\t\t\tcurrentLine = broken[broken.length - 1] ?? \"\";\n\t\t\tcurrentVisibleLength = currentLine.length;\n\t\t\ttokenStart = tokenEnd;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst totalNeeded = currentVisibleLength + tokenVisibleLength;\n\t\tif (totalNeeded > width && currentVisibleLength > 0) {\n\t\t\twrapped.push(currentLine.trimEnd());\n\t\t\tif (tokenIsSpace) {\n\t\t\t\tcurrentLine = \"\";\n\t\t\t\tcurrentVisibleLength = 0;\n\t\t\t} else {\n\t\t\t\tcurrentLine = token;\n\t\t\t\tcurrentVisibleLength = tokenVisibleLength;\n\t\t\t}\n\t\t} else {\n\t\t\tcurrentLine += token;\n\t\t\tcurrentVisibleLength += tokenVisibleLength;\n\t\t}\n\n\t\ttokenStart = tokenEnd;\n\t}\n\n\tif (currentLine) wrapped.push(currentLine);\n\treturn wrapped.length > 0 ? wrapped.map((wrappedLine) => wrappedLine.trimEnd()) : [\"\"];\n}\n\nfunction matchSimpleSgrWrappedText(text: string): SimpleSgrWrappedText | null {\n\tconst prefixMatch = SGR_PREFIX_PATTERN.exec(text);\n\tconst suffixMatch = SGR_SUFFIX_PATTERN.exec(text);\n\tif (!prefixMatch || !suffixMatch) return null;\n\tconst prefix = prefixMatch[0];\n\tconst suffix = suffixMatch[0];\n\tconst bodyStart = prefix.length;\n\tconst bodyEnd = suffixMatch.index;\n\tif (bodyEnd < bodyStart) return null;\n\n\tconst body = text.slice(bodyStart, bodyEnd);\n\tconst bodyWidth = knownVisibleWidth(body);\n\tif (!bodyWidth || bodyWidth.kind === \"sgrAscii\" || bodyWidth.kind === \"sgrSimple\") return null;\n\treturn { prefix, body, suffix, kind: bodyWidth.kind === \"ascii\" ? \"sgrAscii\" : \"sgrSimple\" };\n}\n\nfunction wrapSimpleSgrWrappedText(\n\ttext: string,\n\twidth: number,\n): { lines: string[]; kind: \"sgrAscii\" | \"sgrSimple\" } | null {\n\tconst match = matchSimpleSgrWrappedText(text);\n\tif (!match) return null;\n\treturn {\n\t\tlines: wrapPrintableAsciiLine(match.body, width).map((line) => `${match.prefix}${line}${match.suffix}`),\n\t\tkind: match.kind,\n\t};\n}\n\nfunction readSgrSequenceEnd(text: string, offset: number): number {\n\tif (text.charCodeAt(offset) !== 0x1b || text[offset + 1] !== \"[\") return -1;\n\tlet cursor = offset + 2;\n\twhile (cursor < text.length) {\n\t\tconst code = text.charCodeAt(cursor);\n\t\tif (code === 0x6d) return cursor + 1; // m\n\t\tif (code !== 0x3b && (code < 0x30 || code > 0x39)) return -1; // ; or 0-9\n\t\tcursor++;\n\t}\n\treturn -1;\n}\n\nfunction knownVisibleWidth(text: string): FastTextWidth | null {\n\tlet width = 0;\n\tlet sawSgr = false;\n\tlet sawSimpleGlyph = false;\n\tfor (let i = 0; i < text.length; ) {\n\t\tconst sgrEnd = readSgrSequenceEnd(text, i);\n\t\tif (sgrEnd > i) {\n\t\t\tsawSgr = true;\n\t\t\ti = sgrEnd;\n\t\t\tcontinue;\n\t\t}\n\t\tconst code = text.charCodeAt(i);\n\t\tif (!isSimpleWidthOneCode(code)) return null;\n\t\tif (!isPrintableAsciiCode(code)) sawSimpleGlyph = true;\n\t\twidth++;\n\t\ti++;\n\t}\n\tif (sawSgr) return { visibleWidth: width, kind: sawSimpleGlyph ? \"sgrSimple\" : \"sgrAscii\" };\n\treturn { visibleWidth: width, kind: sawSimpleGlyph ? \"simple\" : \"ascii\" };\n}\n\nfunction knownEllipsisWidth(text: string): number | null {\n\tif (text === TRUNCATE_ELLIPSIS) return 1;\n\treturn knownVisibleWidth(text)?.visibleWidth ?? null;\n}\n\nfunction truncatePrintableAscii(\n\ttext: string,\n\twidth: number,\n\tellipsis = TRUNCATE_ELLIPSIS,\n): { text: string; visibleWidth: number } {\n\tif (width <= 0) return { text: \"\", visibleWidth: 0 };\n\tif (text.length <= width) return { text, visibleWidth: text.length };\n\tconst ellipsisWidth = knownEllipsisWidth(ellipsis);\n\tif (ellipsisWidth === null) return { text: text.slice(0, width), visibleWidth: width };\n\tif (ellipsisWidth >= width) {\n\t\tif (ellipsis === TRUNCATE_ELLIPSIS) return { text: TRUNCATE_ELLIPSIS, visibleWidth: 1 };\n\t\treturn { text: ellipsis.slice(0, width), visibleWidth: Math.min(width, ellipsis.length) };\n\t}\n\tconst targetWidth = Math.max(0, width - ellipsisWidth);\n\treturn { text: `${text.slice(0, targetWidth)}${ellipsis}`, visibleWidth: targetWidth + ellipsisWidth };\n}\n\nfunction truncateSgrAscii(\n\ttext: string,\n\twidth: number,\n\tellipsis: string,\n\tvisibleWidth: number,\n): { text: string; visibleWidth: number } | null {\n\tif (visibleWidth <= width) return { text, visibleWidth };\n\tconst ellipsisWidth = knownEllipsisWidth(ellipsis);\n\tif (ellipsisWidth === null) return null;\n\tif (ellipsisWidth >= width) return truncatePrintableAscii(ellipsis, width, \"\");\n\n\tconst targetWidth = Math.max(0, width - ellipsisWidth);\n\tlet keptWidth = 0;\n\tlet output = \"\";\n\tfor (let i = 0; i < text.length && keptWidth < targetWidth; ) {\n\t\tconst sgrEnd = readSgrSequenceEnd(text, i);\n\t\tif (sgrEnd > i) {\n\t\t\toutput += text.slice(i, sgrEnd);\n\t\t\ti = sgrEnd;\n\t\t\tcontinue;\n\t\t}\n\t\tconst code = text.charCodeAt(i);\n\t\tif (!isSimpleWidthOneCode(code)) return null;\n\t\toutput += text[i] ?? \"\";\n\t\tkeptWidth++;\n\t\ti++;\n\t}\n\treturn { text: `${output}${ANSI_RESET}${ellipsis}${ANSI_RESET}`, visibleWidth: keptWidth + ellipsisWidth };\n}\n\nfunction fastTruncateText(text: string, width: number, ellipsis = TRUNCATE_ELLIPSIS): FastTruncateResult | null {\n\tconst knownWidth = knownVisibleWidth(text);\n\tif (!knownWidth) return null;\n\tif (knownWidth.kind === \"ascii\" || knownWidth.kind === \"simple\")\n\t\treturn { ...truncatePrintableAscii(text, width, ellipsis), kind: knownWidth.kind };\n\n\tconst simple = matchSimpleSgrWrappedText(text);\n\tif (simple) {\n\t\tconst truncated = truncatePrintableAscii(simple.body, width, ellipsis);\n\t\treturn {\n\t\t\ttext: `${simple.prefix}${truncated.text}${simple.suffix}`,\n\t\t\tvisibleWidth: truncated.visibleWidth,\n\t\t\tkind: simple.kind,\n\t\t};\n\t}\n\n\tconst truncated = truncateSgrAscii(text, width, ellipsis, knownWidth.visibleWidth);\n\treturn truncated ? { ...truncated, kind: knownWidth.kind } : null;\n}\n\nexport function safeVisibleWidth(text: string): number {\n\tconst fastWidth = knownVisibleWidth(text);\n\tif (fastWidth) return fastWidth.visibleWidth;\n\tif (text === TRUNCATE_ELLIPSIS) return 1;\n\treturn tuiVisibleWidth(text);\n}\n\nexport function safeTruncateToWidth(text: string, maxWidth: number, ellipsis = \"...\", pad = false): string {\n\tconst width = Math.floor(maxWidth);\n\tif (!Number.isFinite(width) || width <= 0) return \"\";\n\tif (text.length === 0) return pad ? \" \".repeat(width) : \"\";\n\n\tconst truncated = fastTruncateText(text, width, ellipsis);\n\tif (truncated)\n\t\treturn pad ? `${truncated.text}${\" \".repeat(Math.max(0, width - truncated.visibleWidth))}` : truncated.text;\n\n\treturn tuiTruncateToWidth(text, maxWidth, ellipsis, pad);\n}\n\nexport function fastBoxLineContent(content: string, width: number): FastBoxLineContent | null {\n\tconst contentWidth = Math.floor(width);\n\tif (!Number.isFinite(contentWidth) || contentWidth <= 0) return null;\n\n\treturn fastTruncateText(content, contentWidth);\n}\n\nexport function safeWrapTextWithAnsi(text: string, width: number, maxChars = MAX_RENDER_LINE_CHARS): string[] {\n\tconst clamped = clampRenderLine(text, maxChars);\n\tconst wrapWidth = Math.floor(width);\n\tif (!Number.isFinite(wrapWidth) || wrapWidth <= 0) {\n\t\treturn wrapTextWithAnsi(clamped, width);\n\t}\n\tconst clampedWidth = knownVisibleWidth(clamped);\n\tif (clampedWidth?.kind === \"ascii\" || clampedWidth?.kind === \"simple\") {\n\t\treturn wrapPrintableAsciiLine(clamped, wrapWidth);\n\t}\n\tconst simpleSgrWrapped = wrapSimpleSgrWrappedText(clamped, wrapWidth);\n\tif (simpleSgrWrapped) {\n\t\treturn simpleSgrWrapped.lines;\n\t}\n\treturn wrapTextWithAnsi(clamped, width);\n}\n\nexport function boxedResultRenderBudget(\n\trawLineBudget: number = DEFAULT_COLLAPSED_RENDER_LINES,\n): BoxedResultRenderBudget {\n\tconst rawLines = Math.max(\n\t\t0,\n\t\tMath.floor(Number.isFinite(rawLineBudget) ? rawLineBudget : DEFAULT_COLLAPSED_RENDER_LINES),\n\t);\n\tconst maxRenderedLines = Math.max(1, Math.min(rawLines * 3, MAX_BOXED_RESULT_RENDERED_LINES));\n\tconst tailLines = Math.min(\n\t\tMath.ceil(rawLines * 0.15),\n\t\tMAX_BOXED_RESULT_RENDERED_TAIL_LINES,\n\t\tMath.max(0, maxRenderedLines - 1),\n\t);\n\tconst headLines = Math.min(\n\t\trawLines,\n\t\tMAX_BOXED_RESULT_RENDERED_HEAD_LINES,\n\t\tMath.max(1, maxRenderedLines - tailLines - 1),\n\t);\n\n\treturn { headLines, tailLines, maxRenderedLines };\n}\n","// Theme extras reader.\n//\n// Reads extension-specific \"extras\" plus raw theme vars/export values from the\n// active theme's JSON file on disk. Pi does not expose all of these raw values\n// through the theme object, so we locate and parse the file directly.\n//\n// pi-style constraint: no filesystem I/O inside render. The cache is populated\n// by `syncThemeExtras(theme, force)` at session start and on theme change; the\n// render-facing `getThemeExtra`/`getThemePageBackground`/`getThemeVarBackground`\n// read cached values only and return \"\" (graceful fallback) when unavailable.\n\nimport { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { isHexColor } from \"../shared/ansi.js\";\n\nconst extensionDir = dirname(fileURLToPath(import.meta.url));\n\nexport const THEME_EXTRA_DEFAULTS: Readonly<Record<string, string>> = Object.freeze({\n\tassistantPrefix: \"•\",\n\tassistantPrefixColor: \"\",\n\tdividerChar: \"─\",\n\tdividerColor: \"\",\n\tshowDivider: \"true\",\n\tquoteStyle: \"false\",\n\tquoteChar: \"┆\",\n\tquoteColor: \"\",\n\tinputBorderColor: \"\",\n\tbashPromptColor: \"\",\n\ttagBgColor: \"\",\n\tparensTextColor: \"\",\n\tparensBracketColor: \"\",\n\tslashSelectedColor: \"\",\n\tslashCommandColor: \"\",\n\tslashDescriptionColor: \"\",\n\tslashHintColor: \"\",\n\tuserBoxBorderColor: \"\",\n\tgitInsertionColor: \"#2ea043\",\n\tgitDeletionColor: \"#f85149\",\n});\n\nlet cachedExtras: Record<string, string | boolean> | null = null;\nlet cachedVars: Record<string, string> | null = null;\nlet cachedColors: Record<string, string> | null = null;\nlet cachedThemeExport: Record<string, string> | null = null;\nlet cachedThemeName: string | null = null;\n\ntype ThemeDiscovery = {\n\textras: Record<string, string | boolean> | null;\n\tvars: Record<string, string> | null;\n\tcolors: Record<string, string> | null;\n\tthemeExport: Record<string, string> | null;\n};\n\nfunction themeDiscoveryFromContent(content: unknown): ThemeDiscovery | null {\n\tif (!content || typeof content !== \"object\") return null;\n\tconst record = content as Record<string, unknown>;\n\tconst extras =\n\t\trecord.extras && typeof record.extras === \"object\" ? (record.extras as Record<string, string | boolean>) : null;\n\tconst vars = record.vars && typeof record.vars === \"object\" ? (record.vars as Record<string, string>) : null;\n\tconst colors = record.colors && typeof record.colors === \"object\" ? (record.colors as Record<string, string>) : null;\n\tconst themeExport =\n\t\trecord.export && typeof record.export === \"object\" ? (record.export as Record<string, string>) : null;\n\treturn extras || vars || colors || themeExport ? { extras, vars, colors, themeExport } : null;\n}\n\nfunction readThemeDiscoveryFromPath(filePath: string): ThemeDiscovery | null {\n\ttry {\n\t\tif (!filePath || !existsSync(filePath)) return null;\n\t\tconst content = JSON.parse(readFileSync(filePath, \"utf-8\")) as unknown;\n\t\treturn themeDiscoveryFromContent(content);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction resolveThemeSourcePath(theme: unknown): string {\n\tif (!theme || typeof theme !== \"object\") return \"\";\n\tconst record = theme as Record<string, unknown>;\n\tif (typeof record.sourcePath === \"string\") return record.sourcePath;\n\tconst definition =\n\t\trecord.definition && typeof record.definition === \"object\"\n\t\t\t? (record.definition as Record<string, unknown>)\n\t\t\t: undefined;\n\treturn typeof definition?.sourcePath === \"string\" ? definition.sourcePath : \"\";\n}\n\nfunction addThemeDir(searchDirs: Set<string>, dir: string): void {\n\tif (existsSync(dir)) searchDirs.add(dir);\n}\n\nfunction addBundledThemeDirs(searchDirs: Set<string>): void {\n\tfor (const root of [extensionDir, process.cwd()]) {\n\t\tfor (const scope of [\"@earendil-works\", \"@mariozechner\"]) {\n\t\t\taddThemeDir(\n\t\t\t\tsearchDirs,\n\t\t\t\tresolve(root, \"node_modules\", scope, \"pi-coding-agent\", \"dist\", \"modes\", \"interactive\", \"theme\"),\n\t\t\t);\n\t\t\taddThemeDir(searchDirs, resolve(root, \"node_modules\", scope, \"pi-coding-agent\", \"dist\", \"theme\"));\n\t\t}\n\t}\n}\n\nfunction collectThemeDirs(root: string, searchDirs: Set<string>, maxDepth = 4): void {\n\tif (maxDepth < 0 || !existsSync(root)) return;\n\ttry {\n\t\tfor (const entry of readdirSync(root, { withFileTypes: true })) {\n\t\t\tif (!entry.isDirectory() || entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n\t\t\tconst dir = join(root, entry.name);\n\t\t\tif (entry.name === \"themes\") {\n\t\t\t\tsearchDirs.add(dir);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcollectThemeDirs(dir, searchDirs, maxDepth - 1);\n\t\t}\n\t} catch {\n\t\t// best effort discovery only\n\t}\n}\n\nfunction readSettingsPackagePaths(settingsPath: string): string[] {\n\tif (!existsSync(settingsPath)) return [];\n\ttry {\n\t\tconst settings = JSON.parse(readFileSync(settingsPath, \"utf-8\")) as Record<string, unknown>;\n\t\tconst entries = [\n\t\t\t...(Array.isArray(settings.packages) ? settings.packages : []),\n\t\t\t...(Array.isArray(settings.extensions) ? settings.extensions : []),\n\t\t];\n\t\treturn entries\n\t\t\t.map((entry) =>\n\t\t\t\ttypeof entry === \"string\"\n\t\t\t\t\t? entry\n\t\t\t\t\t: entry && typeof entry === \"object\"\n\t\t\t\t\t\t? String((entry as Record<string, unknown>).source ?? \"\")\n\t\t\t\t\t\t: \"\",\n\t\t\t)\n\t\t\t.filter((entry) => entry && !entry.startsWith(\"npm:\") && !entry.startsWith(\"git:\"));\n\t} catch {\n\t\treturn [];\n\t}\n}\n\n/** Scan known theme directories for a JSON file whose \"name\" matches themeName. */\nfunction discoverThemeExtras(themeName: string): ThemeDiscovery | null {\n\tconst searchDirs = new Set<string>();\n\n\taddThemeDir(searchDirs, join(homedir(), \".pi\", \"agent\", \"themes\"));\n\taddThemeDir(searchDirs, resolve(process.cwd(), \".pi\", \"themes\"));\n\taddBundledThemeDirs(searchDirs);\n\tcollectThemeDirs(join(homedir(), \".pi\", \"agent\", \"git\"), searchDirs);\n\tcollectThemeDirs(resolve(process.cwd(), \".pi\", \"git\"), searchDirs);\n\n\tconst localPackagePaths = [\n\t\t...readSettingsPackagePaths(join(homedir(), \".pi\", \"agent\", \"settings.json\")),\n\t\t...readSettingsPackagePaths(resolve(process.cwd(), \".pi\", \"settings.json\")),\n\t];\n\tfor (const packagePath of localPackagePaths) {\n\t\taddThemeDir(searchDirs, resolve(process.cwd(), packagePath, \"themes\"));\n\t}\n\n\tfor (const dir of searchDirs) {\n\t\ttry {\n\t\t\tfor (const file of readdirSync(dir)) {\n\t\t\t\tif (!file.endsWith(\".json\")) continue;\n\t\t\t\tconst filePath = join(dir, file);\n\t\t\t\ttry {\n\t\t\t\t\tconst content = JSON.parse(readFileSync(filePath, \"utf-8\")) as Record<string, unknown>;\n\t\t\t\t\tif (content?.name === themeName) {\n\t\t\t\t\t\tconst result = themeDiscoveryFromContent(content);\n\t\t\t\t\t\tif (result) return result;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// skip unparsable theme files\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// skip unreadable directories\n\t\t}\n\t}\n\n\treturn null;\n}\n\nfunction resolveThemeName(theme: unknown): string | null {\n\tif (!theme || typeof theme !== \"object\") return null;\n\tconst record = theme as Record<string, unknown>;\n\tconst definition =\n\t\trecord.definition && typeof record.definition === \"object\"\n\t\t\t? (record.definition as Record<string, unknown>)\n\t\t\t: undefined;\n\tif (typeof definition?.name === \"string\") return definition.name;\n\tif (typeof record.name === \"string\") return record.name;\n\ttry {\n\t\tconst settingsPath = join(homedir(), \".pi\", \"agent\", \"settings.json\");\n\t\tif (existsSync(settingsPath)) {\n\t\t\tconst settings = JSON.parse(readFileSync(settingsPath, \"utf-8\")) as Record<string, unknown>;\n\t\t\tif (typeof settings.theme === \"string\") return settings.theme;\n\t\t}\n\t} catch {\n\t\t// fall through\n\t}\n\treturn null;\n}\n\nfunction readThemeToken(name: string): string {\n\tconst varValue = cachedVars && typeof cachedVars[name] === \"string\" ? cachedVars[name] : \"\";\n\tif (varValue) return varValue;\n\treturn cachedColors && typeof cachedColors[name] === \"string\" ? cachedColors[name] : \"\";\n}\n\nfunction resolveThemeColorToken(value: string): string {\n\tlet resolved = value;\n\tconst seen = new Set<string>();\n\tfor (let depth = 0; depth < 8; depth++) {\n\t\tif (!resolved) return \"\";\n\t\tif (isHexColor(resolved)) return resolved;\n\t\tif (seen.has(resolved)) return \"\";\n\t\tseen.add(resolved);\n\n\t\tconst next = readThemeToken(resolved);\n\t\tif (!next) return \"\";\n\t\tresolved = next;\n\t}\n\treturn \"\";\n}\n\nfunction resolveThemeExtraValue(key: string, value: string): string {\n\tif (!key.endsWith(\"Color\")) return value;\n\treturn resolveThemeColorToken(value) || value;\n}\n\nfunction resolveThemeExportColor(key: string): string {\n\tif (!cachedThemeExport) return \"\";\n\tconst value = cachedThemeExport[key];\n\tif (typeof value !== \"string\" || !value) return \"\";\n\tconst resolved = cachedVars && typeof cachedVars[value] === \"string\" ? cachedVars[value] : value;\n\treturn isHexColor(resolved) ? resolved : \"\";\n}\n\n/** Populate the extras cache from a theme (session start / theme change only). */\nexport function setFullTheme(theme: unknown, force = false): void {\n\tconst themeName = resolveThemeName(theme);\n\tconst sourcePath = resolveThemeSourcePath(theme);\n\tif (!themeName && !sourcePath) return;\n\n\tconst cacheKey = sourcePath || themeName;\n\tif (\n\t\t!force &&\n\t\tcacheKey === cachedThemeName &&\n\t\t(cachedExtras !== null || cachedVars !== null || cachedColors !== null || cachedThemeExport !== null)\n\t)\n\t\treturn;\n\n\tcachedThemeName = cacheKey;\n\tconst result = readThemeDiscoveryFromPath(sourcePath) ?? (themeName ? discoverThemeExtras(themeName) : null);\n\tcachedExtras = result?.extras ?? null;\n\tcachedVars = result?.vars ?? null;\n\tcachedColors = result?.colors ?? null;\n\tcachedThemeExport = result?.themeExport ?? null;\n}\n\nexport function resetThemeExtrasCache(): void {\n\tcachedExtras = null;\n\tcachedVars = null;\n\tcachedColors = null;\n\tcachedThemeExport = null;\n\tcachedThemeName = null;\n}\n\n/** Resolve a theme-extra key from the cache; \"\" when unavailable (graceful fallback). */\nexport function getThemeExtra(_theme: unknown, key: string): string {\n\tconst extraValue = cachedExtras?.[key];\n\tif (typeof extraValue === \"string\" || typeof extraValue === \"boolean\") {\n\t\treturn resolveThemeExtraValue(key, String(extraValue));\n\t}\n\treturn resolveThemeExtraValue(key, THEME_EXTRA_DEFAULTS[key] ?? \"\");\n}\n\nexport function getThemePageBackground(_theme: unknown): string {\n\tconst directBg = cachedVars && typeof cachedVars.bg === \"string\" ? cachedVars.bg : \"\";\n\tif (isHexColor(directBg)) return directBg;\n\treturn resolveThemeExportColor(\"pageBg\");\n}\n\nexport function getThemeVarBackground(_theme: unknown, varName: string): string {\n\tconst value = cachedVars && typeof cachedVars[varName] === \"string\" ? cachedVars[varName] : \"\";\n\tconst resolved = cachedVars && value && typeof cachedVars[value] === \"string\" ? cachedVars[value] : value;\n\treturn isHexColor(resolved) ? resolved : \"\";\n}\n","// Boxless output-tree primitives shared by the ls/find/grep/bash renderers.\n//\n// ls/find/grep and bash `ls/find/grep/rg` results render their parsed output as\n// a **boxless tree panel** — a summary header line followed by `├─/└─` rows —\n// instead of a boxed command/response shell. This module owns:\n//\n// - output parsers that turn native tool text (entries, paths, `file:line:`\n// match lines) into structured records, dropping trailing truncation notices;\n// - `renderOutputTree`, which lays out a flat list of entries under a header\n// (used by lone ls/find and bash ls/find);\n// - `renderGrepTree`, which lays out grep matches grouped by file (used by grep\n// and bash grep/rg).\n//\n// Design notes:\n// - Pure + theme-consuming: no filesystem, no global state, no caching (callers\n// cache at the component boundary).\n// - Every row is width-safe via safeTruncateToWidth; the header is never\n// truncated by this layer (callers pass a concise, pre-sized header).\n// - Tree indent matches the quiet-tool batch panel (` ├─`) so the panels read\n// as one visual family.\n\nimport type { BoxTheme } from \"../../../shared/box.js\";\nimport { dimLine } from \"../../../shared/box.js\";\nimport { safeTruncateToWidth } from \"../../../shared/render-budget.js\";\n\n/** Indent for top-level tree rows; matches the quiet-tool batch panel. */\nexport const TREE_INDENT = \" \";\n/** Extra indent for rows nested under a grouping node. */\nexport const TREE_CHILD_INDENT = \" \";\n/** Default number of entries/matches shown before collapsing to \"… N more\". */\nexport const OUTPUT_TREE_HEAD_LIMIT = 6;\n\n// ── Nerd Font file-type icons ───────────────────────────────────────────────\n// Only used when the session glyph mode is nerd (see withIcons). Unicode/ASCII\n// modes render plain entries.\n\nconst FILE_ICON_FOLDER = \"\\u{F415}\"; // (nf-md-folder)\nconst FILE_ICON_DEFAULT = \"\\u{E612}\"; // (nf-seti-default)\n/** Search (magnifying-glass) icon for find/grep headers (nf-fa-search). */\nexport const SEARCH_ICON = \"\\u{F002}\";\nconst FILE_ICONS: Readonly<Record<string, string>> = {\n\tts: \"\\u{E628}\", // (nf-seti-typescript)\n\ttsx: \"\\u{E7BA}\", // (nf-seti-react)\n\tjs: \"\\u{E62C}\", // (nf-seti-javascript)\n\tjsx: \"\\u{E7BA}\", // (nf-seti-react)\n\tmjs: \"\\u{E62C}\",\n\tcjs: \"\\u{E62C}\",\n\tjson: \"\\u{E62B}\", // (nf-seti-json)\n\tmd: \"\\u{E609}\", // (nf-seti-markdown)\n\tmdx: \"\\u{E609}\",\n\tcss: \"\\u{E749}\", // (nf-seti-css)\n\tscss: \"\\u{E749}\",\n\tsass: \"\\u{E749}\",\n\tless: \"\\u{E749}\",\n\thtml: \"\\u{E60E}\", // (nf-seti-html)\n\thtm: \"\\u{E60E}\",\n\tpy: \"\\u{E606}\", // (nf-seti-python)\n\tgo: \"\\u{E627}\", // (nf-seti-go)\n\trs: \"\\u{E7A8}\", // (nf-seti-rust)\n\tsh: \"\\u{E795}\", // (nf-seti-shell)\n\tbash: \"\\u{E795}\",\n\tzsh: \"\\u{E795}\",\n\tfish: \"\\u{E795}\",\n\tyml: \"\\u{E615}\", // (nf-seti-yaml)\n\tyaml: \"\\u{E615}\",\n\ttoml: \"\\u{E615}\",\n\tjava: \"\\u{E738}\", // (nf-seti-java)\n\tc: \"\\u{E61E}\", // (nf-seti-c)\n\th: \"\\u{E61E}\",\n\tcpp: \"\\u{E61E}\",\n\thpp: \"\\u{E61E}\",\n\tcs: \"\\u{E61E}\",\n\tsvg: \"\\u{E62A}\", // (nf-seti-svg)\n\tpng: \"\\u{E61D}\", // (nf-seti-image)\n\tjpg: \"\\u{E61D}\",\n\tjpeg: \"\\u{E61D}\",\n\tgif: \"\\u{E61D}\",\n\twebp: \"\\u{E61D}\",\n\tpdf: \"\\u{E67A}\", // (nf-seti-pdf)\n\tdockerfile: \"\\u{E7B0}\", // (nf-seti-docker)\n\tlock: \"\\u{E7B0}\",\n\tgitignore: \"\\u{E702}\", // (nf-seti-git)\n\tgitattributes: \"\\u{E702}\",\n\tvue: \"\\u{ED43}\", // (nf-vue)\n\tsvelte: \"\\u{E697}\",\n};\n\n/** Nerd Font file-type icon for a path, or \"\" when not applicable. */\nexport function fileIcon(path: string): string {\n\tif (path.endsWith(\"/\")) return FILE_ICON_FOLDER;\n\tconst name = path.split(\"/\").pop() ?? path;\n\tconst lower = name.toLowerCase();\n\tconst ext = lower.includes(\".\") ? lower.slice(lower.lastIndexOf(\".\") + 1) : lower;\n\treturn FILE_ICONS[ext] ?? FILE_ICONS[lower] ?? FILE_ICON_DEFAULT;\n}\n\n/** Lines produced by these native tools to signal truncation (already in the\n * output text, not separate metadata). Dropped before parsing. */\nconst NOTICE_LINE_PATTERN = /^\\[[^\\]]*\\]$/;\n\n/** A parsed grep match line. Context lines are not surfaced in the tree. */\nexport interface GrepMatch {\n\treadonly file: string;\n\treadonly line: number;\n\treadonly content: string;\n}\n\n/** Drop trailing tool notices (`[Showing last …]`, `[Truncated: …]`) and blanks. */\nfunction stripNotices(text: string): string[] {\n\treturn text\n\t\t.replace(/\\r/g, \"\")\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trimEnd())\n\t\t.filter((line) => line.length > 0 && !NOTICE_LINE_PATTERN.test(line.trim()));\n}\n\n/**\n * Parse native `ls` output into display entries. Directories keep their `/`\n * suffix; the `(empty directory)` placeholder and truncation notices are\n * removed. Output is already sorted alphabetically by the tool.\n */\nexport function parseLsOutput(rawText: string): string[] {\n\treturn stripNotices(rawText)\n\t\t.map((line) => line.trim())\n\t\t.filter((line) => line.length > 0 && line !== \"(empty directory)\");\n}\n\n/**\n * Parse `ls -l`/`ls -la` long-format output into display entries: the entry\n * name is the text after the time column; directory names get a trailing `/`.\n * The `total N` summary and `.`/`..` entries are dropped. Standard POSIX\n * columns: perms links owner group size month day time name. macOS `@`/`+`\n * permission suffixes are tolerated.\n */\nexport function parseLsLongOutput(rawText: string): string[] {\n\tconst entries: string[] = [];\n\tfor (const line of stripNotices(rawText)) {\n\t\tif (!/^[bcdlsp-][rwxtsST-]{9}/.test(line)) continue;\n\t\tconst parts = line.split(/\\s+/);\n\t\tconst name = parts.slice(8).join(\" \").trim();\n\t\tif (!name || name === \".\" || name === \"..\") continue;\n\t\tconst isDir = (parts[0] ?? \"\").startsWith(\"d\");\n\t\tentries.push(isDir ? `${name}/` : name);\n\t}\n\treturn entries;\n}\n\n/**\n * Parse native `find` output into display paths (one per line). Notices are\n * removed. The native tool returns paths relative to the search directory.\n */\nexport function parseFindOutput(rawText: string): string[] {\n\treturn stripNotices(rawText)\n\t\t.map((line) => line.trim())\n\t\t.filter((line) => line.length > 0);\n}\n\n// Match line: path/to/file.ts:42: matched content (Pi grep adds a space;\n// ripgrep/grep emit no space). Context lines (path-line- …) are dropped.\nconst GREP_MATCH_PATTERN = /^(.*):(\\d+):[ \\t]?(.*)$/;\n// Single-file ripgrep/grep output: `42: content` (no filename).\nconst GREP_BARE_PATTERN = /^(\\d+):[ \\t]?(.*)$/;\n\n/**\n * Parse native `grep` output into match records. Only real match lines\n * (`file:line: content`) are kept; context lines (`file-line- …`) are dropped\n * so the tree stays focused on hits. Trailing notices are removed.\n */\nexport function parseGrepOutput(rawText: string): GrepMatch[] {\n\tconst matches: GrepMatch[] = [];\n\tfor (const line of stripNotices(rawText)) {\n\t\tconst match = GREP_MATCH_PATTERN.exec(line);\n\t\tif (!match) continue;\n\t\tconst [, file, lineNo, content] = match;\n\t\tif (!file || lineNo === undefined || content === undefined) continue;\n\t\tconst parsed = Number(lineNo);\n\t\tif (!Number.isFinite(parsed) || parsed < 1) continue;\n\t\tmatches.push({ file, line: parsed, content });\n\t}\n\treturn matches;\n}\n\n/**\n * Parse single-file grep/ripgrep output — `line: content` without a filename —\n * attributing every match to the given file. Used by bash `grep pattern file`.\n */\nexport function parseGrepBareOutput(rawText: string, file: string): GrepMatch[] {\n\tconst matches: GrepMatch[] = [];\n\tfor (const line of stripNotices(rawText)) {\n\t\tconst match = GREP_BARE_PATTERN.exec(line);\n\t\tif (!match) continue;\n\t\tconst parsed = Number(match[1]);\n\t\tif (!Number.isFinite(parsed) || parsed < 1) continue;\n\t\tmatches.push({ file, line: parsed, content: match[2] ?? \"\" });\n\t}\n\treturn matches;\n}\n\n/** Group grep matches by file, preserving first-seen order. */\nexport function groupMatchesByFile(matches: readonly GrepMatch[]): { file: string; matches: GrepMatch[] }[] {\n\tconst order: string[] = [];\n\tconst buckets = new Map<string, GrepMatch[]>();\n\tfor (const match of matches) {\n\t\tlet bucket = buckets.get(match.file);\n\t\tif (!bucket) {\n\t\t\tbucket = [];\n\t\t\tbuckets.set(match.file, bucket);\n\t\t\torder.push(match.file);\n\t\t}\n\t\tbucket.push(match);\n\t}\n\treturn order.map((file) => ({ file, matches: buckets.get(file) ?? [] }));\n}\n\nexport interface OutputTreeOptions {\n\t/** Maximum entries shown before the \"… N more\" row. */\n\theadLimit?: number;\n\t/** Singular noun used in the collapse row (default \"file\"); pluralized automatically. */\n\tmoreUnit?: string;\n\t/** Optional ANSI-themed color for entry text (defaults to \"toolOutput\"). */\n\tentryColor?: string;\n\t/** Indent prefix applied to every row (defaults to TREE_INDENT). */\n\tindent?: string;\n\t/** Nerd Font mode: prefix each entry with its file-type icon. */\n\twithIcons?: boolean;\n}\n\n/**\n * Render a flat output tree: `<header>` then `├─/└─` rows for the first entries\n * and a trailing `└─ … N more <unit>` row when truncated. Used by lone ls/find\n * (and bash ls/find).\n */\nexport function renderOutputTree(\n\ttheme: BoxTheme,\n\theader: string,\n\tentries: readonly string[],\n\twidth: number,\n\toptions: OutputTreeOptions = {},\n): string[] {\n\tconst headLimit = options.headLimit ?? OUTPUT_TREE_HEAD_LIMIT;\n\tconst moreUnit = options.moreUnit ?? \"file\";\n\tconst entryColor = options.entryColor ?? \"toolOutput\";\n\tconst indent = options.indent ?? TREE_INDENT;\n\tconst safeWidth = Math.max(1, width);\n\tconst label = (entry: string) => (options.withIcons && entry ? `${fileIcon(entry)} ${entry}` : entry);\n\n\tconst out: string[] = [safeTruncateToWidth(header, safeWidth, \"…\")];\n\tif (entries.length === 0) return out;\n\n\tconst visible = entries.slice(0, headLimit);\n\tconst more = entries.length - visible.length;\n\tconst lastIndex = visible.length - 1;\n\tfor (let i = 0; i < visible.length; i++) {\n\t\tconst branch = i < lastIndex || more > 0 ? \"├─\" : \"└─\";\n\t\tconst line = `${indent}${dimLine(branch)} ${theme.fg(entryColor, label(visible[i] ?? \"\"))}`;\n\t\tout.push(safeTruncateToWidth(line, safeWidth, \"…\"));\n\t}\n\tif (more > 0) {\n\t\tconst line = `${indent}${dimLine(\"└─\")} ${theme.fg(\"dim\", `… ${more} more ${pluralForm(moreUnit, more)}`)}`;\n\t\tout.push(safeTruncateToWidth(line, safeWidth, \"…\"));\n\t}\n\treturn out;\n}\n\nexport interface GrepTreeOptions {\n\t/** Maximum matches shown (across all files) before the \"… N more\" row. */\n\theadLimit?: number;\n\t/** Indent prefix applied to top-level rows. */\n\tindent?: string;\n\t/** Nerd Font mode: prefix file nodes with their file-type icon. */\n\twithIcons?: boolean;\n}\n\nfunction formatMatchRow(theme: BoxTheme, match: GrepMatch): string {\n\t// Match rows render in the output text color (not primary) so they read like\n\t// the matched code; only the file nodes carry the primary color.\n\tconst label = theme.fg(\"toolOutput\", `*${match.line}`);\n\tconst sep = dimLine(\"│\");\n\treturn `${label}${sep} ${theme.fg(\"toolOutput\", match.content)}`;\n}\n\n/**\n * Render a grep matches tree: `<header>` then matches grouped by file. With a\n * single file the matches are direct children; with several files each file is\n * a `├─ file` node and its matches hang off an indented trunk beneath. A\n * trailing `└─ … N more matches` row appears when the match budget is exceeded.\n */\nexport function renderGrepTree(\n\ttheme: BoxTheme,\n\theader: string,\n\tmatches: readonly GrepMatch[],\n\twidth: number,\n\toptions: GrepTreeOptions = {},\n): string[] {\n\tconst headLimit = options.headLimit ?? OUTPUT_TREE_HEAD_LIMIT;\n\tconst indent = options.indent ?? TREE_INDENT;\n\tconst safeWidth = Math.max(1, width);\n\n\tconst out: string[] = [safeTruncateToWidth(header, safeWidth, \"…\")];\n\tif (matches.length === 0) return out;\n\n\tconst groups = groupMatchesByFile(matches);\n\tconst singleFile = groups.length === 1;\n\n\t// First decide which matches fit the budget so branch glyphs (├─ vs └─) and\n\t// the trailing \"… N more\" row stay consistent.\n\tconst budget = matches.slice(0, headLimit);\n\tconst remaining = matches.length - budget.length;\n\tconst truncated = remaining > 0;\n\tconst totalVisible = budget.length;\n\n\tconst push = (line: string) => out.push(safeTruncateToWidth(line, safeWidth, \"…\"));\n\n\tif (singleFile) {\n\t\tbudget.forEach((match, index) => {\n\t\t\tconst isLast = index === totalVisible - 1 && !truncated;\n\t\t\tpush(`${indent}${dimLine(isLast ? \"└─\" : \"├─\")} ${formatMatchRow(theme, match)}`);\n\t\t});\n\t} else {\n\t\t// Walk the budget, tracking position within each file group so the file\n\t\t// node and its match subtree render as one connected unit.\n\t\tlet shown = 0;\n\t\tfor (let gi = 0; gi < groups.length && shown < totalVisible; gi++) {\n\t\t\tconst group = groups[gi];\n\t\t\tif (!group) continue;\n\t\t\tconst isLastGroup = gi === groups.length - 1;\n\t\t\tconst trunk = isLastGroup ? \" \" : dimLine(\"│\");\n\n\t\t\tconst visibleHere: GrepMatch[] = [];\n\t\t\tfor (const match of group.matches) {\n\t\t\t\tif (shown >= totalVisible) break;\n\t\t\t\tvisibleHere.push(match);\n\t\t\t\tshown++;\n\t\t\t}\n\t\t\tif (visibleHere.length === 0) continue;\n\n\t\t\tconst groupIsLastRendered = shown >= totalVisible && !truncated;\n\t\t\tconst fileLabel = options.withIcons ? `${fileIcon(group.file)} ${group.file}` : group.file;\n\t\t\t// File nodes use the primary (accent) color, matching read/ls/find paths.\n\t\t\tpush(`${indent}${dimLine(groupIsLastRendered ? \"└─\" : \"├─\")} ${theme.fg(\"accent\", fileLabel)}`);\n\n\t\t\tvisibleHere.forEach((match, index) => {\n\t\t\t\tconst isLastInGroup = index === visibleHere.length - 1;\n\t\t\t\tconst isLastOverall = groupIsLastRendered && isLastInGroup;\n\t\t\t\tpush(\n\t\t\t\t\t`${indent}${trunk}${TREE_CHILD_INDENT}${dimLine(isLastOverall ? \"└─\" : \"├─\")} ${formatMatchRow(theme, match)}`,\n\t\t\t\t);\n\t\t\t});\n\t\t}\n\t}\n\n\tif (truncated) {\n\t\tpush(`${indent}${dimLine(\"└─\")} ${theme.fg(\"dim\", `… ${remaining} more ${pluralForm(\"match\", remaining)}`)}`);\n\t}\n\treturn out;\n}\n\n/** Return the pluralized form of a noun for the given count. */\nexport function pluralForm(noun: string, count: number): string {\n\tif (count === 1) return noun;\n\treturn /(s|x|z|ch|sh)$/i.test(noun) ? `${noun}es` : `${noun}s`;\n}\n\n/** Pluralize a count noun: \"1 file\" / \"3 files\", \"1 match\" / \"3 matches\". */\nexport function pluralize(count: number, noun: string): string {\n\treturn `${count} ${pluralForm(noun, count)}`;\n}\n","// Per-session render configuration for boxed tool presentation.\n//\n// Set once per session by the compatibility coordinator; read inside renderers.\n// Kept out of the render path (no filesystem/config reads during render).\n\nexport interface ToolsRenderConfig {\n\tmaxCollapsedLines: number;\n\tmaxExpandedLines: number;\n\tdimOutput: boolean;\n\tshowElapsed: boolean;\n\t/** Open-tree glyph for the done batch header (nerd `\\u{F111}` / unicode `●`). */\n\tbatchOpenGlyph: string;\n\t/** Nerd Font mode is active: file-type icons render in output trees. */\n\tnerdFonts: boolean;\n}\n\nlet sessionToolsConfig: ToolsRenderConfig = {\n\tmaxCollapsedLines: 10,\n\tmaxExpandedLines: 50,\n\tdimOutput: false,\n\tshowElapsed: true,\n\tbatchOpenGlyph: \"●\",\n\tnerdFonts: false,\n};\n\nexport function setToolsRenderConfig(config: Partial<ToolsRenderConfig>): void {\n\tsessionToolsConfig = { ...sessionToolsConfig, ...config };\n}\n\nexport function getToolsRenderConfig(): ToolsRenderConfig {\n\treturn sessionToolsConfig;\n}\n\n// Wall-clock elapsed tracking through the renderer context state (no tool\n// re-registration, so result.details has no execution timing).\n//\n// Elapsed is computed live from the recorded start on every read, so a running\n// tool keeps growing its displayed time. The value only freezes once the\n// execution end is recorded (terminal result), which keeps the completed footer\n// stable across later re-renders (expand toggles, terminal resizes).\n\nconst STARTED_AT_KEY = \"__piStyleStartedAt\";\nconst ENDED_AT_KEY = \"__piStyleEndedAt\";\nconst RESULT_SEEN_KEY = \"__piStyleResultSeen\";\nconst TICKER_KEY = \"__piStyleElapsedTicker\";\n\nexport function recordExecutionStarted(state: Record<string, unknown> | undefined, executionStarted: boolean): void {\n\tif (!executionStarted || !state || typeof state !== \"object\") return;\n\tif (typeof state[STARTED_AT_KEY] !== \"number\") state[STARTED_AT_KEY] = performance.now();\n}\n\n/** Freeze the elapsed at the first terminal render (idempotent). */\nexport function recordExecutionEnded(state: Record<string, unknown> | undefined): void {\n\tif (!state || typeof state !== \"object\") return;\n\tif (typeof state[ENDED_AT_KEY] !== \"number\") state[ENDED_AT_KEY] = performance.now();\n}\n\nexport function getStateElapsedMs(state: Record<string, unknown> | undefined): number | undefined {\n\tif (!state || typeof state !== \"object\") return undefined;\n\tconst started = state[STARTED_AT_KEY];\n\tif (typeof started !== \"number\") return undefined;\n\tconst ended = state[ENDED_AT_KEY];\n\tif (typeof ended === \"number\") return Math.max(0, ended - started);\n\treturn Math.max(0, performance.now() - started);\n}\n\n/** Whether a result renderer already produced a continuation for this call. */\nexport function isResultSeen(state: Record<string, unknown> | undefined): boolean {\n\treturn Boolean(state && typeof state === \"object\" && state[RESULT_SEEN_KEY] === true);\n}\n\n/** Record that a result renderer ran for this call (streaming or final). */\nexport function markResultSeen(state: Record<string, unknown> | undefined): void {\n\tif (!state || typeof state !== \"object\") return;\n\tstate[RESULT_SEEN_KEY] = true;\n}\n\ntype TickerHandle = ReturnType<typeof setInterval>;\n\n/** States that currently own a 1s elapsed-render interval, for session cleanup. */\nconst tickerStates = new Set<Record<string, unknown>>();\n\n/**\n * While a tool is running, re-render once per second so live elapsed labels\n * tick without any output events. Idempotent per state.\n */\nexport function startElapsedTicker(state: Record<string, unknown> | undefined, invalidate: () => void): void {\n\tif (!state || typeof state !== \"object\") return;\n\tif (state[TICKER_KEY] !== undefined) return;\n\tstate[TICKER_KEY] = setInterval(() => invalidate(), 1000) as unknown as TickerHandle;\n\ttickerStates.add(state);\n}\n\n/** Stop a running tool's elapsed ticker (terminal result, error, session end). */\nexport function stopElapsedTicker(state: Record<string, unknown> | undefined): void {\n\tif (!state || typeof state !== \"object\") return;\n\tconst handle = state[TICKER_KEY] as TickerHandle | undefined;\n\tif (handle !== undefined) clearInterval(handle);\n\tdelete state[TICKER_KEY];\n\ttickerStates.delete(state);\n}\n\n/** Stop every elapsed ticker (session start/shutdown). */\nexport function stopAllElapsedTickers(): void {\n\tfor (const state of tickerStates) {\n\t\tconst handle = state[TICKER_KEY] as TickerHandle | undefined;\n\t\tif (handle !== undefined) clearInterval(handle);\n\t\tdelete state[TICKER_KEY];\n\t}\n\ttickerStates.clear();\n}\n","// Consecutive quiet-tool (read/ls/find) call batching.\n//\n// Groups back-to-back calls of the same quiet tool inside one assistant turn\n// into a single collapsible, **boxless** tree panel instead of one boxed panel\n// per call. The first call of a batch becomes its leader: the leader's call\n// component renders the whole panel (header + tree), reading the live batch\n// state on every render pass. Subsequent members render zero lines, so they\n// consume no vertical space.\n//\n// Design notes:\n// - No caching in the batch panel: it reads the module-level registry on every\n// render, so member completions (which trigger ui.requestRender via Pi's\n// tool_execution_end handler) are picked up without cross-component\n// invalidation plumbing.\n// - Batch boundaries: a new batch starts when the active batch is closed. The\n// active batch closes when a non-batchable tool call is dispatched\n// (boxed/index.ts), when a new message starts (pi/index.ts), and on session\n// reset (session-coordinator.ts). A lone `read` call renders as a single\n// inline line (`➔ Read <path>`); lone ls/find calls render a flat output\n// tree (a batch of one).\n// - No surrounding box: indentation and tree glyphs (├─/└─) carry the\n// hierarchy; the header line of a batched panel is the summary\n// (` Read (N) · 0.08s`).\n// - Errors stay visible: failed members are always rendered inline (even in the\n// collapsed state), with their error text indented beneath the path.\n// - read members render a single path row (a lone read collapses to one inline\n// line). ls/find members render their parsed output as a file subtree (flat\n// for a lone call, nested per member when batched) — see\n// renderOutputBatchPanel. Pending/failed members without output fall back to\n// the path row.\n\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport { stripAnsi } from \"../../../shared/ansi.js\";\nimport { type BoxTheme, dimLine, formatToolTitlePrefix } from \"../../../shared/box.js\";\nimport { safeTruncateToWidth } from \"../../../shared/render-budget.js\";\nimport {\n\tfileIcon,\n\tOUTPUT_TREE_HEAD_LIMIT,\n\tpluralForm,\n\trenderOutputTree,\n\tSEARCH_ICON,\n\tTREE_CHILD_INDENT,\n\tTREE_INDENT,\n} from \"./output-tree.js\";\nimport { getToolsRenderConfig } from \"./session-config.js\";\nimport type { BoxedToolContext } from \"./shared.js\";\n\n/** Quiet tools whose calls group into a single batch panel. */\nexport const BATCHABLE_TOOL_NAMES: ReadonlySet<string> = new Set([\"read\", \"ls\", \"find\"]);\n\nexport function isBatchableTool(toolName: unknown): boolean {\n\treturn typeof toolName === \"string\" && BATCHABLE_TOOL_NAMES.has(toolName);\n}\n\nexport interface BatchToolMeta {\n\treadonly toolName: string;\n\t/** Human label shown in the batch header (e.g. \"Read\", \"List\", \"Find\"). */\n\treadonly label: string;\n\t/** Header label for output-tree panels: \"Find\" for find, \"List\" for ls. */\n\treadonly headerLabel?: string;\n}\n\nexport type BatchMemberStatus = \"pending\" | \"running\" | \"done\";\n\nexport interface BatchMember {\n\treadonly toolCallId: string;\n\tdetail: string;\n\tstatus: BatchMemberStatus;\n\tisError: boolean;\n\terrorText?: string;\n\t/** find glob pattern (header detail for output panels). */\n\tpattern?: string;\n\t/** Display path (header detail for output panels). */\n\tpathLabel?: string;\n\t/** Parsed output entries once the result arrives (ls/find). `undefined` until\n\t * the result is registered; an empty array means a successful zero-entry\n\t * result (e.g. an empty directory). */\n\toutputEntries?: string[];\n}\n\nexport interface BatchState {\n\treadonly meta: BatchToolMeta;\n\treadonly leaderId: string;\n\treadonly startedAt: number;\n\tcompletedAt?: number;\n\tclosed: boolean;\n\treadonly members: BatchMember[];\n}\n\n/** Tree head limit: only the first few members are listed, the rest collapse. */\nconst BATCH_TREE_HEAD_LIMIT = 5;\n/** Per-member file subtree head limit in a batched output panel. */\nconst BATCH_MEMBER_FILE_HEAD_LIMIT = 4;\nconst BATCH_ERROR_LINES = 2;\n/** Indent for tree lines below the header. */\nconst BATCH_TREE_INDENT = TREE_INDENT;\n\n/** Component rendered for non-leader batch members (zero height). */\nexport const EMPTY_BATCH_COMPONENT: Component = Object.freeze({\n\tinvalidate() {},\n\trender() {\n\t\treturn [];\n\t},\n});\n\nlet activeBatch: BatchState | undefined;\nconst batchByCallId = new Map<string, BatchState>();\n\n/** Close the current batch: no new members join; existing panels keep rendering. */\nexport function closeActiveBatch(): void {\n\tif (!activeBatch) return;\n\tactiveBatch.closed = true;\n\tactiveBatch = undefined;\n}\n\n/** Reset all batch state (session start/shutdown). */\nexport function resetBatchRegistry(): void {\n\tactiveBatch = undefined;\n\tbatchByCallId.clear();\n}\n\nfunction createBatch(\n\tmeta: BatchToolMeta,\n\tleaderId: string,\n\tdetail: string,\n\topts: { pattern?: string; pathLabel?: string } = {},\n): BatchState {\n\tconst batch: BatchState = {\n\t\tmeta,\n\t\tleaderId,\n\t\tstartedAt: performance.now(),\n\t\tclosed: false,\n\t\tmembers: [\n\t\t\t{\n\t\t\t\ttoolCallId: leaderId,\n\t\t\t\tdetail,\n\t\t\t\tstatus: \"pending\",\n\t\t\t\tisError: false,\n\t\t\t\t...(opts.pattern ? { pattern: opts.pattern } : {}),\n\t\t\t\t...(opts.pathLabel ? { pathLabel: opts.pathLabel } : {}),\n\t\t\t},\n\t\t],\n\t};\n\tactiveBatch = batch;\n\tbatchByCallId.set(leaderId, batch);\n\treturn batch;\n}\n\n/**\n * Register a call renderer invocation. Idempotent per toolCallId: re-fires\n * (updateDisplay on the same component) reuse the call's existing batch, even\n * after the batch was closed.\n */\nexport function registerBatchCall(\n\tmeta: BatchToolMeta,\n\tdetail: string,\n\tcontext: BoxedToolContext,\n\topts: { pattern?: string; pathLabel?: string } = {},\n): { batch: BatchState; isLeader: boolean } {\n\tconst existing = batchByCallId.get(context.toolCallId);\n\tif (existing) {\n\t\tconst member = existing.members.find((entry) => entry.toolCallId === context.toolCallId);\n\t\tif (member) {\n\t\t\tmember.detail = detail;\n\t\t\tif (opts.pattern !== undefined) member.pattern = opts.pattern;\n\t\t\tif (opts.pathLabel !== undefined) member.pathLabel = opts.pathLabel;\n\t\t}\n\t\treturn { batch: existing, isLeader: existing.leaderId === context.toolCallId };\n\t}\n\tconst current = activeBatch;\n\tif (!current || current.closed || current.meta.toolName !== meta.toolName) {\n\t\tcloseActiveBatch();\n\t\treturn { batch: createBatch(meta, context.toolCallId, detail, opts), isLeader: true };\n\t}\n\tconst member: BatchMember = {\n\t\ttoolCallId: context.toolCallId,\n\t\tdetail,\n\t\tstatus: \"pending\",\n\t\tisError: false,\n\t\t...(opts.pattern ? { pattern: opts.pattern } : {}),\n\t\t...(opts.pathLabel ? { pathLabel: opts.pathLabel } : {}),\n\t};\n\tcurrent.members.push(member);\n\tbatchByCallId.set(context.toolCallId, current);\n\treturn { batch: current, isLeader: false };\n}\n\nexport interface BatchResultData {\n\treadonly isPartial: boolean;\n\treadonly isError: boolean;\n\treadonly errorText: string | undefined;\n\t/** Parsed output entries (ls/find) stored on the member for tree rendering. */\n\treadonly entries?: string[];\n}\n\n/**\n * Register a result renderer invocation: updates the member's status/metadata\n * and records batch completion once every member has settled. The member's\n * display detail stays as registered by the call renderer (the result context's\n * args may be normalized differently).\n */\nexport function registerBatchResult(\n\tmeta: BatchToolMeta,\n\tdata: BatchResultData,\n\tcontext: BoxedToolContext,\n): { batch: BatchState | undefined; isLeader: boolean } {\n\tconst batch = batchByCallId.get(context.toolCallId);\n\tif (!batch || batch.meta.toolName !== meta.toolName) return { batch: undefined, isLeader: false };\n\tconst member = batch.members.find((entry) => entry.toolCallId === context.toolCallId);\n\tif (member) {\n\t\tmember.status = data.isPartial ? \"running\" : \"done\";\n\t\tmember.isError = !data.isPartial && data.isError;\n\t\tif (member.isError && data.errorText !== undefined) member.errorText = data.errorText;\n\t\telse delete member.errorText;\n\t\tif (data.entries !== undefined) member.outputEntries = data.entries;\n\t}\n\tif (batch.completedAt === undefined && batch.members.every((entry) => entry.status === \"done\")) {\n\t\tbatch.completedAt = performance.now();\n\t}\n\treturn { batch, isLeader: batch.leaderId === context.toolCallId };\n}\n\ninterface BatchStatus {\n\treadonly total: number;\n\treadonly done: number;\n\treadonly failed: number;\n\treadonly allDone: boolean;\n\treadonly elapsedMs: number | undefined;\n}\n\nfunction batchStatus(batch: BatchState): BatchStatus {\n\tlet done = 0;\n\tlet failed = 0;\n\tfor (const member of batch.members) {\n\t\tif (member.status !== \"done\") continue;\n\t\tdone++;\n\t\tif (member.isError) failed++;\n\t}\n\tconst total = batch.members.length;\n\tconst allDone = done === total;\n\treturn {\n\t\ttotal,\n\t\tdone,\n\t\tfailed,\n\t\tallDone,\n\t\telapsedMs: allDone && batch.completedAt !== undefined ? batch.completedAt - batch.startedAt : undefined,\n\t};\n}\n\nfunction formatElapsed(theme: BoxTheme, elapsedMs: number): string {\n\treturn theme.fg(\"dim\", ` · ${(elapsedMs / 1000).toFixed(2)}s`);\n}\n\nfunction bold(theme: BoxTheme, text: string): string {\n\treturn typeof theme?.bold === \"function\" ? theme.bold(text) : text;\n}\n\nfunction isOutputTool(meta: BatchToolMeta): boolean {\n\treturn meta.toolName === \"ls\" || meta.toolName === \"find\";\n}\n\n/** Header line: state glyph + batch label(count) + progress/elapsed (no box). */\nfunction formatBatchHeader(theme: BoxTheme, batch: BatchState, status: BatchStatus): string {\n\tconst label = `${batch.meta.headerLabel ?? batch.meta.label} (${status.total})`;\n\tif (status.failed > 0) return theme.fg(\"error\", bold(theme, `✗ ${label} · ${status.failed} failed`));\n\tif (status.allDone) {\n\t\tconst glyph = getToolsRenderConfig().batchOpenGlyph;\n\t\tconst elapsed = status.elapsedMs === undefined ? \"\" : formatElapsed(theme, status.elapsedMs);\n\t\treturn `${theme.fg(\"text\", bold(theme, `${glyph} ${label}`))}${elapsed}`;\n\t}\n\tif (status.done > 0)\n\t\treturn `${theme.fg(\"text\", bold(theme, `◌ ${label}`))}${theme.fg(\"dim\", ` · ${status.done}/${status.total}`)}`;\n\treturn bold(theme, formatToolTitlePrefix(theme, label));\n}\n\nfunction memberGlyph(theme: BoxTheme, member: BatchMember, show: boolean): string {\n\tif (!show) return \"\";\n\tif (member.isError) return theme.fg(\"error\", \"✗\");\n\tif (member.status === \"done\") return theme.fg(\"success\", \"✓\");\n\treturn theme.fg(\"text\", \"◌\");\n}\n\nfunction renderErrorLines(theme: BoxTheme, errorText: string, width: number): string[] {\n\tconst raw = stripAnsi(errorText)\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trim())\n\t\t.filter((line) => line.length > 0);\n\tif (raw.length === 0) return [];\n\tconst prefix = `${dimLine(\" │ \")}`;\n\tconst out = raw\n\t\t.slice(0, BATCH_ERROR_LINES)\n\t\t.map((line) => safeTruncateToWidth(`${prefix}${theme.fg(\"error\", line)}`, Math.max(1, width), \"…\"));\n\tif (raw.length > BATCH_ERROR_LINES)\n\t\tout.push(safeTruncateToWidth(`${prefix}${theme.fg(\"error\", \"…\")}`, Math.max(1, width), \"…\"));\n\treturn out;\n}\n\nfunction renderBatchTree(theme: BoxTheme, batch: BatchState, status: BatchStatus, width: number): string[] {\n\tconst showGlyphs = !status.allDone || status.failed > 0;\n\tconst visible = batch.members.slice(0, BATCH_TREE_HEAD_LIMIT);\n\tconst more = batch.members.length - visible.length;\n\tconst lastIndex = visible.length - 1;\n\tconst out: string[] = [];\n\tfor (let i = 0; i < visible.length; i++) {\n\t\tconst member = visible[i];\n\t\tif (!member) continue;\n\t\tconst branch = i < lastIndex || more > 0 ? \"├─\" : \"└─\";\n\t\tconst glyph = memberGlyph(theme, member, showGlyphs);\n\t\t// Primary color for files read successfully, error red for failures.\n\t\tconst pathColor = member.isError ? \"error\" : member.status === \"done\" ? \"accent\" : \"text\";\n\t\tconst line = `${BATCH_TREE_INDENT}${dimLine(branch)}${glyph ? ` ${glyph}` : \"\"} ${theme.fg(pathColor, member.detail)}`;\n\t\tout.push(safeTruncateToWidth(line, Math.max(1, width), \"…\"));\n\t\tif (member.isError && member.errorText) out.push(...renderErrorLines(theme, member.errorText, width));\n\t}\n\tif (more > 0) {\n\t\tout.push(\n\t\t\tsafeTruncateToWidth(\n\t\t\t\t`${BATCH_TREE_INDENT}${dimLine(\"└─\")} ${theme.fg(\"dim\", `${more} more`)}`,\n\t\t\t\tMath.max(1, width),\n\t\t\t\t\"…\",\n\t\t\t),\n\t\t);\n\t}\n\treturn out;\n}\n\n/** Header for a lone (batch-of-one) ls/find output panel: `Find: <pattern> <N> files · in <path>`. */\nfunction formatLoneOutputHeader(theme: BoxTheme, meta: BatchToolMeta, member: BatchMember): string {\n\tconst label = meta.headerLabel ?? meta.label;\n\tconst count = member.outputEntries?.length ?? 0;\n\tconst filesPart = theme.fg(\"accent\", `${count} ${count === 1 ? \"file\" : \"files\"}`);\n\tconst patternPart = meta.toolName === \"find\" && member.pattern ? `${theme.fg(\"text\", member.pattern)} ` : \"\";\n\tconst pathPart = member.pathLabel ? theme.fg(\"dim\", ` · in ${member.pathLabel}`) : \"\";\n\t// ls/find headers carry the magnifying-glass icon in Nerd Font mode,\n\t// matching find/grep.\n\tconst icon = getToolsRenderConfig().nerdFonts ? `${SEARCH_ICON} ` : \"\";\n\treturn `${icon}${bold(theme, `${label}:`)} ${patternPart}${filesPart}${pathPart}`;\n}\n\n/** Nested file subtree for one member inside a batched (2+) output panel. */\nfunction renderMemberSubtree(theme: BoxTheme, member: BatchMember, isLastMember: boolean, width: number): string[] {\n\tconst safeWidth = Math.max(1, width);\n\tconst trunk = isLastMember ? \" \" : dimLine(\"│\");\n\tconst out: string[] = [];\n\n\t// Member header row: path + file count (or status glyph when not done).\n\tconst entries = member.outputEntries ?? [];\n\tif (member.isError) {\n\t\tconst line = `${BATCH_TREE_INDENT}${dimLine(isLastMember ? \"└─\" : \"├─\")} ${theme.fg(\"error\", \"✗\")} ${theme.fg(\"error\", member.pathLabel ?? member.detail)}`;\n\t\tout.push(safeTruncateToWidth(line, safeWidth, \"…\"));\n\t\tif (member.errorText) out.push(...renderErrorLines(theme, member.errorText, width));\n\t\treturn out;\n\t}\n\tif (member.status !== \"done\" || member.outputEntries === undefined) {\n\t\tconst glyph = member.status === \"done\" ? theme.fg(\"success\", \"✓\") : theme.fg(\"text\", \"◌\");\n\t\tconst line = `${BATCH_TREE_INDENT}${dimLine(isLastMember ? \"└─\" : \"├─\")} ${glyph} ${theme.fg(\"text\", member.pathLabel ?? member.detail)}`;\n\t\tout.push(safeTruncateToWidth(line, safeWidth, \"…\"));\n\t\treturn out;\n\t}\n\n\tconst countLabel = theme.fg(\"dim\", ` · ${entries.length} ${pluralForm(\"file\", entries.length)}`);\n\tconst headerLine = `${BATCH_TREE_INDENT}${dimLine(isLastMember ? \"└─\" : \"├─\")} ${theme.fg(\"accent\", member.pathLabel ?? member.detail)}${countLabel}`;\n\tout.push(safeTruncateToWidth(headerLine, safeWidth, \"…\"));\n\n\tconst visible = entries.slice(0, BATCH_MEMBER_FILE_HEAD_LIMIT);\n\tconst more = entries.length - visible.length;\n\tconst lastIndex = visible.length - 1;\n\tconst icons = getToolsRenderConfig().nerdFonts;\n\tfor (let i = 0; i < visible.length; i++) {\n\t\tconst entry = visible[i] ?? \"\";\n\t\tconst label = icons && entry ? `${fileIcon(entry)} ${entry}` : entry;\n\t\tconst branch = i < lastIndex || more > 0 ? \"├─\" : \"└─\";\n\t\tconst line = `${BATCH_TREE_INDENT}${trunk}${TREE_CHILD_INDENT}${dimLine(branch)} ${theme.fg(\"toolOutput\", label)}`;\n\t\tout.push(safeTruncateToWidth(line, safeWidth, \"…\"));\n\t}\n\tif (more > 0) {\n\t\tconst line = `${BATCH_TREE_INDENT}${trunk}${TREE_CHILD_INDENT}${dimLine(\"└─\")} ${theme.fg(\"dim\", `… ${more} more ${pluralForm(\"file\", more)}`)}`;\n\t\tout.push(safeTruncateToWidth(line, safeWidth, \"…\"));\n\t}\n\treturn out;\n}\n\n/** ls/find output panel: lone call renders a flat tree; a batch renders nested subtrees. */\nfunction renderOutputBatchPanel(theme: BoxTheme, batch: BatchState, status: BatchStatus, width: number): string[] {\n\tconst safeWidth = Math.max(1, width);\n\n\t// Lone successful call with output: flat tree under a `Find:/List:` header.\n\tif (batch.members.length === 1) {\n\t\tconst member = batch.members[0];\n\t\tif (member && member.outputEntries !== undefined && !member.isError) {\n\t\t\tconst header = safeTruncateToWidth(formatLoneOutputHeader(theme, batch.meta, member), safeWidth, \"…\");\n\t\t\treturn renderOutputTree(theme, header, member.outputEntries, safeWidth, {\n\t\t\t\theadLimit: OUTPUT_TREE_HEAD_LIMIT,\n\t\t\t\tmoreUnit: \"file\",\n\t\t\t\tentryColor: \"toolOutput\",\n\t\t\t\tindent: BATCH_TREE_INDENT,\n\t\t\t\twithIcons: getToolsRenderConfig().nerdFonts,\n\t\t\t});\n\t\t}\n\t\t// Pending/error/empty-without-entries: fall through to the path-only panel.\n\t}\n\n\t// Batched (2+) or a not-yet-ready lone call: per-member rows/subtrees.\n\tconst header = safeTruncateToWidth(formatBatchHeader(theme, batch, status), safeWidth, \"…\");\n\tconst out: string[] = [header];\n\tconst visible = batch.members.slice(0, BATCH_TREE_HEAD_LIMIT);\n\tconst more = batch.members.length - visible.length;\n\tvisible.forEach((member, index) => {\n\t\tconst isLast = index === visible.length - 1 && more <= 0;\n\t\tout.push(...renderMemberSubtree(theme, member, isLast, safeWidth));\n\t});\n\tif (more > 0) {\n\t\tout.push(\n\t\t\tsafeTruncateToWidth(`${BATCH_TREE_INDENT}${dimLine(\"└─\")} ${theme.fg(\"dim\", `${more} more`)}`, safeWidth, \"…\"),\n\t\t);\n\t}\n\treturn out;\n}\n\n/** Lone `read` call: single inline line `➔ Read <path>` — no count, no tree. */\nfunction isLoneRead(batch: BatchState): boolean {\n\treturn batch.meta.toolName === \"read\" && batch.members.length === 1;\n}\n\n/** Lone read renders `➔ Read <path>` on one line; errors keep their error text. */\nfunction renderLoneReadPanel(theme: BoxTheme, batch: BatchState, status: BatchStatus, width: number): string[] {\n\tconst member = batch.members[0];\n\tif (!member) return [];\n\tconst prefix = bold(theme, formatToolTitlePrefix(theme, batch.meta.label));\n\tconst glyph = memberGlyph(theme, member, !status.allDone || status.failed > 0);\n\tconst pathColor = member.isError ? \"error\" : member.status === \"done\" ? \"accent\" : \"text\";\n\tconst out = [\n\t\tsafeTruncateToWidth(\n\t\t\t`${prefix}${glyph ? ` ${glyph}` : \"\"} ${theme.fg(pathColor, member.detail)}`,\n\t\t\tMath.max(1, width),\n\t\t\t\"…\",\n\t\t),\n\t];\n\tif (member.isError && member.errorText) out.push(...renderErrorLines(theme, member.errorText, width));\n\treturn out;\n}\n\nfunction renderBatchPanelLines(theme: BoxTheme, batch: BatchState, status: BatchStatus, width: number): string[] {\n\t// Lone read collapses to a single inline line; batched reads and lone\n\t// ls/find calls keep their tree panels.\n\tif (isLoneRead(batch)) return renderLoneReadPanel(theme, batch, status, width);\n\tif (isOutputTool(batch.meta) && batch.members.some((member) => member.outputEntries !== undefined)) {\n\t\treturn renderOutputBatchPanel(theme, batch, status, width);\n\t}\n\tconst header = safeTruncateToWidth(formatBatchHeader(theme, batch, status), Math.max(1, width), \"…\");\n\tconst lines = [header];\n\tlines.push(...renderBatchTree(theme, batch, status, width));\n\treturn lines;\n}\n\n/**\n * Leader call component: renders the live batch panel (header + tree) reading\n * the registry on every render pass. Members render EMPTY_BATCH_COMPONENT.\n */\nexport function renderBatchAwareCall(theme: BoxTheme, batch: BatchState): Component {\n\treturn {\n\t\tinvalidate() {},\n\t\trender(width: number): string[] {\n\t\t\treturn renderBatchPanelLines(theme, batch, batchStatus(batch), width);\n\t\t},\n\t};\n}\n\n/**\n * Empty result component for the batch leader. The panel lives in the call\n * component; the result adds nothing. Deliberately NOT the shared member\n * singleton, so the decoration's hideBatchMember (identity-compared to\n * EMPTY_BATCH_COMPONENT) never hides the leader.\n */\nexport function emptyBatchResult(): Component {\n\treturn {\n\t\tinvalidate() {},\n\t\trender() {\n\t\t\treturn [];\n\t\t},\n\t};\n}\n","export type ConfigDiagnosticLevel = \"warning\" | \"error\";\nexport interface ConfigDiagnostic {\n\treadonly code: string;\n\treadonly level: ConfigDiagnosticLevel;\n\treadonly path: string;\n\treadonly message: string;\n}\n\nexport function boundedDiagnostics(items: readonly ConfigDiagnostic[], limit = 32): readonly ConfigDiagnostic[] {\n\tconst seen = new Set<string>();\n\tconst result: ConfigDiagnostic[] = [];\n\tfor (const item of items) {\n\t\tconst key = `${item.level}:${item.code}:${item.path}:${item.message}`;\n\t\tif (seen.has(key)) continue;\n\t\tseen.add(key);\n\t\tresult.push(Object.freeze(item));\n\t\tif (result.length >= limit) break;\n\t}\n\treturn Object.freeze(result);\n}\n","import type { PiStyleConfig, PresetName } from \"./config-types.js\";\n\n/** Code-defined coordinated defaults. Explicit fields are merged after these values. */\nexport const CONFIG_PRESETS: Readonly<Record<PresetName, Readonly<PiStyleConfig>>> = Object.freeze({\n\tdefault: Object.freeze({\n\t\tstartup: { mode: \"compact\" },\n\t}),\n\tminimal: Object.freeze({\n\t\tstatusLine: { layout: { left: [\"path\", \"git\"], right: [\"context_pct\"], secondary: [] } },\n\t\teditor: { style: \"native\", frame: \"native\", showMetadata: false },\n\t\tstartup: { mode: \"off\" },\n\t\tmessages: { enabled: false },\n\t\ttools: { enabled: false },\n\t\ttheme: { terminalBackgroundSync: \"off\" },\n\t}),\n\tcompact: Object.freeze({\n\t\tstatusLine: {\n\t\t\tlayout: { left: [\"model\", \"thinking\", \"git\"], right: [\"context_pct\"], secondary: [\"extension_statuses\"] },\n\t\t},\n\t\teditor: { style: \"compact\", frame: \"auto\", showMetadata: false },\n\t\tstartup: { mode: \"compact\" },\n\t}),\n\tfull: Object.freeze({\n\t\tstatusLine: {\n\t\t\tlayout: {\n\t\t\t\tleft: [\"hostname\", \"model\", \"thinking\", \"path\", \"git\", \"session\"],\n\t\t\t\tright: [\"token_in\", \"token_out\", \"cache_read\", \"cost\", \"context_pct\", \"time_spent\", \"time\"],\n\t\t\t\tsecondary: [\"extension_statuses\"],\n\t\t\t},\n\t\t},\n\t\teditor: { style: \"boxed\", frame: \"outline\", showMetadata: true },\n\t\tstartup: { mode: \"overlay\", showResources: true },\n\t}),\n\tascii: Object.freeze({\n\t\teditor: { style: \"compact\", frame: \"auto\" },\n\t\tstartup: { mode: \"compact\" },\n\t\ttheme: { nerdFonts: \"off\", terminalBackgroundSync: \"off\" },\n\t}),\n\tnative: Object.freeze({\n\t\tstatusLine: { layout: { left: [\"model\", \"path\"], right: [\"context_pct\"], secondary: [] } },\n\t\teditor: { style: \"native\", frame: \"native\", showMetadata: false },\n\t\tstartup: { mode: \"off\" },\n\t\tmessages: { enabled: false },\n\t\ttools: { enabled: false },\n\t\ttheme: { terminalBackgroundSync: \"off\", autoApply: \"off\" },\n\t}),\n});\n\nexport function presetConfig(name: unknown): Readonly<PiStyleConfig> {\n\treturn CONFIG_PRESETS[(typeof name === \"string\" && name in CONFIG_PRESETS ? name : \"default\") as PresetName];\n}\n","export const PI_STYLE_SCHEMA_VERSION = 1 as const;\n\nexport type Placement = \"above\" | \"below\";\nexport type NerdFontsMode = \"auto\" | \"on\" | \"off\";\nexport type ToggleMode = \"auto\" | \"on\" | \"off\";\nexport type PresetName = \"default\" | \"minimal\" | \"compact\" | \"full\" | \"ascii\" | \"native\";\nexport type EditorStyle = \"compact\" | \"boxed\" | \"dock\" | \"native\";\nexport type EditorFrame = \"auto\" | \"halfblock\" | \"line\" | \"solid\" | \"outline\" | \"rounded\" | \"native\";\n\nexport interface StatusCustomItemConfig {\n\tid: string;\n\tstatusKey: string;\n\tlabel?: string;\n\tpriority?: number;\n\tplacement?: \"left\" | \"right\" | \"secondary\";\n}\n\nexport interface PiStyleConfig {\n\tenabled?: boolean;\n\tpreset?: string;\n\tplacement?: string;\n\tstartup?: { mode?: string; showResources?: boolean; alwaysExpanded?: boolean };\n\tstatusLine?: {\n\t\tenabled?: boolean;\n\t\tseparator?: string;\n\t\tlayout?: { left?: string[]; right?: string[]; secondary?: string[] };\n\t\tdisabledSegments?: string[];\n\t\tcustomItems?: StatusCustomItemConfig[];\n\t\t/** Blank rows reserved below the primary status row (0 disables). */\n\t\tbottomMargin?: number;\n\t\t/** Context progress-bar cell count (default 10). */\n\t\tcontextBarWidth?: number;\n\t};\n\teditor?: { enabled?: boolean; style?: string; frame?: string; showMetadata?: boolean; hint?: string };\n\tmessages?: { enabled?: boolean; assistantPrefix?: boolean; specialBlocks?: boolean; hideThinkingLabel?: boolean };\n\ttools?: {\n\t\tenabled?: boolean;\n\t\tstyle?: string;\n\t\tmaxCollapsedLines?: number;\n\t\tmaxExpandedLines?: number;\n\t\tdimOutput?: boolean;\n\t\tshowElapsed?: boolean;\n\t};\n\ttheme?: {\n\t\tnerdFonts?: string;\n\t\tterminalBackgroundSync?: string;\n\t\t/** Pi theme name auto-applied at TUI session start (\"off\" disables; default \"titanium\"). */\n\t\tautoApply?: string;\n\t\tcolors?: Record<string, unknown>;\n\t\tglyphs?: Record<string, unknown>;\n\t};\n\tcompatibility?: {\n\t\tallowSafePatches?: boolean;\n\t\tallowCorePatches?: boolean;\n\t\tpreferExistingEditor?: boolean;\n\t\tpreferExistingFooter?: boolean;\n\t};\n\tdebug?: boolean;\n\tschemaVersion?: number;\n}\n\nexport interface NormalizedPiStyleConfig {\n\treadonly schemaVersion: typeof PI_STYLE_SCHEMA_VERSION;\n\treadonly enabled: boolean;\n\treadonly preset: PresetName;\n\treadonly placement: Placement;\n\treadonly startup: {\n\t\tmode: \"off\" | \"compact\" | \"overlay\";\n\t\tshowResources: boolean;\n\t\talwaysExpanded: boolean;\n\t};\n\treadonly statusLine: {\n\t\tenabled: boolean;\n\t\tseparator: string;\n\t\tlayout: { left: readonly string[]; right: readonly string[]; secondary: readonly string[] };\n\t\tdisabledSegments: readonly string[];\n\t\tcustomItems: readonly StatusCustomItemConfig[];\n\t\t/** Blank rows reserved below the primary status row (0 disables). */\n\t\tbottomMargin: number;\n\t\t/** Context progress-bar cell count. */\n\t\tcontextBarWidth: number;\n\t};\n\treadonly editor: { enabled: boolean; style: EditorStyle; frame: EditorFrame; showMetadata: boolean; hint: string };\n\treadonly messages: { enabled: boolean; assistantPrefix: boolean; specialBlocks: boolean; hideThinkingLabel: boolean };\n\treadonly tools: {\n\t\tenabled: boolean;\n\t\tstyle: string;\n\t\tmaxCollapsedLines: number;\n\t\tmaxExpandedLines: number;\n\t\tdimOutput: boolean;\n\t\tshowElapsed: boolean;\n\t};\n\treadonly theme: {\n\t\tnerdFonts: NerdFontsMode;\n\t\tterminalBackgroundSync: ToggleMode;\n\t\t/** Pi theme name auto-applied at TUI session start; \"off\" disables the surface. */\n\t\tautoApply: string;\n\t\tcolors: Readonly<Record<string, string>>;\n\t\tglyphs: Readonly<Record<string, string>>;\n\t};\n\treadonly compatibility: {\n\t\tallowSafePatches: boolean;\n\t\tallowCorePatches: boolean;\n\t\tpreferExistingEditor: boolean;\n\t\tpreferExistingFooter: boolean;\n\t};\n\t/** Internal provenance marker; never serialized or accepted as a command field. */\n\treadonly productCorePatchesExplicit?: boolean;\n\treadonly debug: boolean;\n}\n\nexport interface ConfigSources {\n\tdefaults?: unknown;\n\tglobal?: unknown;\n\tproject?: unknown;\n\tenvironment?: Record<string, string | undefined>;\n\tsession?: unknown;\n\tprojectTrusted?: boolean;\n}\n","import type { PresetName } from \"./config-types.js\";\nimport type { StatusLayout, StatusSegmentId } from \"./status.js\";\n\nexport const STATUS_PRESETS: Readonly<Record<PresetName, StatusLayout>> = Object.freeze({\n\tdefault: Object.freeze({\n\t\tleft: [\"path\", \"git\", \"context_bar\", \"cost\"],\n\t\tright: [\"model_effort\"],\n\t\tsecondary: [\"extension_statuses\"],\n\t}),\n\tminimal: Object.freeze({ left: [\"path\", \"git\"], right: [\"context_pct\"], secondary: [] }),\n\tcompact: Object.freeze({\n\t\tleft: [\"model\", \"thinking\", \"git\"],\n\t\tright: [\"context_pct\"],\n\t\tsecondary: [\"extension_statuses\"],\n\t}),\n\tfull: Object.freeze({\n\t\tleft: [\"hostname\", \"model\", \"thinking\", \"path\", \"git\", \"session\"],\n\t\tright: [\"token_in\", \"token_out\", \"cache_read\", \"cost\", \"context_pct\", \"time_spent\", \"time\"],\n\t\tsecondary: [\"extension_statuses\"],\n\t}),\n\tascii: Object.freeze({\n\t\tleft: [\"path\", \"git\", \"context_bar\", \"cost\"],\n\t\tright: [\"model_effort\"],\n\t\tsecondary: [\"extension_statuses\"],\n\t}),\n\tnative: Object.freeze({ left: [\"model\", \"path\"], right: [\"context_pct\"], secondary: [] }),\n});\n\nfunction unique(values: readonly unknown[]): StatusSegmentId[] {\n\tconst result: StatusSegmentId[] = [];\n\tfor (const value of values) {\n\t\tif (typeof value !== \"string\" || result.includes(value)) continue;\n\t\tresult.push(value);\n\t}\n\treturn result;\n}\n\nexport function normalizeStatusLayout(\n\tpreset: PresetName,\n\tinput:\n\t\t| {\n\t\t\t\tleft?: readonly unknown[] | undefined;\n\t\t\t\tright?: readonly unknown[] | undefined;\n\t\t\t\tsecondary?: readonly unknown[] | undefined;\n\t\t }\n\t\t| undefined,\n): StatusLayout {\n\tconst base = STATUS_PRESETS[preset] ?? STATUS_PRESETS.default;\n\tconst left = input?.left === undefined ? base.left : unique(input.left);\n\tconst right = input?.right === undefined ? base.right : unique(input.right);\n\tconst secondary = input?.secondary === undefined ? base.secondary : unique(input.secondary);\n\tconst seen = new Set<StatusSegmentId>();\n\tconst dedupe = (values: readonly StatusSegmentId[]) =>\n\t\tvalues.filter((value) => {\n\t\t\tif (seen.has(value)) return false;\n\t\t\tseen.add(value);\n\t\t\treturn true;\n\t\t});\n\treturn Object.freeze({ left: dedupe(left), right: dedupe(right), secondary: dedupe(secondary) });\n}\n","import { boundedDiagnostics, type ConfigDiagnostic } from \"./config-diagnostics.js\";\nimport { presetConfig } from \"./config-presets.js\";\nimport {\n\ttype ConfigSources,\n\ttype NormalizedPiStyleConfig,\n\tPI_STYLE_SCHEMA_VERSION,\n\ttype PiStyleConfig,\n} from \"./config-types.js\";\nimport { normalizeStatusLayout } from \"./status-presets.js\";\n\nexport const DEFAULT_CONFIG: NormalizedPiStyleConfig = Object.freeze({\n\tschemaVersion: PI_STYLE_SCHEMA_VERSION,\n\tenabled: true,\n\tpreset: \"default\",\n\tplacement: \"below\",\n\tstartup: Object.freeze({ mode: \"compact\", showResources: false, alwaysExpanded: false }),\n\tstatusLine: Object.freeze({\n\t\tenabled: true,\n\t\tseparator: \"powerline-thin\",\n\t\tlayout: Object.freeze({\n\t\t\tleft: [\"path\", \"git\", \"context_bar\", \"cost\"],\n\t\t\tright: [\"model_effort\"],\n\t\t\tsecondary: [],\n\t\t}),\n\t\tdisabledSegments: [],\n\t\tcustomItems: [],\n\t\tbottomMargin: 1,\n\t\tcontextBarWidth: 10,\n\t}),\n\teditor: Object.freeze({ enabled: true, style: \"dock\", frame: \"rounded\", showMetadata: false, hint: \"\" }),\n\tmessages: Object.freeze({ enabled: true, assistantPrefix: true, specialBlocks: true, hideThinkingLabel: true }),\n\ttools: Object.freeze({\n\t\tenabled: true,\n\t\tstyle: \"compact-box\",\n\t\tmaxCollapsedLines: 10,\n\t\tmaxExpandedLines: 50,\n\t\tdimOutput: false,\n\t\tshowElapsed: true,\n\t}),\n\ttheme: Object.freeze({\n\t\tnerdFonts: \"auto\",\n\t\tterminalBackgroundSync: \"auto\",\n\t\tautoApply: \"titanium\",\n\t\tcolors: {},\n\t\tglyphs: {},\n\t}),\n\tcompatibility: Object.freeze({\n\t\tallowSafePatches: true,\n\t\tallowCorePatches: false,\n\t\tpreferExistingEditor: true,\n\t\tpreferExistingFooter: true,\n\t}),\n\tdebug: false,\n});\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction merge(base: Record<string, unknown>, source: unknown): Record<string, unknown> {\n\tif (!isRecord(source)) return base;\n\tconst result: Record<string, unknown> = { ...base };\n\tfor (const [key, value] of Object.entries(source))\n\t\tresult[key] =\n\t\t\tisRecord(value) && isRecord(result[key]) ? merge(result[key] as Record<string, unknown>, value) : value;\n\treturn result;\n}\nfunction bool(value: unknown, fallback: boolean): boolean {\n\treturn typeof value === \"boolean\" ? value : fallback;\n}\nfunction boundedInt(value: unknown, fallback: number, min: number, max: number): number {\n\treturn typeof value === \"number\" && Number.isFinite(value)\n\t\t? Math.min(max, Math.max(min, Math.floor(value)))\n\t\t: fallback;\n}\nfunction stringEnum<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {\n\treturn typeof value === \"string\" && (allowed as readonly string[]).includes(value) ? (value as T) : fallback;\n}\nfunction strings(value: unknown, fallback: readonly string[]): readonly string[] {\n\treturn Array.isArray(value) && value.every((item) => typeof item === \"string\") ? [...value] : fallback;\n}\nfunction stringMap(value: unknown): Readonly<Record<string, string>> {\n\treturn isRecord(value)\n\t\t? Object.fromEntries(\n\t\t\t\tObject.entries(value).filter((entry): entry is [string, string] => typeof entry[1] === \"string\"),\n\t\t\t)\n\t\t: {};\n}\nfunction customItems(value: unknown): readonly import(\"./config-types.js\").StatusCustomItemConfig[] {\n\tif (!Array.isArray(value)) return [];\n\treturn value.filter((item): item is import(\"./config-types.js\").StatusCustomItemConfig => {\n\t\tif (!isRecord(item) || typeof item.id !== \"string\" || typeof item.statusKey !== \"string\") return false;\n\t\treturn item.placement === undefined || [\"left\", \"right\", \"secondary\"].includes(item.placement as string);\n\t});\n}\n\nexport function normalizeConfig(\n\tinput: unknown,\n\tdefaults: NormalizedPiStyleConfig = DEFAULT_CONFIG,\n): NormalizedPiStyleConfig {\n\tconst value = merge(defaults as unknown as Record<string, unknown>, acceptedInput(input));\n\tconst inputRecord = isRecord(input) ? input : {};\n\tconst inputStatus = isRecord(inputRecord.statusLine) ? inputRecord.statusLine : {};\n\tconst inputLayout = isRecord(inputStatus.layout) ? inputStatus.layout : undefined;\n\tconst startup = isRecord(value.startup) ? value.startup : {};\n\tconst status = isRecord(value.statusLine) ? value.statusLine : {};\n\tconst editor = isRecord(value.editor) ? value.editor : {};\n\tconst messages = isRecord(value.messages) ? value.messages : {};\n\tconst tools = isRecord(value.tools) ? value.tools : {};\n\tconst theme = isRecord(value.theme) ? value.theme : {};\n\tconst compatibility = isRecord(value.compatibility) ? value.compatibility : {};\n\tconst max =\n\t\ttypeof tools.maxCollapsedLines === \"number\" &&\n\t\tNumber.isFinite(tools.maxCollapsedLines) &&\n\t\ttools.maxCollapsedLines >= 0\n\t\t\t? Math.floor(tools.maxCollapsedLines)\n\t\t\t: defaults.tools.maxCollapsedLines;\n\tconst maxExpanded =\n\t\ttypeof tools.maxExpandedLines === \"number\" && Number.isFinite(tools.maxExpandedLines) && tools.maxExpandedLines >= 0\n\t\t\t? Math.min(Math.floor(tools.maxExpandedLines), 1000)\n\t\t\t: defaults.tools.maxExpandedLines;\n\treturn Object.freeze({\n\t\tschemaVersion: PI_STYLE_SCHEMA_VERSION,\n\t\tenabled: bool(value.enabled, defaults.enabled),\n\t\tpreset: stringEnum(value.preset, [\"default\", \"minimal\", \"compact\", \"full\", \"ascii\", \"native\"], defaults.preset),\n\t\tplacement: stringEnum(value.placement, [\"above\", \"below\"], defaults.placement),\n\t\tstartup: Object.freeze({\n\t\t\tmode: stringEnum(startup.mode, [\"off\", \"compact\", \"overlay\"], defaults.startup.mode),\n\t\t\tshowResources: bool(startup.showResources, defaults.startup.showResources),\n\t\t\talwaysExpanded: bool(startup.alwaysExpanded, defaults.startup.alwaysExpanded),\n\t\t}),\n\t\tstatusLine: Object.freeze({\n\t\t\tenabled: bool(status.enabled, defaults.statusLine.enabled),\n\t\t\tseparator: typeof status.separator === \"string\" ? status.separator : defaults.statusLine.separator,\n\t\t\tlayout: normalizeStatusLayout(\n\t\t\t\tstringEnum(value.preset, [\"default\", \"minimal\", \"compact\", \"full\", \"ascii\", \"native\"], defaults.preset),\n\t\t\t\tinputLayout\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tleft:\n\t\t\t\t\t\t\t\tinputLayout.left === undefined ? undefined : strings(inputLayout.left, defaults.statusLine.layout.left),\n\t\t\t\t\t\t\tright:\n\t\t\t\t\t\t\t\tinputLayout.right === undefined\n\t\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t\t: strings(inputLayout.right, defaults.statusLine.layout.right),\n\t\t\t\t\t\t\tsecondary:\n\t\t\t\t\t\t\t\tinputLayout.secondary === undefined\n\t\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t\t: strings(inputLayout.secondary, defaults.statusLine.layout.secondary),\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\t),\n\t\t\tdisabledSegments: strings(status.disabledSegments, defaults.statusLine.disabledSegments),\n\t\t\tcustomItems: customItems(status.customItems),\n\t\t\tbottomMargin: boundedInt(status.bottomMargin, defaults.statusLine.bottomMargin, 0, 4),\n\t\t\tcontextBarWidth: boundedInt(status.contextBarWidth, defaults.statusLine.contextBarWidth, 4, 40),\n\t\t}),\n\t\teditor: Object.freeze({\n\t\t\tenabled: bool(editor.enabled, defaults.editor.enabled),\n\t\t\tstyle: stringEnum(editor.style, [\"compact\", \"boxed\", \"dock\", \"native\"], defaults.editor.style),\n\t\t\tframe: stringEnum(\n\t\t\t\teditor.frame,\n\t\t\t\t[\"auto\", \"halfblock\", \"line\", \"solid\", \"outline\", \"rounded\", \"native\"],\n\t\t\t\tdefaults.editor.frame,\n\t\t\t),\n\t\t\tshowMetadata: bool(editor.showMetadata, defaults.editor.showMetadata),\n\t\t\thint: typeof editor.hint === \"string\" ? editor.hint : defaults.editor.hint,\n\t\t}),\n\t\tmessages: Object.freeze({\n\t\t\tenabled: bool(messages.enabled, defaults.messages.enabled),\n\t\t\tassistantPrefix: bool(messages.assistantPrefix, defaults.messages.assistantPrefix),\n\t\t\tspecialBlocks: bool(messages.specialBlocks, defaults.messages.specialBlocks),\n\t\t\thideThinkingLabel: bool(messages.hideThinkingLabel, defaults.messages.hideThinkingLabel),\n\t\t}),\n\t\ttools: Object.freeze({\n\t\t\tenabled: bool(tools.enabled, defaults.tools.enabled),\n\t\t\tstyle: typeof tools.style === \"string\" ? tools.style : defaults.tools.style,\n\t\t\tmaxCollapsedLines: max,\n\t\t\tmaxExpandedLines: maxExpanded,\n\t\t\tdimOutput: bool(tools.dimOutput, defaults.tools.dimOutput),\n\t\t\tshowElapsed: bool(tools.showElapsed, defaults.tools.showElapsed),\n\t\t}),\n\t\ttheme: Object.freeze({\n\t\t\tnerdFonts: stringEnum(theme.nerdFonts, [\"auto\", \"on\", \"off\"], defaults.theme.nerdFonts),\n\t\t\tterminalBackgroundSync: stringEnum(\n\t\t\t\ttheme.terminalBackgroundSync,\n\t\t\t\t[\"auto\", \"on\", \"off\"],\n\t\t\t\tdefaults.theme.terminalBackgroundSync,\n\t\t\t),\n\t\t\tautoApply:\n\t\t\t\ttypeof theme.autoApply === \"string\" && theme.autoApply.trim() !== \"\"\n\t\t\t\t\t? theme.autoApply\n\t\t\t\t\t: defaults.theme.autoApply,\n\t\t\tcolors: stringMap(theme.colors),\n\t\t\tglyphs: stringMap(theme.glyphs),\n\t\t}),\n\t\tcompatibility: Object.freeze({\n\t\t\tallowSafePatches: bool(compatibility.allowSafePatches, defaults.compatibility.allowSafePatches),\n\t\t\tallowCorePatches: bool(compatibility.allowCorePatches, defaults.compatibility.allowCorePatches),\n\t\t\tpreferExistingEditor: bool(compatibility.preferExistingEditor, defaults.compatibility.preferExistingEditor),\n\t\t\tpreferExistingFooter: bool(compatibility.preferExistingFooter, defaults.compatibility.preferExistingFooter),\n\t\t}),\n\t\tdebug: bool(value.debug, defaults.debug),\n\t});\n}\n\nexport function resolveConfig(sources: ConfigSources): NormalizedPiStyleConfig {\n\treturn resolveConfigDetailed(sources).config;\n}\n\nconst PRESET_NAMES = [\"default\", \"minimal\", \"compact\", \"full\", \"ascii\", \"native\"] as const;\nconst ENUMS: Readonly<Record<string, readonly string[]>> = {\n\tpreset: PRESET_NAMES,\n\tplacement: [\"above\", \"below\"],\n\t\"startup.mode\": [\"off\", \"compact\", \"overlay\"],\n\t\"editor.style\": [\"compact\", \"boxed\", \"dock\", \"native\"],\n\t\"editor.frame\": [\"auto\", \"halfblock\", \"line\", \"solid\", \"outline\", \"rounded\", \"native\"],\n\t\"theme.nerdFonts\": [\"auto\", \"on\", \"off\"],\n\t\"theme.terminalBackgroundSync\": [\"auto\", \"on\", \"off\"],\n};\nconst BOOL_PATHS = new Set([\n\t\"enabled\",\n\t\"startup.showResources\",\n\t\"startup.alwaysExpanded\",\n\t\"statusLine.enabled\",\n\t\"editor.enabled\",\n\t\"editor.showMetadata\",\n\t\"messages.enabled\",\n\t\"messages.assistantPrefix\",\n\t\"messages.specialBlocks\",\n\t\"messages.hideThinkingLabel\",\n\t\"tools.enabled\",\n\t\"tools.showElapsed\",\n\t\"tools.dimOutput\",\n\t\"compatibility.allowSafePatches\",\n\t\"compatibility.allowCorePatches\",\n\t\"compatibility.preferExistingEditor\",\n\t\"compatibility.preferExistingFooter\",\n\t\"debug\",\n]);\nconst STRING_ARRAY_PATHS = new Set([\n\t\"statusLine.layout.left\",\n\t\"statusLine.layout.right\",\n\t\"statusLine.layout.secondary\",\n\t\"statusLine.disabledSegments\",\n]);\nconst MAP_PATHS = new Set([\"theme.colors\", \"theme.glyphs\"]);\nconst CONTAINER_PATHS = new Set([\n\t\"startup\",\n\t\"statusLine\",\n\t\"statusLine.layout\",\n\t\"editor\",\n\t\"messages\",\n\t\"tools\",\n\t\"theme\",\n\t\"compatibility\",\n]);\nfunction validCustomItem(item: unknown): boolean {\n\tif (!isRecord(item) || typeof item.id !== \"string\" || typeof item.statusKey !== \"string\") return false;\n\tif (Object.keys(item).some((key) => ![\"id\", \"statusKey\", \"label\", \"priority\", \"placement\"].includes(key)))\n\t\treturn false;\n\tif (item.label !== undefined && typeof item.label !== \"string\") return false;\n\tif (item.priority !== undefined && (typeof item.priority !== \"number\" || !Number.isFinite(item.priority)))\n\t\treturn false;\n\treturn (\n\t\titem.placement === undefined ||\n\t\titem.placement === \"left\" ||\n\t\titem.placement === \"right\" ||\n\t\titem.placement === \"secondary\"\n\t);\n}\nfunction validLeaf(path: string, value: unknown): boolean {\n\tif (BOOL_PATHS.has(path)) return typeof value === \"boolean\";\n\tif (ENUMS[path]) return typeof value === \"string\" && ENUMS[path].includes(value);\n\tif (path === \"theme.autoApply\") return typeof value === \"string\" && value !== \"\";\n\tif (path === \"statusLine.separator\" || path === \"tools.style\" || path === \"editor.hint\")\n\t\treturn typeof value === \"string\";\n\tif (path === \"tools.maxCollapsedLines\" || path === \"tools.maxExpandedLines\")\n\t\treturn typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\tif (path === \"statusLine.bottomMargin\" || path === \"statusLine.contextBarWidth\")\n\t\treturn typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\tif (STRING_ARRAY_PATHS.has(path)) return Array.isArray(value) && value.every((item) => typeof item === \"string\");\n\tif (MAP_PATHS.has(path)) return isRecord(value) && Object.values(value).every((item) => typeof item === \"string\");\n\tif (path === \"statusLine.customItems\") return Array.isArray(value) && value.every(validCustomItem);\n\treturn false;\n}\nexport interface ConfigLayerResult {\n\treadonly accepted: unknown;\n\treadonly diagnostics: readonly ConfigDiagnostic[];\n\treadonly paths: ReadonlySet<string>;\n}\nfunction cloneLeaf(value: unknown): unknown {\n\treturn Array.isArray(value)\n\t\t? value.map((item) => (isRecord(item) ? { ...item } : item))\n\t\t: isRecord(value)\n\t\t\t? { ...value }\n\t\t\t: value;\n}\nexport function validateConfigLayer(input: unknown): ConfigLayerResult {\n\tconst diagnostics: ConfigDiagnostic[] = [];\n\tconst paths = new Set<string>();\n\tconst walk = (value: unknown, prefix: string): unknown => {\n\t\tif (!isRecord(value)) return value;\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const [key, nestedValue] of Object.entries(value)) {\n\t\t\tconst path = prefix ? `${prefix}.${key}` : key;\n\t\t\tif (path === \"schemaVersion\") {\n\t\t\t\tif (nestedValue === undefined || nestedValue === PI_STYLE_SCHEMA_VERSION) result[key] = nestedValue;\n\t\t\t\telse\n\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\tcode: \"CFG-SCHEMA\",\n\t\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tmessage: \"unsupported schema version ignored\",\n\t\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (path === \"statusLine.customItems\" && Array.isArray(nestedValue)) {\n\t\t\t\tconst acceptedItems: Record<string, unknown>[] = [];\n\t\t\t\tfor (const [index, item] of nestedValue.entries()) {\n\t\t\t\t\tif (!isRecord(item)) {\n\t\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\t\tcode: \"CFG-VALUE\",\n\t\t\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\t\t\tpath: `${path}[${index}]`,\n\t\t\t\t\t\t\tmessage: \"custom item must be an object\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst allowed = [\"id\", \"statusKey\", \"label\", \"priority\", \"placement\"];\n\t\t\t\t\tlet valid = typeof item.id === \"string\" && typeof item.statusKey === \"string\";\n\t\t\t\t\tif (typeof item.id !== \"string\")\n\t\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\t\tcode: \"CFG-VALUE\",\n\t\t\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\t\t\tpath: `${path}[${index}].id`,\n\t\t\t\t\t\t\tmessage: \"required custom item field is invalid or missing\",\n\t\t\t\t\t\t});\n\t\t\t\t\tif (typeof item.statusKey !== \"string\")\n\t\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\t\tcode: \"CFG-VALUE\",\n\t\t\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\t\t\tpath: `${path}[${index}].statusKey`,\n\t\t\t\t\t\t\tmessage: \"required custom item field is invalid or missing\",\n\t\t\t\t\t\t});\n\t\t\t\t\tfor (const field of Object.keys(item)) {\n\t\t\t\t\t\tif (!allowed.includes(field)) {\n\t\t\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\t\t\tcode: \"CFG-VALUE\",\n\t\t\t\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\t\t\t\tpath: `${path}[${index}].${field}`,\n\t\t\t\t\t\t\t\tmessage: \"unknown custom item field ignored\",\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tvalid = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (item.label !== undefined && typeof item.label !== \"string\") {\n\t\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\t\tcode: \"CFG-VALUE\",\n\t\t\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\t\t\tpath: `${path}[${index}].label`,\n\t\t\t\t\t\t\tmessage: \"invalid custom item field ignored\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tvalid = false;\n\t\t\t\t\t}\n\t\t\t\t\tif (item.priority !== undefined && (typeof item.priority !== \"number\" || !Number.isFinite(item.priority))) {\n\t\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\t\tcode: \"CFG-VALUE\",\n\t\t\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\t\t\tpath: `${path}[${index}].priority`,\n\t\t\t\t\t\t\tmessage: \"invalid custom item field ignored\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tvalid = false;\n\t\t\t\t\t}\n\t\t\t\t\tif (item.placement !== undefined && ![\"left\", \"right\", \"secondary\"].includes(item.placement as string)) {\n\t\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\t\tcode: \"CFG-VALUE\",\n\t\t\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\t\t\tpath: `${path}[${index}].placement`,\n\t\t\t\t\t\t\tmessage: \"invalid custom item field ignored\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tvalid = false;\n\t\t\t\t\t}\n\t\t\t\t\tif (valid) {\n\t\t\t\t\t\tacceptedItems.push({ ...item });\n\t\t\t\t\t\tpaths.add(`${path}[${index}].id`);\n\t\t\t\t\t\tpaths.add(`${path}[${index}].statusKey`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tresult[key] = acceptedItems;\n\t\t\t\tpaths.add(path);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (validLeaf(path, nestedValue)) {\n\t\t\t\tresult[key] = cloneLeaf(nestedValue);\n\t\t\t\tpaths.add(path);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tisRecord(nestedValue) &&\n\t\t\t\tCONTAINER_PATHS.has(path) &&\n\t\t\t\t!MAP_PATHS.has(path) &&\n\t\t\t\tpath !== \"statusLine.customItems\"\n\t\t\t) {\n\t\t\t\tconst child = walk(nestedValue, path);\n\t\t\t\tif (isRecord(child) && Object.keys(child).length > 0) result[key] = child;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (path !== \"statusLine.customItems\" || !Array.isArray(nestedValue))\n\t\t\t\tdiagnostics.push({ code: \"CFG-VALUE\", level: \"warning\", path, message: \"invalid or unknown field ignored\" });\n\t\t\tif (path === \"statusLine.customItems\" && Array.isArray(nestedValue))\n\t\t\t\tfor (const [index, item] of nestedValue.entries()) {\n\t\t\t\t\tif (!isRecord(item)) continue;\n\t\t\t\t\tfor (const field of [\"id\", \"statusKey\", \"label\", \"priority\", \"placement\"]) {\n\t\t\t\t\t\tif (Object.hasOwn(item, field)) {\n\t\t\t\t\t\t\tconst fieldValue = item[field];\n\t\t\t\t\t\t\tconst valid =\n\t\t\t\t\t\t\t\tfield === \"id\" || field === \"statusKey\" || field === \"label\"\n\t\t\t\t\t\t\t\t\t? typeof fieldValue === \"string\"\n\t\t\t\t\t\t\t\t\t: field === \"priority\"\n\t\t\t\t\t\t\t\t\t\t? typeof fieldValue === \"number\" && Number.isFinite(fieldValue)\n\t\t\t\t\t\t\t\t\t\t: fieldValue === \"left\" || fieldValue === \"right\" || fieldValue === \"secondary\";\n\t\t\t\t\t\t\tif (!valid)\n\t\t\t\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\t\t\t\tcode: \"CFG-VALUE\",\n\t\t\t\t\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\t\t\t\t\tpath: `${path}[${index}].${field}`,\n\t\t\t\t\t\t\t\t\tmessage: \"invalid custom item field ignored\",\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfor (const field of Object.keys(item))\n\t\t\t\t\t\tif (![\"id\", \"statusKey\", \"label\", \"priority\", \"placement\"].includes(field))\n\t\t\t\t\t\t\tdiagnostics.push({\n\t\t\t\t\t\t\t\tcode: \"CFG-VALUE\",\n\t\t\t\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\t\t\t\tpath: `${path}[${index}].${field}`,\n\t\t\t\t\t\t\t\tmessage: \"unknown custom item field ignored\",\n\t\t\t\t\t\t\t});\n\t\t\t\t}\n\t\t}\n\t\treturn result;\n\t};\n\treturn { accepted: walk(input, \"\"), diagnostics: boundedDiagnostics(diagnostics), paths };\n}\nfunction acceptedInput(input: unknown): unknown {\n\treturn validateConfigLayer(input).accepted;\n}\n\nexport function resolveConfigDetailed(sources: ConfigSources): {\n\treadonly config: NormalizedPiStyleConfig;\n\treadonly diagnostics: readonly ConfigDiagnostic[];\n\treadonly sources: Readonly<Record<string, string>>;\n} {\n\tconst diagnostics: ConfigDiagnostic[] = [];\n\tconst layerResults = new Map<string, ConfigLayerResult>();\n\tconst layers: readonly [string, unknown][] = [\n\t\t[\"global\", sources.global],\n\t\t[\"project\", sources.projectTrusted === false ? undefined : sources.project],\n\t\t[\"session\", sources.session],\n\t];\n\tfor (const [name, value] of layers) {\n\t\tconst result = validateConfigLayer(value);\n\t\tlayerResults.set(name, result);\n\t\tdiagnostics.push(...result.diagnostics);\n\t}\n\tconst defaults = sources.defaults ?? DEFAULT_CONFIG;\n\tlet merged: unknown = defaults;\n\tconst presetCandidates = [\n\t\t[\"session\", sources.session],\n\t\t[\"project\", sources.projectTrusted === false ? undefined : sources.project],\n\t\t[\"global\", sources.global],\n\t\t[\"default\", defaults],\n\t] as const;\n\tlet selectedPreset: unknown;\n\tfor (const [, source] of presetCandidates) {\n\t\tconst candidate = isRecord(source) ? source.preset : undefined;\n\t\tif (candidate === undefined) continue;\n\t\tif (typeof candidate === \"string\" && (PRESET_NAMES as readonly string[]).includes(candidate)) {\n\t\t\tselectedPreset = candidate;\n\t\t\tbreak;\n\t\t}\n\t\tdiagnostics.push({\n\t\t\tcode: \"CFG-ENUM\",\n\t\t\tlevel: \"warning\",\n\t\t\tpath: \"preset\",\n\t\t\tmessage: \"unsupported value; lower-precedence preset used\",\n\t\t});\n\t}\n\tmerged = merge(isRecord(merged) ? merged : {}, presetConfig(selectedPreset));\n\tfor (const name of [\"global\", \"project\"] as const)\n\t\tmerged = merge(isRecord(merged) ? merged : {}, layerResults.get(name)?.accepted);\n\tconst env = sources.environment ?? {};\n\tconst envPatch: PiStyleConfig = {};\n\tif (env.PI_STYLE_DISABLED === \"1\") envPatch.enabled = false;\n\tif (env.PI_STYLE_NERD_FONTS === \"1\" || env.PI_STYLE_NERD_FONTS === \"0\")\n\t\tenvPatch.theme = { nerdFonts: env.PI_STYLE_NERD_FONTS === \"1\" ? \"on\" : \"off\" };\n\tif (env.PI_STYLE_EDITOR && [\"native\", \"compact\", \"boxed\", \"dock\"].includes(env.PI_STYLE_EDITOR))\n\t\tenvPatch.editor = { style: env.PI_STYLE_EDITOR };\n\tif (env.PI_STYLE_THEME !== undefined && env.PI_STYLE_THEME !== \"\")\n\t\tenvPatch.theme = { ...(envPatch.theme ?? {}), autoApply: env.PI_STYLE_THEME };\n\tif (env.PI_STYLE_OSC11 === \"1\" || env.PI_STYLE_OSC11 === \"0\")\n\t\tenvPatch.theme = { ...(envPatch.theme ?? {}), terminalBackgroundSync: env.PI_STYLE_OSC11 === \"1\" ? \"on\" : \"off\" };\n\tif (env.PI_STYLE_DEBUG === \"1\") envPatch.debug = true;\n\tif (env.PI_STYLE_STATUS === \"above\" || env.PI_STYLE_STATUS === \"below\") envPatch.placement = env.PI_STYLE_STATUS;\n\tif (env.PI_STYLE_STATUS === \"off\") envPatch.statusLine = { enabled: false };\n\tif (env.PI_STYLE_DISABLED !== undefined && env.PI_STYLE_DISABLED !== \"1\")\n\t\tdiagnostics.push({\n\t\t\tcode: \"CFG-ENV\",\n\t\t\tlevel: \"warning\",\n\t\t\tpath: \"PI_STYLE_DISABLED\",\n\t\t\tmessage: \"expected 1; override ignored\",\n\t\t});\n\tif (env.PI_STYLE_NERD_FONTS !== undefined && ![\"0\", \"1\"].includes(env.PI_STYLE_NERD_FONTS))\n\t\tdiagnostics.push({\n\t\t\tcode: \"CFG-ENV\",\n\t\t\tlevel: \"warning\",\n\t\t\tpath: \"PI_STYLE_NERD_FONTS\",\n\t\t\tmessage: \"expected 0 or 1; override ignored\",\n\t\t});\n\tif (env.PI_STYLE_STATUS !== undefined && ![\"above\", \"below\", \"off\"].includes(env.PI_STYLE_STATUS))\n\t\tdiagnostics.push({\n\t\t\tcode: \"CFG-ENV\",\n\t\t\tlevel: \"warning\",\n\t\t\tpath: \"PI_STYLE_STATUS\",\n\t\t\tmessage: \"expected above, below, or off; override ignored\",\n\t\t});\n\tif (env.PI_STYLE_EDITOR !== undefined && ![\"native\", \"compact\", \"boxed\", \"dock\"].includes(env.PI_STYLE_EDITOR))\n\t\tdiagnostics.push({\n\t\t\tcode: \"CFG-ENV\",\n\t\t\tlevel: \"warning\",\n\t\t\tpath: \"PI_STYLE_EDITOR\",\n\t\t\tmessage: \"unknown editor style; override ignored\",\n\t\t});\n\tfor (const [key, value] of Object.entries(env))\n\t\tif (\n\t\t\tvalue !== undefined &&\n\t\t\tkey.startsWith(\"PI_STYLE_\") &&\n\t\t\t![\n\t\t\t\t\"PI_STYLE_DISABLED\",\n\t\t\t\t\"PI_STYLE_NERD_FONTS\",\n\t\t\t\t\"PI_STYLE_EDITOR\",\n\t\t\t\t\"PI_STYLE_OSC11\",\n\t\t\t\t\"PI_STYLE_DEBUG\",\n\t\t\t\t\"PI_STYLE_STATUS\",\n\t\t\t\t\"PI_STYLE_THEME\",\n\t\t\t].includes(key)\n\t\t)\n\t\t\tdiagnostics.push({\n\t\t\t\tcode: \"CFG-ENV\",\n\t\t\t\tlevel: \"warning\",\n\t\t\t\tpath: key,\n\t\t\t\tmessage: \"unsupported environment override ignored\",\n\t\t\t});\n\tmerged = merge(isRecord(merged) ? merged : {}, envPatch);\n\tmerged = merge(isRecord(merged) ? merged : {}, layerResults.get(\"session\")?.accepted);\n\tconst sourceMap: Record<string, string> = {};\n\tconst sourcePath = (value: unknown, prefix: string, sourceName: string) => {\n\t\tif (!isRecord(value)) return;\n\t\tfor (const [key, nested] of Object.entries(value)) {\n\t\t\tconst path = prefix ? `${prefix}.${key}` : key;\n\t\t\tif (validLeaf(path, nested)) {\n\t\t\t\tsourceMap[path] = sourceName;\n\t\t\t\tif (path === \"statusLine.customItems\" && Array.isArray(nested))\n\t\t\t\t\tfor (const [index, item] of nested.entries())\n\t\t\t\t\t\tif (isRecord(item))\n\t\t\t\t\t\t\tfor (const field of [\"id\", \"statusKey\", \"label\", \"priority\", \"placement\"])\n\t\t\t\t\t\t\t\tif (Object.hasOwn(item, field)) sourceMap[`${path}[${index}].${field}`] = sourceName;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (isRecord(nested)) sourcePath(nested, path, sourceName);\n\t\t}\n\t};\n\tsourcePath(defaults, \"\", \"default\");\n\tsourcePath(\n\t\tpresetConfig(selectedPreset),\n\t\t\"\",\n\t\t`preset:${typeof selectedPreset === \"string\" ? selectedPreset : \"default\"}`,\n\t);\n\tsourcePath(layerResults.get(\"global\")?.accepted, \"\", \"global\");\n\tif (sources.projectTrusted !== false) sourcePath(layerResults.get(\"project\")?.accepted, \"\", \"project\");\n\tsourcePath(envPatch, \"\", \"environment\");\n\tsourcePath(layerResults.get(\"session\")?.accepted, \"\", \"session\");\n\treturn { config: normalizeConfig(merged), diagnostics: boundedDiagnostics(diagnostics), sources: sourceMap };\n}\n","import { boundedDiagnostics, type ConfigDiagnostic } from \"./config-diagnostics.js\";\nimport { PI_STYLE_SCHEMA_VERSION } from \"./config-types.js\";\n\nfunction record(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport interface MigrationResult {\n\treadonly config: Record<string, unknown> | undefined;\n\treadonly diagnostics: readonly ConfigDiagnostic[];\n\treadonly readOnly: boolean;\n}\n\n/** Purely validates the durable envelope; v1 is identity and future data is read-only. */\nexport function migrateConfig(input: unknown, source = \"config\"): MigrationResult {\n\tif (!record(input))\n\t\treturn {\n\t\t\tconfig: undefined,\n\t\t\treadOnly: false,\n\t\t\tdiagnostics: boundedDiagnostics([\n\t\t\t\t{ code: \"CFG-001\", level: \"warning\", path: source, message: \"configuration must be an object; defaults used\" },\n\t\t\t]),\n\t\t};\n\tconst version = input.schemaVersion;\n\tif (version === undefined)\n\t\treturn {\n\t\t\tconfig: { ...input, schemaVersion: PI_STYLE_SCHEMA_VERSION },\n\t\t\treadOnly: false,\n\t\t\tdiagnostics: boundedDiagnostics([\n\t\t\t\t{\n\t\t\t\t\tcode: \"CFG-002\",\n\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\tpath: `${source}.schemaVersion`,\n\t\t\t\t\tmessage: \"missing schemaVersion accepted as v1-shaped input\",\n\t\t\t\t},\n\t\t\t]),\n\t\t};\n\tif (version !== PI_STYLE_SCHEMA_VERSION)\n\t\treturn {\n\t\t\tconfig: undefined,\n\t\t\treadOnly: true,\n\t\t\tdiagnostics: boundedDiagnostics([\n\t\t\t\t{\n\t\t\t\t\tcode: \"CFG-003\",\n\t\t\t\t\tlevel: \"error\",\n\t\t\t\t\tpath: `${source}.schemaVersion`,\n\t\t\t\t\tmessage: `unsupported schemaVersion ${String(version)}; ignored without rewrite`,\n\t\t\t\t},\n\t\t\t]),\n\t\t};\n\treturn { config: { ...input }, readOnly: false, diagnostics: [] };\n}\n","import type { ConfigDiagnostic } from \"../domain/config-diagnostics.js\";\nimport { migrateConfig } from \"../domain/config-migrations.js\";\n\nexport interface ConfigStoragePaths {\n\treadonly globalPath: string;\n\treadonly projectPath: string;\n}\nexport interface ConfigFilePort {\n\tread(path: string): Promise<string>;\n\twriteAtomic(path: string, content: string): Promise<void>;\n}\nexport interface ConfigRead {\n\treadonly value: unknown;\n\treadonly diagnostics: readonly ConfigDiagnostic[];\n\treadonly readOnly: boolean;\n}\n\nexport async function readScopedConfig(\n\tport: ConfigFilePort,\n\tpath: string,\n\tselectedNamespace = \"piStyle\",\n): Promise<ConfigRead> {\n\ttry {\n\t\tconst parsed = JSON.parse(await port.read(path)) as unknown;\n\t\tif (!record(parsed))\n\t\t\treturn {\n\t\t\t\tvalue: undefined,\n\t\t\t\treadOnly: true,\n\t\t\t\tdiagnostics: [{ code: \"CFG-001\", level: \"warning\", path, message: \"settings root must be an object\" }],\n\t\t\t};\n\t\tif (!Object.hasOwn(parsed, selectedNamespace)) return { value: undefined, readOnly: false, diagnostics: [] };\n\t\tconst result = migrateConfig(parsed[selectedNamespace], `${path}.${selectedNamespace}`);\n\t\treturn { value: result.config, diagnostics: result.diagnostics, readOnly: result.readOnly };\n\t} catch (error) {\n\t\tconst code =\n\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error ? (error as { code?: unknown }).code : undefined;\n\t\tif (code === \"ENOENT\") return { value: undefined, readOnly: false, diagnostics: [] };\n\t\treturn {\n\t\t\tvalue: undefined,\n\t\t\treadOnly: true,\n\t\t\tdiagnostics: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"CFG-IO\",\n\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\tpath,\n\t\t\t\t\tmessage: `settings unreadable; preserved without rewrite (${error instanceof Error ? error.message : \"invalid JSON\"})`,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction mergePatch(base: unknown, patch: unknown): unknown {\n\tif (!record(base) || !record(patch)) return patch;\n\tconst result: Record<string, unknown> = { ...base };\n\tfor (const [key, value] of Object.entries(patch)) result[key] = mergePatch(result[key], value);\n\treturn result;\n}\n\nconst writeLocks = new Map<string, Promise<void>>();\n\nexport async function writeScopedConfig(\n\tport: ConfigFilePort,\n\tpath: string,\n\tvalue: unknown,\n\tselectedNamespace = \"piStyle\",\n): Promise<void> {\n\tconst previous = writeLocks.get(path) ?? Promise.resolve();\n\tconst operation = previous.then(async () => {\n\t\tlet document: Record<string, unknown> = {};\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(await port.read(path)) as unknown;\n\t\t\tif (!record(parsed)) throw new Error(\"settings root must be an object\");\n\t\t\tdocument = parsed;\n\t\t} catch (error) {\n\t\t\tconst code =\n\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error ? (error as { code?: unknown }).code : undefined;\n\t\t\tif (code !== \"ENOENT\") throw new Error(`refusing to rewrite unreadable settings: ${path}`);\n\t\t}\n\t\tif (Object.hasOwn(document, selectedNamespace)) {\n\t\t\tconst existing = migrateConfig(document[selectedNamespace], `${path}.${selectedNamespace}`);\n\t\t\tif (existing.readOnly || !record(document[selectedNamespace]))\n\t\t\t\tthrow new Error(`refusing to rewrite protected ${selectedNamespace} namespace: ${path}`);\n\t\t}\n\t\tconst nextNamespace = mergePatch(document[selectedNamespace], value);\n\t\tawait port.writeAtomic(path, `${JSON.stringify({ ...document, [selectedNamespace]: nextNamespace }, null, 2)}\\n`);\n\t});\n\twriteLocks.set(path, operation);\n\ttry {\n\t\tawait operation;\n\t} finally {\n\t\tif (writeLocks.get(path) === operation) writeLocks.delete(path);\n\t}\n}\n","import { validateConfigLayer } from \"../domain/config-normalization.js\";\nimport type { NormalizedPiStyleConfig } from \"../domain/config-types.js\";\nimport { type ConfigFilePort, type ConfigStoragePaths, writeScopedConfig } from \"./config-storage.js\";\n\nexport type Mutation = Record<string, unknown>;\nexport interface CommandUi {\n\tselect(title: string, options: string[]): Promise<string | undefined>;\n\tnotify(message: string, type?: \"info\" | \"warning\" | \"error\"): void;\n}\nexport interface CommandHost {\n\treadonly ui: CommandUi;\n\treadonly cwd: string;\n\tisProjectTrusted(): boolean;\n}\nexport interface CommandApp {\n\treadonly config: NormalizedPiStyleConfig;\n\tapplySession(patch: Mutation): void;\n\tsetProjectTrusted?(trusted: boolean): void;\n\treload(): Promise<void>;\n\tdoctor(): Readonly<Record<string, unknown>>;\n}\n\nconst surfaces = new Set([\"status\", \"editor\", \"startup\", \"messages\", \"tools\"]);\nconst presets = [\"default\", \"minimal\", \"compact\", \"full\", \"ascii\", \"native\"];\nconst styles = [\"compact\", \"boxed\", \"dock\", \"native\"];\nconst frames = [\"auto\", \"halfblock\", \"line\", \"solid\", \"outline\", \"native\"];\nconst startupModes = [\"off\", \"compact\", \"overlay\"];\nconst allowedPaths = new Set([\n\t\"enabled\",\n\t\"preset\",\n\t\"placement\",\n\t\"startup.mode\",\n\t\"startup.showResources\",\n\t\"statusLine.enabled\",\n\t\"statusLine.separator\",\n\t\"statusLine.layout.left\",\n\t\"statusLine.layout.right\",\n\t\"statusLine.layout.secondary\",\n\t\"statusLine.disabledSegments\",\n\t\"statusLine.customItems\",\n\t\"statusLine.bottomMargin\",\n\t\"statusLine.contextBarWidth\",\n\t\"editor.enabled\",\n\t\"editor.style\",\n\t\"editor.frame\",\n\t\"editor.showMetadata\",\n\t\"messages.enabled\",\n\t\"messages.assistantPrefix\",\n\t\"messages.specialBlocks\",\n\t\"messages.hideThinkingLabel\",\n\t\"tools.enabled\",\n\t\"tools.style\",\n\t\"tools.maxCollapsedLines\",\n\t\"tools.maxExpandedLines\",\n\t\"tools.dimOutput\",\n\t\"tools.showElapsed\",\n\t\"theme.nerdFonts\",\n\t\"theme.terminalBackgroundSync\",\n\t\"theme.autoApply\",\n\t\"theme.colors\",\n\t\"theme.glyphs\",\n\t\"compatibility.allowSafePatches\",\n\t\"compatibility.allowCorePatches\",\n\t\"compatibility.preferExistingEditor\",\n\t\"compatibility.preferExistingFooter\",\n\t\"debug\",\n]);\nfunction validatePathValue(path: string, value: unknown): boolean {\n\tif (!allowedPaths.has(path)) return false;\n\tif (\n\t\t[\n\t\t\t\"enabled\",\n\t\t\t\"startup.showResources\",\n\t\t\t\"statusLine.enabled\",\n\t\t\t\"editor.enabled\",\n\t\t\t\"editor.showMetadata\",\n\t\t\t\"messages.enabled\",\n\t\t\t\"messages.assistantPrefix\",\n\t\t\t\"messages.specialBlocks\",\n\t\t\t\"messages.hideThinkingLabel\",\n\t\t\t\"tools.enabled\",\n\t\t\t\"tools.showElapsed\",\n\t\t\t\"tools.dimOutput\",\n\t\t\t\"compatibility.allowSafePatches\",\n\t\t\t\"compatibility.allowCorePatches\",\n\t\t\t\"compatibility.preferExistingEditor\",\n\t\t\t\"compatibility.preferExistingFooter\",\n\t\t\t\"debug\",\n\t\t].includes(path)\n\t)\n\t\treturn typeof value === \"boolean\";\n\tif (path === \"preset\") return typeof value === \"string\" && presets.includes(value);\n\tif (path === \"placement\") return value === \"above\" || value === \"below\";\n\tif (path === \"startup.mode\") return typeof value === \"string\" && startupModes.includes(value);\n\tif (path === \"editor.style\") return typeof value === \"string\" && styles.includes(value);\n\tif (path === \"editor.frame\") return typeof value === \"string\" && frames.includes(value);\n\tif (path === \"theme.autoApply\") return typeof value === \"string\" && value !== \"\";\n\tif ([\"theme.nerdFonts\", \"theme.terminalBackgroundSync\", \"statusLine.separator\", \"tools.style\"].includes(path))\n\t\treturn typeof value === \"string\";\n\tif (path === \"tools.maxCollapsedLines\" || path === \"tools.maxExpandedLines\")\n\t\treturn typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\tif (path === \"statusLine.bottomMargin\" || path === \"statusLine.contextBarWidth\")\n\t\treturn typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\tif (path.endsWith(\".colors\") || path.endsWith(\".glyphs\"))\n\t\treturn (\n\t\t\ttypeof value === \"object\" &&\n\t\t\tvalue !== null &&\n\t\t\t!Array.isArray(value) &&\n\t\t\tObject.values(value).every((item) => typeof item === \"string\")\n\t\t);\n\tif (path.includes(\"layout.\") || path === \"statusLine.disabledSegments\")\n\t\treturn Array.isArray(value) && value.every((item) => typeof item === \"string\");\n\treturn (\n\t\tpath === \"statusLine.customItems\" &&\n\t\tvalidateConfigLayer({ statusLine: { customItems: value } }).diagnostics.length === 0\n\t);\n}\nfunction validateMutation(patch: Mutation, prefix = \"\"): boolean {\n\treturn Object.entries(patch).every(([key, value]) => {\n\t\tconst path = prefix ? `${prefix}.${key}` : key;\n\t\tif (\n\t\t\t[\n\t\t\t\t\"theme.colors\",\n\t\t\t\t\"theme.glyphs\",\n\t\t\t\t\"statusLine.layout.left\",\n\t\t\t\t\"statusLine.layout.right\",\n\t\t\t\t\"statusLine.layout.secondary\",\n\t\t\t\t\"statusLine.disabledSegments\",\n\t\t\t\t\"statusLine.customItems\",\n\t\t\t].includes(path)\n\t\t)\n\t\t\treturn validatePathValue(path, value);\n\t\tif (typeof value === \"object\" && value !== null && !Array.isArray(value))\n\t\t\treturn Object.keys(value).length > 0 && validateMutation(value as Mutation, path);\n\t\treturn validatePathValue(path, value);\n\t});\n}\nfunction sanitizeMutation(patch: Mutation): Mutation | undefined {\n\treturn validateMutation(patch) ? patch : undefined;\n}\n\nfunction mutation(parts: readonly string[]): Mutation | undefined {\n\tif (parts[0] === \"set\" && parts[1] && parts[2]) {\n\t\ttry {\n\t\t\tconst value = JSON.parse(parts.slice(2).join(\" \")) as unknown;\n\t\t\tconst patch: Mutation = {};\n\t\t\tlet cursor = patch;\n\t\t\tconst keys = parts[1].split(\".\");\n\t\t\tfor (const key of keys.slice(0, -1)) {\n\t\t\t\tconst next = cursor[key];\n\t\t\t\tif (typeof next === \"object\" && next !== null && !Array.isArray(next)) cursor = next as Mutation;\n\t\t\t\telse {\n\t\t\t\t\tcursor[key] = {};\n\t\t\t\t\tcursor = cursor[key] as Mutation;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcursor[keys.at(-1) as string] = value;\n\t\t\treturn sanitizeMutation(patch);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\tconst [action, value, extra] = parts;\n\tif (action === \"on\" || action === \"off\") return { enabled: action === \"on\" };\n\tif (action === \"preset\" && value && presets.includes(value)) return { preset: value };\n\tif (action === \"placement\" && (value === \"above\" || value === \"below\")) return { placement: value };\n\tif (action === \"editor\" && value && styles.includes(value) && (!extra || frames.includes(extra)))\n\t\treturn { editor: { style: value, ...(extra ? { frame: extra } : {}) } };\n\tif (action === \"startup\" && value && startupModes.includes(value)) return { startup: { mode: value } };\n\tif (action === \"surface\" && value && surfaces.has(value) && (extra === \"on\" || extra === \"off\")) {\n\t\tif (value === \"startup\") return { startup: { mode: extra === \"on\" ? \"compact\" : \"off\" } };\n\t\treturn { [value === \"status\" ? \"statusLine\" : value]: { enabled: extra === \"on\" } };\n\t}\n\treturn undefined;\n}\n\nexport async function executePiStyleCommand(\n\targs: string,\n\thost: CommandHost,\n\tapp: CommandApp,\n\tstorage: { readonly port: ConfigFilePort; readonly paths: ConfigStoragePaths },\n): Promise<void> {\n\tconst parts = args.trim().split(/\\s+/).filter(Boolean);\n\tconst [action, scope, ...rest] = parts;\n\tif (!action) {\n\t\thost.ui.notify(\n\t\t\t`pi-style preset ${app.config.preset}; status ${app.config.statusLine.enabled ? \"on\" : \"off\"}`,\n\t\t\t\"info\",\n\t\t);\n\t\treturn;\n\t}\n\tif (action === \"reload\") {\n\t\tawait app.reload();\n\t\treturn;\n\t}\n\tif (action === \"doctor\") {\n\t\thost.ui.notify(JSON.stringify(app.doctor()), \"info\");\n\t\treturn;\n\t}\n\tif (action === \"persist\") {\n\t\tif (scope !== \"global\" && scope !== \"project\") {\n\t\t\thost.ui.notify(\"persistence requires explicit global or project scope\", \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tif (scope === \"project\" && !host.isProjectTrusted()) {\n\t\t\thost.ui.notify(\"pi-style project persistence requires a trusted project\", \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tconst patch = mutation(rest);\n\t\tif (!patch) {\n\t\t\thost.ui.notify(\"invalid pi-style mutation or value\", \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tconst sanitized = sanitizeMutation(patch);\n\t\tif (!sanitized) {\n\t\t\thost.ui.notify(\"mutation contains fields that cannot be persisted\", \"warning\");\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tawait writeScopedConfig(\n\t\t\t\tstorage.port,\n\t\t\t\tscope === \"global\" ? storage.paths.globalPath : storage.paths.projectPath,\n\t\t\t\tsanitized,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\thost.ui.notify(\n\t\t\t\t`pi-style settings write failed: ${error instanceof Error ? error.message : \"unknown error\"}`,\n\t\t\t\t\"error\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tapp.applySession(patch);\n\t\tif (\n\t\t\t(patch.messages as Record<string, unknown> | undefined)?.enabled === true ||\n\t\t\t(patch.tools as Record<string, unknown> | undefined)?.enabled === true\n\t\t)\n\t\t\thost.ui.notify(\"desired Tier C state stored; awaiting session authorization\", \"info\");\n\t\treturn;\n\t}\n\tconst patch = mutation(parts);\n\tif (patch) app.applySession(patch);\n\telse if (action === \"preset\" && !scope) {\n\t\tconst selected = await host.ui.select(\"pi-style preset\", presets);\n\t\tif (selected) app.applySession({ preset: selected });\n\t} else host.ui.notify(\"invalid pi-style command or value\", \"warning\");\n}\n","import type { CommandApp, CommandHost } from \"./command-service.js\";\nimport { executePiStyleCommand } from \"./command-service.js\";\nimport type { ConfigFilePort, ConfigStoragePaths } from \"./config-storage.js\";\n\nexport function runCommand(\n\targs: string,\n\thost: CommandHost,\n\tapp: CommandApp,\n\tstorage: { readonly port: ConfigFilePort; readonly paths: ConfigStoragePaths },\n): Promise<void> {\n\treturn executePiStyleCommand(args, host, app, storage);\n}\n","import { mkdir, readFile, rename, unlink, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"@earendil-works/pi-coding-agent\";\nimport type { ConfigFilePort, ConfigStoragePaths } from \"../app/config-storage.js\";\n\nconst locks = new Map<string, Promise<void>>();\n\nfunction serialize(path: string, operation: () => Promise<void>): Promise<void> {\n\tconst previous = locks.get(path) ?? Promise.resolve();\n\tconst current = previous.catch(() => undefined).then(operation);\n\tlocks.set(path, current);\n\treturn current.finally(() => {\n\t\tif (locks.get(path) === current) locks.delete(path);\n\t});\n}\n\nexport interface ConfigHostFs {\n\treadonly mkdir?: typeof mkdir;\n\treadonly readFile?: typeof readFile;\n\treadonly rename?: typeof rename;\n\treadonly unlink?: typeof unlink;\n\treadonly writeFile?: typeof writeFile;\n}\n\nexport function createPiConfigFilePort(fs: ConfigHostFs = {}): ConfigFilePort {\n\tconst fsMkdir = fs.mkdir ?? mkdir;\n\tconst fsReadFile = fs.readFile ?? readFile;\n\tconst fsRename = fs.rename ?? rename;\n\tconst fsUnlink = fs.unlink ?? unlink;\n\tconst fsWriteFile = fs.writeFile ?? writeFile;\n\treturn {\n\t\tread: (path) => fsReadFile(path, \"utf8\"),\n\t\twriteAtomic: async (path, content) =>\n\t\t\tserialize(path, async () => {\n\t\t\t\tawait fsMkdir(dirname(path), { recursive: true });\n\t\t\t\tconst temporary = `${path}.pi-style-${process.pid}-${Date.now()}.tmp`;\n\t\t\t\ttry {\n\t\t\t\t\tawait fsWriteFile(temporary, content, { mode: 0o600 });\n\t\t\t\t\tawait fsRename(temporary, path);\n\t\t\t\t} finally {\n\t\t\t\t\tawait fsUnlink(temporary).catch(() => undefined);\n\t\t\t\t}\n\t\t\t}),\n\t};\n}\n\nexport function defaultStoragePaths(cwd: string, overrides: Partial<ConfigStoragePaths> = {}): ConfigStoragePaths {\n\treturn {\n\t\tglobalPath: overrides.globalPath ?? join(getAgentDir(), \"settings.json\"),\n\t\tprojectPath: overrides.projectPath ?? join(cwd, CONFIG_DIR_NAME, \"settings.json\"),\n\t};\n}\n","import type { ExtensionAPI, ExtensionCommandContext } from \"@earendil-works/pi-coding-agent\";\nimport type { CommandApp } from \"../app/command-service.js\";\nimport { runCommand } from \"../app/commands.js\";\nimport { createPiConfigFilePort, defaultStoragePaths } from \"./config-host.js\";\n\nexport function registerPiStyleCommand(pi: ExtensionAPI, app: CommandApp): void {\n\tpi.registerCommand(\"pi-style\", {\n\t\tdescription: \"Configure pi-style for this session\",\n\t\thandler: async (args: string, ctx: ExtensionCommandContext) => {\n\t\t\tconst cwd = ctx.cwd ?? process.cwd();\n\t\t\tawait runCommand(args, { ui: ctx.ui, cwd, isProjectTrusted: ctx.isProjectTrusted }, app, {\n\t\t\t\tport: createPiConfigFilePort(),\n\t\t\t\tpaths: defaultStoragePaths(cwd),\n\t\t\t});\n\t\t},\n\t});\n}\n","import type { ExtensionAPI, ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { type KeyId, matchesKey } from \"@earendil-works/pi-tui\";\nimport type { ConfigFilePort } from \"../app/config-storage.js\";\nimport { createPiStyleApp, type PiStyleApp } from \"../app/index.js\";\nimport { resolveTheme } from \"../domain/theme.js\";\nimport { setSpecialBlockTheme } from \"../features/messages/special-blocks.js\";\nimport { setBashExecutionTheme } from \"../features/tools/bash-execution.js\";\nimport { resetBashTreeRegistry } from \"../features/tools/boxed/bash.js\";\nimport { resetBatchRegistry } from \"../features/tools/boxed/batch.js\";\nimport { resetGrepRegistry } from \"../features/tools/boxed/grep.js\";\nimport {\n\tsetToolsRenderConfig,\n\tstopAllElapsedTickers,\n\ttype ToolsRenderConfig,\n} from \"../features/tools/boxed/session-config.js\";\nimport { createCompatibilityCoordinator } from \"./compatibility-coordinator.js\";\nimport {\n\ttype CompatibilityCleanupResult,\n\ttype CompatibilityProbeReport,\n\tdisposePiCompatibilityProbe,\n} from \"./compatibility-probe.js\";\nimport { createPiConfigFilePort, defaultStoragePaths } from \"./config-host.js\";\nimport { createConfigSourceAdapter, readSessionAuthorization } from \"./config-session.js\";\nimport { buildOperationalState } from \"./operational-state.js\";\nimport { collectToolDetails } from \"./startup-resources.js\";\n\nexport type CompatibilityTestHooks = {\n\tdispose?: (report: CompatibilityProbeReport) => CompatibilityCleanupResult;\n\tfilePort?: ConfigFilePort;\n\tpaths?: (cwd: string) => { globalPath: string; projectPath: string };\n\t/** Test-only capability seam; Pi's ExtensionContext does not provide a Git runner. */\n\tgitRunner?: import(\"../domain/providers.js\").GitCommandRunner;\n\t/** Override the thinking-cycle key binding consumed to suppress Pi's status toast. */\n\tthinkingCycleKey?: string;\n};\n\nconst THINKING_CYCLE = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\n\nexport function createPiStyleSessionCoordinator(pi: ExtensionAPI, hooks: CompatibilityTestHooks = {}) {\n\tconst filePort = hooks.filePort ?? createPiConfigFilePort();\n\tconst gitRunner =\n\t\thooks.gitRunner ??\n\t\t({\n\t\t\trun: async (args, commandCwd, timeoutMs, signal) => {\n\t\t\t\tconst result = await pi.exec(\"git\", [...args], {\n\t\t\t\t\tcwd: commandCwd,\n\t\t\t\t\ttimeout: timeoutMs,\n\t\t\t\t\t...(signal ? { signal } : {}),\n\t\t\t\t});\n\t\t\t\treturn { stdout: result.stdout, stderr: result.stderr, code: result.code };\n\t\t\t},\n\t\t} satisfies import(\"../domain/providers.js\").GitCommandRunner);\n\tlet cwd = process.cwd();\n\tlet active = false;\n\tlet tuiSession = false;\n\tlet terminalInputUnsubscribe: (() => void) | undefined;\n\tlet sessionTheme: unknown;\n\tlet sessionUi: import(\"@earendil-works/pi-coding-agent\").ExtensionUIContext | undefined;\n\tconst source = createConfigSourceAdapter(\n\t\tpi,\n\t\tfilePort,\n\t\thooks.paths ?? ((sessionCwd) => defaultStoragePaths(sessionCwd)),\n\t);\n\tconst compatibility = createCompatibilityCoordinator(\n\t\t(report) => hooks.dispose?.(report) ?? disposePiCompatibilityProbe(report),\n\t);\n\t// Initial read may be empty in real Pi (flag values apply after extension load);\n\t// start() re-reads and re-captures at every session_start.\n\tlet authorization = readSessionAuthorization(pi);\n\tlet productGate: \"omitted\" | \"allow\" | \"deny\" = \"omitted\";\n\tconst syncOperational = (config: import(\"../domain/config-types.js\").NormalizedPiStyleConfig) => {\n\t\tapp.setOperationalState(\n\t\t\tbuildOperationalState(\n\t\t\t\tconfig,\n\t\t\t\tauthorization,\n\t\t\t\tcompatibility,\n\t\t\t\tapp.runtime.current?.installationState,\n\t\t\t\tapp.productPolicy.corePatchGate,\n\t\t\t),\n\t\t);\n\t};\n\t/** Render-scoped tool config: line budgets + the resolved open-tree glyph. */\n\tconst applyToolsRenderConfig = (config: import(\"../domain/config-types.js\").NormalizedPiStyleConfig) => {\n\t\tsetToolsRenderConfig({\n\t\t\t...config.tools,\n\t\t\tbatchOpenGlyph: resolveTheme(sessionTheme as never, config, process.env).glyph(\"batchOpen\"),\n\t\t\tnerdFonts: resolveTheme(sessionTheme as never, config, process.env).mode === \"nerd\",\n\t\t} satisfies ToolsRenderConfig);\n\t};\n\t/**\n\t * Hide Pi's \"Thinking...\" placeholder label: an empty label renders zero\n\t * lines, so the thinking block leaves no trace while content stays hidden.\n\t * Passing undefined restores the default label.\n\t */\n\tconst applyMessagesConfig = (config: import(\"../domain/config-types.js\").NormalizedPiStyleConfig) => {\n\t\tsessionUi?.setHiddenThinkingLabel?.(config.messages.hideThinkingLabel ? \"\" : undefined);\n\t};\n\t/**\n\t * Auto-apply the configured pi-style theme (default \"titanium\") once per TUI\n\t * session before any surface captures the active theme, so a fresh install\n\t * renders with the intended palette. Failure-safe: an unresolvable target is\n\t * never passed to Pi (its setTheme falls back to the dark theme on load\n\t * error, which would clobber the user's theme), and \"off\" disables the\n\t * surface for users who keep their own theme.\n\t */\n\tconst applyAutoTheme = (\n\t\tconfig: import(\"../domain/config-types.js\").NormalizedPiStyleConfig,\n\t\tctx: ExtensionContext,\n\t) => {\n\t\tconst target = config.theme.autoApply;\n\t\tif (ctx.mode !== \"tui\" || !target || target === \"off\") return;\n\t\tconst ui = ctx.ui;\n\t\tif (ui?.theme?.name === target) return;\n\t\t// Resolve before switching (see failure-safe note above).\n\t\tif (!ui?.getTheme?.(target)) return;\n\t\tui.setTheme?.(target);\n\t};\n\tconst app: PiStyleApp = createPiStyleApp(\n\t\tundefined,\n\t\t{\n\t\t\tload: async (trusted) => {\n\t\t\t\tsource.setSession(cwd, trusted);\n\t\t\t\treturn source.load();\n\t\t\t},\n\t\t},\n\t\t(config) => {\n\t\t\tproductGate = app.productPolicy.corePatchGate;\n\t\t\tif (!active) return;\n\t\t\t// Apply render-scoped tool config live so `/pi-style set tools.*` takes\n\t\t\t// effect immediately (line budgets, dimOutput, open-tree glyph, …).\n\t\t\tapplyToolsRenderConfig(config);\n\t\t\tapplyMessagesConfig(config);\n\t\t\tif (compatibility.report) {\n\t\t\t\tconst cleanup = compatibility.dispose();\n\t\t\t\tif (!cleanup.complete) {\n\t\t\t\t\tsyncOperational(config);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcompatibility.install(config, tuiSession, productGate);\n\t\t\tsyncOperational(config);\n\t\t},\n\t);\n\n\treturn {\n\t\tapp,\n\t\tasync start(event: { reason: string }, ctx: ExtensionContext): Promise<void> {\n\t\t\t// Authorization is session-bound: Pi applies extension flag values only after\n\t\t\t// extension modules finish loading, so flags must be read here (session_start),\n\t\t\t// never at coordinator creation time.\n\t\t\tauthorization = readSessionAuthorization(pi);\n\t\t\tcompatibility.captureAuthorization(\n\t\t\t\tauthorization.core,\n\t\t\t\tauthorization.assistant,\n\t\t\t\tauthorization.specialBlocks,\n\t\t\t\tauthorization.tools,\n\t\t\t\tauthorization.ascii,\n\t\t\t);\n\t\t\t// Replacement is failure-atomic: retain the current runtime until\n\t\t\t// compatibility ownership has been restored successfully.\n\t\t\tif (compatibility.report) {\n\t\t\t\tconst cleanup = compatibility.dispose();\n\t\t\t\tif (!cleanup.complete) {\n\t\t\t\t\tsyncOperational(app.config);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (app.runtime.current) app.sessionShutdown();\n\t\t\tcwd = ctx.cwd ?? process.cwd();\n\t\t\ttuiSession = ctx.mode === \"tui\";\n\t\t\tapp.setProjectTrusted(ctx.isProjectTrusted());\n\t\t\tsource.setSession(cwd, ctx.isProjectTrusted());\n\t\t\t// Drop any batch state carried over from the previous session (Pi renders\n\t\t\t// the restored chat between session_shutdown and the next session_start).\n\t\t\tresetBatchRegistry();\n\t\t\tresetGrepRegistry();\n\t\t\tresetBashTreeRegistry();\n\t\t\t// Stop any 1s elapsed re-render ticker left by a tool that was still\n\t\t\t// running when the session ended.\n\t\t\tstopAllElapsedTickers();\n\t\t\tactive = false;\n\t\t\tawait app.reload();\n\t\t\tproductGate = app.productPolicy.corePatchGate;\n\t\t\tactive = true;\n\t\t\tcompatibility.install(app.config, ctx.mode === \"tui\", productGate);\n\t\t\t// Auto-apply the configured theme before surfaces capture the active one.\n\t\t\tapplyAutoTheme(app.config, ctx);\n\t\t\t// Session-scoped render configuration for the boxed tool/message surfaces.\n\t\t\t// Populated once per session (never inside render).\n\t\t\tsessionTheme = ctx.ui?.theme as never;\n\t\t\tsessionUi = ctx.ui as import(\"@earendil-works/pi-coding-agent\").ExtensionUIContext | undefined;\n\t\t\tapplyToolsRenderConfig(app.config);\n\t\t\tapplyMessagesConfig(app.config);\n\t\t\tif (ctx.ui?.theme) setSpecialBlockTheme(ctx.ui.theme as never);\n\t\t\tif (ctx.ui?.theme) setBashExecutionTheme(ctx.ui.theme as never);\n\t\t\tconst toolDetails = collectToolDetails(pi.getActiveTools?.(), pi.getAllTools?.());\n\t\t\tapp.sessionStart(\n\t\t\t\t{\n\t\t\t\t\tmode: ctx.mode,\n\t\t\t\t\thasUI: ctx.hasUI,\n\t\t\t\t\t...(ctx.ui ? { ui: ctx.ui } : {}),\n\t\t\t\t\t...(ctx.cwd ? { cwd: ctx.cwd } : {}),\n\t\t\t\t\t...(ctx.model\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tmodel: {\n\t\t\t\t\t\t\t\t\tid: ctx.model.id,\n\t\t\t\t\t\t\t\t\tname: ctx.model.name,\n\t\t\t\t\t\t\t\t\tprovider: ctx.model.provider,\n\t\t\t\t\t\t\t\t\treasoning: ctx.model.reasoning,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(ctx.thinkingLevel ? { thinkingLevel: ctx.thinkingLevel } : {}),\n\t\t\t\t\tgetContextUsage: ctx.getContextUsage,\n\t\t\t\t\tprojectTrusted: ctx.isProjectTrusted(),\n\t\t\t\t\tgitRunner,\n\t\t\t\t},\n\t\t\t\tevent.reason as \"startup\" | \"reload\" | \"new\" | \"resume\" | \"fork\",\n\t\t\t\t{\n\t\t\t\t\t...(typeof ctx.getSystemPrompt === \"function\" ? { systemPrompt: ctx.getSystemPrompt() } : {}),\n\t\t\t\t\t...(toolDetails ? { toolDetails } : {}),\n\t\t\t\t\t...(ctx.scopedModels && ctx.scopedModels.length > 0 ? { models: ctx.scopedModels.length } : {}),\n\t\t\t\t},\n\t\t\t);\n\t\t\tterminalInputUnsubscribe?.();\n\t\t\tterminalInputUnsubscribe = undefined;\n\t\t\t// Consume Pi's default thinking-cycle key and re-issue it through the public API so\n\t\t\t// the footer shows the level without Pi's transient \"Thinking level: X\" status toast.\n\t\t\tconst cycleKey = hooks.thinkingCycleKey ?? \"shift+tab\";\n\t\t\tif (ctx.mode === \"tui\" && ctx.ui?.onTerminalInput) {\n\t\t\t\tterminalInputUnsubscribe = ctx.ui.onTerminalInput((data) => {\n\t\t\t\t\tif (!matchesKey(data, cycleKey as KeyId)) return undefined;\n\t\t\t\t\tconst current = pi.getThinkingLevel?.();\n\t\t\t\t\tconst index = Math.max(0, THINKING_CYCLE.indexOf(current as (typeof THINKING_CYCLE)[number]));\n\t\t\t\t\tconst next = THINKING_CYCLE[(index + 1) % THINKING_CYCLE.length];\n\t\t\t\t\tpi.setThinkingLevel?.(next as never);\n\t\t\t\t\treturn { consume: true };\n\t\t\t\t});\n\t\t\t}\n\t\t\tsyncOperational(app.config);\n\t\t},\n\t\tshutdown(): void {\n\t\t\tactive = false;\n\t\t\ttuiSession = false;\n\t\t\tterminalInputUnsubscribe?.();\n\t\t\tterminalInputUnsubscribe = undefined;\n\t\t\tresetBatchRegistry();\n\t\t\tresetGrepRegistry();\n\t\t\tresetBashTreeRegistry();\n\t\t\tstopAllElapsedTickers();\n\t\t\tapp.sessionShutdown();\n\t\t\t// Tier C prototype patches stay installed across session switches. Pi renders\n\t\t\t// the restored chat (renderBeforeBind) AFTER session_shutdown but BEFORE the\n\t\t\t// next session_start, so disposing here would rebuild the resumed tool and\n\t\t\t// special-block surfaces with native prototypes and they would never be\n\t\t\t// re-decorated (their boxed output is derived once at updateDisplay time and\n\t\t\t// cached; a later frame render does not re-invoke the renderer selectors).\n\t\t\t// The next start() disposes this report (restoring the native identities)\n\t\t\t// and reinstalls before any new render. On process exit (reason \"quit\") the\n\t\t\t// terminal is torn down immediately after, so retained patches are harmless.\n\t\t},\n\t};\n}\n","import type { ConfigDiagnostic } from \"../domain/config-diagnostics.js\";\nimport type { NormalizedPiStyleConfig } from \"../domain/config-types.js\";\n\nexport interface DoctorOperationalState {\n\treadonly compatibility?: Readonly<Record<string, unknown>>;\n\treadonly provider?: Readonly<Record<string, unknown>>;\n\treadonly installations?: Readonly<Record<string, unknown>>;\n\treadonly authorization?: Readonly<Record<string, unknown>>;\n}\n\nexport interface DoctorState {\n\treadonly config: NormalizedPiStyleConfig;\n\treadonly diagnostics: readonly ConfigDiagnostic[];\n\treadonly sources?: Readonly<Record<string, string>>;\n\treadonly surfaces: Readonly<Record<string, unknown>>;\n\treadonly piVersion?: string;\n\treadonly compatibility?: string;\n\treadonly operational?: DoctorOperationalState;\n}\n\nexport function createDoctor(state: DoctorState): Readonly<Record<string, unknown>> {\n\treturn Object.freeze({\n\t\tconfig: Object.freeze({\n\t\t\tpreset: state.config.preset,\n\t\t\tenabled: state.config.enabled,\n\t\t\tplacement: state.config.placement,\n\t\t\tstatusLine: state.config.statusLine.enabled ? \"enabled\" : \"disabled\",\n\t\t\teditor: state.config.editor.enabled ? \"enabled\" : \"disabled\",\n\t\t\tstartup: state.config.startup.mode,\n\t\t}),\n\t\tdiagnostics: state.diagnostics,\n\t\tsources: state.sources ?? {},\n\t\tsurfaces: state.surfaces,\n\t\t...(state.piVersion ? { piVersion: state.piVersion } : {}),\n\t\t...(state.operational?.compatibility && typeof state.operational.compatibility.piVersion === \"string\"\n\t\t\t? { piVersion: state.operational.compatibility.piVersion }\n\t\t\t: {}),\n\t\t...(state.operational?.compatibility && typeof state.operational.compatibility.versionRange === \"string\"\n\t\t\t? { piVersionRange: state.operational.compatibility.versionRange }\n\t\t\t: {}),\n\t\t...(state.compatibility ? { compatibility: state.compatibility } : {}),\n\t\t...(state.operational\n\t\t\t? {\n\t\t\t\t\toperational: Object.freeze({\n\t\t\t\t\t\t...(state.operational.compatibility ? { compatibility: state.operational.compatibility } : {}),\n\t\t\t\t\t\t...(state.operational.provider ? { provider: state.operational.provider } : {}),\n\t\t\t\t\t\t...(state.operational.installations ? { installations: state.operational.installations } : {}),\n\t\t\t\t\t\t...(state.operational.authorization ? { authorization: state.operational.authorization } : {}),\n\t\t\t\t\t}),\n\t\t\t\t}\n\t\t\t: {}),\n\t});\n}\n","import type { NormalizedPiStyleConfig } from \"./config-types.js\";\n\nexport type ConfigImpact = \"none\" | \"status\" | \"editor\" | \"startup\" | \"compatibility\" | \"all\";\n\nexport interface ConfigDiff {\n\treadonly changed: readonly string[];\n\treadonly impacts: readonly ConfigImpact[];\n}\n\nexport function diffConfig(previous: NormalizedPiStyleConfig, next: NormalizedPiStyleConfig): ConfigDiff {\n\tconst changed: string[] = [];\n\tconst impacts = new Set<ConfigImpact>();\n\tconst compare = (key: string, before: unknown, after: unknown, impact: ConfigImpact) => {\n\t\tif (JSON.stringify(before) === JSON.stringify(after)) return;\n\t\tchanged.push(key);\n\t\timpacts.add(impact);\n\t};\n\tcompare(\"enabled\", previous.enabled, next.enabled, \"all\");\n\tcompare(\"statusLine\", previous.statusLine, next.statusLine, \"status\");\n\tcompare(\"placement\", previous.placement, next.placement, \"status\");\n\tcompare(\"editor\", previous.editor, next.editor, \"editor\");\n\tcompare(\"startup\", previous.startup, next.startup, \"startup\");\n\tcompare(\"messages\", previous.messages, next.messages, \"compatibility\");\n\tcompare(\"tools\", previous.tools, next.tools, \"compatibility\");\n\tcompare(\"theme\", previous.theme, next.theme, \"all\");\n\tcompare(\"compatibility\", previous.compatibility, next.compatibility, \"compatibility\");\n\tif (impacts.has(\"all\"))\n\t\treturn Object.freeze({ changed: Object.freeze(changed), impacts: Object.freeze([\"all\"] as const) });\n\treturn Object.freeze({ changed: Object.freeze(changed), impacts: Object.freeze([...impacts]) });\n}\n","import type { ResolvedTheme, SemanticToken } from \"./theme.js\";\n\nexport const STATUS_SEGMENT_IDS = [\n\t\"pi\",\n\t\"model\",\n\t\"thinking\",\n\t\"model_effort\",\n\t\"path\",\n\t\"git\",\n\t\"context_pct\",\n\t\"context_bar\",\n\t\"context_total\",\n\t\"auto_compact\",\n\t\"token_in\",\n\t\"token_out\",\n\t\"cache_read\",\n\t\"cache_write\",\n\t\"cost\",\n\t\"time_spent\",\n\t\"time\",\n\t\"hostname\",\n\t\"session\",\n\t\"extension_statuses\",\n] as const;\nexport type StatusSegmentId = (typeof STATUS_SEGMENT_IDS)[number] | (string & {});\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\nexport type ContextState = \"low\" | \"medium\" | \"high\" | \"critical\";\n\nexport interface GitSnapshot {\n\treadonly available: boolean;\n\treadonly branch: string | null;\n\treadonly staged: number;\n\treadonly unstaged: number;\n\treadonly untracked: number;\n\treadonly ahead?: number;\n\treadonly behind?: number;\n\treadonly refreshing: boolean;\n\treadonly error?: string;\n}\n\nexport interface ContextSnapshot {\n\treadonly currentTokens?: number;\n\treadonly windowTokens?: number;\n\treadonly percent?: number;\n\treadonly state?: ContextState;\n\treadonly autoCompacting?: boolean;\n\treadonly customCompaction?: string;\n}\n\nexport interface UsageSnapshot {\n\treadonly inputTokens: number;\n\treadonly outputTokens: number;\n\treadonly cacheReadTokens: number;\n\treadonly cacheWriteTokens: number;\n\treadonly cost?: number;\n\treadonly currency?: string;\n\treadonly subscriptionMode?: \"api\" | \"subscription\" | \"unknown\";\n\treadonly streaming: boolean;\n}\n\nexport interface ExtensionStatus {\n\treadonly key: string;\n\treadonly value: string;\n}\n\nexport interface StatusSnapshot {\n\treadonly model?: string;\n\t/** Provider name for the active model (e.g. `deepseek`), when known. */\n\treadonly provider?: string;\n\t/** Whether the active model supports reasoning/thinking levels, when known. */\n\treadonly reasoning?: boolean;\n\treadonly thinkingLevel?: ThinkingLevel;\n\treadonly cwd?: string;\n\treadonly git?: GitSnapshot;\n\treadonly context?: ContextSnapshot;\n\treadonly usage?: UsageSnapshot;\n\treadonly hostname?: string;\n\treadonly sessionName?: string | undefined;\n\treadonly sessionId?: string | undefined;\n\treadonly sessionStartedAt?: number;\n\treadonly extensionStatuses?: readonly ExtensionStatus[];\n}\n\nexport interface StatusSegmentOptions {\n\treadonly disabled?: boolean;\n\treadonly label?: string;\n\treadonly [key: string]: unknown;\n}\n\nexport interface StatusCustomItem {\n\treadonly id: string;\n\treadonly statusKey: string;\n\treadonly label?: string;\n\treadonly priority?: number;\n\treadonly placement?: \"left\" | \"right\" | \"secondary\";\n}\n\nexport interface SegmentContext {\n\treadonly snapshot: StatusSnapshot;\n\treadonly theme: ResolvedTheme;\n\treadonly options: Readonly<Record<string, StatusSegmentOptions | undefined>>;\n\treadonly width: number;\n}\n\nexport interface SegmentRenderResult {\n\treadonly visible: boolean;\n\treadonly content: string;\n\treadonly compactContent?: string;\n\treadonly minWidth?: number;\n\treadonly truncatable?: boolean;\n}\n\nexport interface StatusSegment {\n\treadonly id: StatusSegmentId;\n\treadonly defaultPriority: number;\n\treadonly essential?: boolean;\n\treadonly overflow?: \"primary\" | \"secondary\" | \"drop\";\n\trender(context: SegmentContext): SegmentRenderResult;\n}\n\nexport interface StatusLayout {\n\treadonly left: readonly StatusSegmentId[];\n\treadonly right: readonly StatusSegmentId[];\n\treadonly secondary: readonly StatusSegmentId[];\n}\n\nexport interface StatusRenderResult {\n\treadonly primary: string;\n\treadonly secondary?: string;\n\treadonly lines: readonly string[];\n\treadonly visibleSegments: readonly StatusSegmentId[];\n}\n\nfunction segment(\n\tid: StatusSegmentId,\n\tpriority: number,\n\trender: StatusSegment[\"render\"],\n\tessential = false,\n): StatusSegment {\n\treturn { id, defaultPriority: priority, essential, overflow: essential ? \"primary\" : \"secondary\", render };\n}\n\nexport function createBuiltinSegments(): ReadonlyMap<StatusSegmentId, StatusSegment> {\n\tconst segments: StatusSegment[] = [\n\t\tsegment(\"pi\", 10, ({ theme }) => ({\n\t\t\tvisible: true,\n\t\t\tcontent: theme.apply(\"accent\", `${theme.glyph(\"pi\")} pi`),\n\t\t\tcompactContent: theme.apply(\"accent\", theme.glyph(\"pi\")),\n\t\t})),\n\t\tsegment(\n\t\t\t\"model\",\n\t\t\t100,\n\t\t\t({ snapshot, theme }) => ({\n\t\t\t\tvisible: Boolean(snapshot.model),\n\t\t\t\tcontent: theme.apply(\"model\", snapshot.model ?? \"\"),\n\t\t\t\tcompactContent: theme.apply(\"model\", snapshot.model ?? \"\"),\n\t\t\t\ttruncatable: true,\n\t\t\t}),\n\t\t\ttrue,\n\t\t),\n\t\tsegment(\n\t\t\t\"model_effort\",\n\t\t\t40,\n\t\t\t({ snapshot, theme }) => {\n\t\t\t\tconst model = snapshot.model;\n\t\t\t\tif (!model) return { visible: false, content: \"\" };\n\t\t\t\tconst label = snapshot.provider ? `(${snapshot.provider}) ${model}` : model;\n\t\t\t\tconst styledLabel = theme.apply(\"model\", label);\n\t\t\t\tconst effort = effortLevel(snapshot);\n\t\t\t\tif (!effort) {\n\t\t\t\t\treturn { visible: true, content: styledLabel, compactContent: theme.apply(\"model\", model) };\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tvisible: true,\n\t\t\t\t\tcontent: `${styledLabel} ${theme.apply(\"separator\", \"•\")} ${styleEffort(theme, effort)}`,\n\t\t\t\t\tcompactContent: theme.apply(\"model\", model),\n\t\t\t\t};\n\t\t\t},\n\t\t\tfalse,\n\t\t),\n\t\tsegment(\n\t\t\t\"thinking\",\n\t\t\t95,\n\t\t\t({ snapshot, theme }) => {\n\t\t\t\tconst level = snapshot.thinkingLevel;\n\t\t\t\tif (!level) return { visible: false, content: \"\" };\n\t\t\t\tconst label = thinkingLabel(level);\n\t\t\t\tconst text = `think:${label}`;\n\t\t\t\tconst compactText = `t:${label}`;\n\t\t\t\tif (level === \"high\" || level === \"xhigh\" || level === \"max\") {\n\t\t\t\t\treturn { visible: true, content: theme.rainbow(text), compactContent: theme.rainbow(compactText) };\n\t\t\t\t}\n\t\t\t\tconst token =\n\t\t\t\t\tlevel === \"minimal\"\n\t\t\t\t\t\t? \"thinkingMinimal\"\n\t\t\t\t\t\t: level === \"low\"\n\t\t\t\t\t\t\t? \"thinkingLow\"\n\t\t\t\t\t\t\t: level === \"medium\"\n\t\t\t\t\t\t\t\t? \"thinkingMedium\"\n\t\t\t\t\t\t\t\t: \"thinking\";\n\t\t\t\treturn {\n\t\t\t\t\tvisible: true,\n\t\t\t\t\tcontent: theme.apply(token, text),\n\t\t\t\t\tcompactContent: theme.apply(token, compactText),\n\t\t\t\t};\n\t\t\t},\n\t\t\ttrue,\n\t\t),\n\t\tsegment(\"path\", 80, ({ snapshot, theme }) => {\n\t\t\tconst name = snapshot.cwd?.split(/[\\\\/]/).filter(Boolean).at(-1) ?? snapshot.cwd;\n\t\t\treturn {\n\t\t\t\tvisible: Boolean(snapshot.cwd),\n\t\t\t\tcontent: theme.apply(\"path\", name ?? \"\"),\n\t\t\t\tcompactContent: theme.apply(\"path\", name ?? \"\"),\n\t\t\t\ttruncatable: true,\n\t\t\t};\n\t\t}),\n\t\tsegment(\"git\", 75, ({ snapshot, theme }) => {\n\t\t\tconst git = snapshot.git;\n\t\t\tif (!git?.available || !git.branch) return { visible: false, content: \"\" };\n\t\t\tconst counts = `${git.staged ? ` +${git.staged}` : \"\"}${git.unstaged ? ` *${git.unstaged}` : \"\"}${git.untracked ? ` ?${git.untracked}` : \"\"}`;\n\t\t\tconst token = git.staged || git.unstaged || git.untracked ? \"gitDirty\" : \"gitClean\";\n\t\t\treturn {\n\t\t\t\tvisible: true,\n\t\t\t\tcontent: theme.apply(token, `${theme.glyph(\"git\")} ${git.branch}${counts}`),\n\t\t\t\tcompactContent: theme.apply(token, `${theme.glyph(\"git\")} ${git.branch}`),\n\t\t\t};\n\t\t}),\n\t\tsegment(\n\t\t\t\"context_pct\",\n\t\t\t90,\n\t\t\t({ snapshot, theme }) => {\n\t\t\t\tconst percent = contextPercent(snapshot.context ?? {});\n\t\t\t\tconst state = contextState(percent);\n\t\t\t\tconst token =\n\t\t\t\t\tstate === \"critical\"\n\t\t\t\t\t\t? \"contextCritical\"\n\t\t\t\t\t\t: state === \"high\"\n\t\t\t\t\t\t\t? \"contextHigh\"\n\t\t\t\t\t\t\t: state === \"medium\"\n\t\t\t\t\t\t\t\t? \"contextMedium\"\n\t\t\t\t\t\t\t\t: \"contextLow\";\n\t\t\t\treturn {\n\t\t\t\t\tvisible: percent !== undefined,\n\t\t\t\t\tcontent: percent === undefined ? \"\" : theme.apply(token, `ctx:${Math.round(percent)}%`),\n\t\t\t\t\tcompactContent: percent === undefined ? \"\" : theme.apply(token, `${Math.round(percent)}%`),\n\t\t\t\t};\n\t\t\t},\n\t\t\ttrue,\n\t\t),\n\t\tsegment(\"context_bar\", 70, ({ snapshot, theme, options }) => {\n\t\t\tconst percent = contextPercent(snapshot.context ?? {});\n\t\t\tif (percent === undefined) return { visible: false, content: \"\" };\n\t\t\tconst token = contextBarToken(percent);\n\t\t\tconst window = snapshot.context?.windowTokens;\n\t\t\tconst label = `ctx${window !== undefined ? ` (${formatTokens(window)})` : \"\"}:`;\n\t\t\tconst width = (options.context_bar?.width as number | undefined) ?? CONTEXT_BAR_WIDTH;\n\t\t\treturn {\n\t\t\t\tvisible: true,\n\t\t\t\tcontent: `${theme.apply(\"muted\", label)} ${theme.apply(token, contextBar(percent, width))} ${theme.apply(token, `${Math.round(percent)}%`)}`,\n\t\t\t\tcompactContent: theme.apply(token, `${Math.round(percent)}%`),\n\t\t\t};\n\t\t}),\n\t\tsegment(\"context_total\", 60, ({ snapshot, theme }) => ({\n\t\t\tvisible: snapshot.context?.currentTokens !== undefined && snapshot.context.windowTokens !== undefined,\n\t\t\tcontent:\n\t\t\t\tsnapshot.context?.currentTokens !== undefined && snapshot.context.windowTokens !== undefined\n\t\t\t\t\t? theme.apply(\"contextLow\", `${snapshot.context.currentTokens}/${snapshot.context.windowTokens}`)\n\t\t\t\t\t: \"\",\n\t\t})),\n\t\tsegment(\"auto_compact\", 55, ({ snapshot, theme }) => ({\n\t\t\tvisible: Boolean(snapshot.context?.autoCompacting || snapshot.context?.customCompaction),\n\t\t\tcontent: theme.apply(\"warning\", snapshot.context?.customCompaction ?? \"compacting\"),\n\t\t\tcompactContent: theme.apply(\"warning\", \"compact\"),\n\t\t})),\n\t\tsegment(\"token_in\", 50, ({ snapshot, theme }) => ({\n\t\t\tvisible: snapshot.usage?.inputTokens !== undefined,\n\t\t\tcontent: theme.apply(\"tokens\", `in:${snapshot.usage?.inputTokens ?? 0}`),\n\t\t\tcompactContent: theme.apply(\"tokens\", `i:${snapshot.usage?.inputTokens ?? 0}`),\n\t\t})),\n\t\tsegment(\"token_out\", 50, ({ snapshot, theme }) => ({\n\t\t\tvisible: snapshot.usage?.outputTokens !== undefined,\n\t\t\tcontent: theme.apply(\"tokens\", `out:${snapshot.usage?.outputTokens ?? 0}`),\n\t\t\tcompactContent: theme.apply(\"tokens\", `o:${snapshot.usage?.outputTokens ?? 0}`),\n\t\t})),\n\t\tsegment(\"cache_read\", 40, ({ snapshot, theme }) => ({\n\t\t\tvisible: Boolean(snapshot.usage?.cacheReadTokens),\n\t\t\tcontent: theme.apply(\"cache\", `cache:${snapshot.usage?.cacheReadTokens ?? 0}`),\n\t\t\tcompactContent: theme.apply(\"cache\", `cr:${snapshot.usage?.cacheReadTokens ?? 0}`),\n\t\t})),\n\t\tsegment(\"cache_write\", 35, ({ snapshot, theme }) => ({\n\t\t\tvisible: Boolean(snapshot.usage?.cacheWriteTokens),\n\t\t\tcontent: theme.apply(\"cache\", `cw:${snapshot.usage?.cacheWriteTokens ?? 0}`),\n\t\t})),\n\t\tsegment(\"cost\", 65, ({ snapshot, theme }) => {\n\t\t\tconst cost = snapshot.usage?.cost;\n\t\t\tconst content = cost === undefined || cost <= 0 ? \"\" : theme.apply(\"cost\", `$${cost.toFixed(3)}`);\n\t\t\treturn { visible: Boolean(content), content, compactContent: content };\n\t\t}),\n\t\tsegment(\"time_spent\", 25, ({ snapshot, theme }) => ({\n\t\t\tvisible: snapshot.sessionStartedAt !== undefined,\n\t\t\tcontent:\n\t\t\t\tsnapshot.sessionStartedAt === undefined\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: theme.apply(\"time\", formatElapsed(Date.now() - snapshot.sessionStartedAt)),\n\t\t\tcompactContent:\n\t\t\t\tsnapshot.sessionStartedAt === undefined\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: theme.apply(\"time\", formatElapsed(Date.now() - snapshot.sessionStartedAt)),\n\t\t})),\n\t\tsegment(\"time\", 20, ({ theme }) => ({\n\t\t\tvisible: true,\n\t\t\tcontent: theme.apply(\"time\", new Date().toLocaleTimeString([], { hour: \"2-digit\", minute: \"2-digit\" })),\n\t\t\tcompactContent: theme.apply(\"time\", new Date().toLocaleTimeString([], { hour: \"2-digit\", minute: \"2-digit\" })),\n\t\t})),\n\t\tsegment(\"hostname\", 20, ({ snapshot, theme }) => ({\n\t\t\tvisible: Boolean(snapshot.hostname),\n\t\t\tcontent: theme.apply(\"muted\", snapshot.hostname ?? \"\"),\n\t\t})),\n\t\tsegment(\"session\", 20, ({ snapshot, theme }) => ({\n\t\t\tvisible: Boolean(snapshot.sessionName || snapshot.sessionId),\n\t\t\tcontent: theme.apply(\"muted\", snapshot.sessionName ?? snapshot.sessionId ?? \"\"),\n\t\t})),\n\t\tsegment(\"extension_statuses\", 30, ({ snapshot, theme }) => {\n\t\t\tconst statuses = snapshot.extensionStatuses;\n\t\t\tif (!statuses || statuses.length === 0) return { visible: false, content: \"\" };\n\t\t\t// Values already carry their display label (extensions publish via\n\t\t\t// `ctx.ui.setStatus(key, text)` where text is the visible string).\n\t\t\t// Mirror Pi's native footer: sort by key, join the values only.\n\t\t\tconst text = [...statuses]\n\t\t\t\t.sort((a, b) => a.key.localeCompare(b.key))\n\t\t\t\t.map((item) => item.value)\n\t\t\t\t.join(\" \");\n\t\t\treturn { visible: true, content: theme.apply(\"muted\", text) };\n\t\t}),\n\t];\n\treturn new Map(segments.map((item) => [item.id, item]));\n}\n\nconst CONTEXT_BAR_WIDTH = 10;\n\nfunction contextBar(percent: number, width = CONTEXT_BAR_WIDTH): string {\n\tconst filled = Math.max(0, Math.min(width, Math.round((percent / 100) * width)));\n\treturn \"█\".repeat(filled) + \"░\".repeat(width - filled);\n}\n\n/** Bar colors: green under 50%, yellow from 50% to 70%, red above 70%. */\nfunction contextBarToken(percent: number): SemanticToken {\n\tif (percent > 70) return \"error\";\n\tif (percent >= 50) return \"warning\";\n\treturn \"success\";\n}\n\nfunction formatTokens(value: number): string {\n\tif (value >= 1_000_000) {\n\t\tconst millions = value / 1_000_000;\n\t\treturn `${Number.isInteger(millions) ? millions : millions.toFixed(1)}M`;\n\t}\n\tif (value >= 1_000) {\n\t\tconst thousands = value / 1_000;\n\t\treturn `${Number.isInteger(thousands) ? thousands : thousands.toFixed(1)}K`;\n\t}\n\treturn String(value);\n}\n\nfunction effortLevel(snapshot: StatusSnapshot): ThinkingLevel | undefined {\n\tconst level = snapshot.thinkingLevel;\n\tif (!level) return undefined;\n\t// Reasoning models always surface an effort level (defaulting to off); other\n\t// models only show a level when one is actively set.\n\tif (snapshot.reasoning === true) return level;\n\treturn level === \"off\" ? undefined : level;\n}\n\nfunction styleEffort(theme: ResolvedTheme, level: ThinkingLevel): string {\n\tif (level === \"high\" || level === \"xhigh\" || level === \"max\") return theme.rainbow(level);\n\tconst token =\n\t\tlevel === \"minimal\"\n\t\t\t? \"thinkingMinimal\"\n\t\t\t: level === \"low\"\n\t\t\t\t? \"thinkingLow\"\n\t\t\t\t: level === \"medium\"\n\t\t\t\t\t? \"thinkingMedium\"\n\t\t\t\t\t: \"thinking\";\n\treturn theme.apply(token, level);\n}\n\nfunction formatElapsed(ms: number): string {\n\tconst seconds = Math.max(0, Math.floor(ms / 1000));\n\treturn `${Math.floor(seconds / 3600)}:${String(Math.floor((seconds % 3600) / 60)).padStart(2, \"0\")}:${String(seconds % 60).padStart(2, \"0\")}`;\n}\n\nfunction thinkingLabel(level: ThinkingLevel): string {\n\treturn level === \"minimal\" ? \"min\" : level === \"medium\" ? \"med\" : level;\n}\n\nexport function contextState(percent: number | undefined): ContextState | undefined {\n\tif (percent === undefined || !Number.isFinite(percent)) return undefined;\n\tif (percent >= 90) return \"critical\";\n\tif (percent >= 75) return \"high\";\n\tif (percent >= 50) return \"medium\";\n\treturn \"low\";\n}\n\nexport function normalizeThinkingLevel(value: unknown): ThinkingLevel {\n\treturn [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"].includes(value as string)\n\t\t? (value as ThinkingLevel)\n\t\t: \"off\";\n}\n\nexport function contextPercent(\n\tvalue: Pick<ContextSnapshot, \"currentTokens\" | \"windowTokens\" | \"percent\">,\n): number | undefined {\n\tconst percent =\n\t\tvalue.percent ??\n\t\t(value.currentTokens !== undefined && value.windowTokens\n\t\t\t? (value.currentTokens / value.windowTokens) * 100\n\t\t\t: undefined);\n\treturn percent === undefined ? undefined : Math.max(0, Math.min(100, percent));\n}\n\nexport function contextSemanticToken(state: ContextState): SemanticToken {\n\treturn state === \"critical\"\n\t\t? \"contextCritical\"\n\t\t: state === \"high\"\n\t\t\t? \"contextHigh\"\n\t\t\t: state === \"medium\"\n\t\t\t\t? \"contextMedium\"\n\t\t\t\t: \"contextLow\";\n}\n","import type { ExtensionUIContext } from \"@earendil-works/pi-coding-agent\";\nimport { CustomEditor } from \"@earendil-works/pi-coding-agent\";\nimport { type EditorComponent, visibleWidth } from \"@earendil-works/pi-tui\";\nimport type { NormalizedPiStyleConfig } from \"../../domain/config-types.js\";\nimport { contextPercent, type StatusSnapshot, type ThinkingLevel } from \"../../domain/status.js\";\nimport type { ResolvedTheme } from \"../../domain/theme.js\";\nimport { resolveTheme } from \"../../domain/theme.js\";\nimport { stripAnsi, truncateAnsi } from \"../../shared/ansi.js\";\n\nexport const EDITOR_DIAGNOSTIC_KEY = \"pi-style.editor\";\ntype SetEditorComponent = NonNullable<ExtensionUIContext[\"setEditorComponent\"]>;\ntype EditorFactory = NonNullable<Parameters<SetEditorComponent>[0]>;\ntype Tui = Parameters<EditorFactory>[0];\ntype PiEditorTheme = Parameters<EditorFactory>[1];\ntype Keybindings = Parameters<EditorFactory>[2];\ntype EditorHost = Pick<ExtensionUIContext, \"setEditorComponent\"> & {\n\tgetEditorComponent?: () => EditorFactory | undefined;\n\tnotify?: (message: string, type?: \"info\" | \"warning\" | \"error\") => void;\n\t/** Full Pi theme; provides thinking-level border colors when available. */\n\treadonly theme?: { getThinkingBorderColor?: (level: ThinkingLevel) => (str: string) => string };\n};\n\nexport interface EditorInstallation {\n\treadonly generation: number;\n\treadonly installedFactory: EditorFactory;\n\treadonly previousFactory: EditorFactory | undefined;\n\treadonly preservedPrevious: boolean;\n\tupdate(snapshot: StatusSnapshot): void;\n\tconfigure(config: NormalizedPiStyleConfig): void;\n\tdispose(): void;\n}\n\ninterface EditorOptions {\n\tconfig: NormalizedPiStyleConfig;\n\tsnapshot: StatusSnapshot;\n\ttheme: PiEditorTheme;\n\t/** Full Pi theme for thinking-level border colors (optional; falls back to borderColor). */\n\tfullTheme?: { getThinkingBorderColor?: (level: ThinkingLevel) => (str: string) => string };\n\tonSnapshot: (snapshot: StatusSnapshot) => void;\n}\n\nconst widthOf = visibleWidth;\n\nfunction widthSafe(value: string, width: number): string {\n\tif (width <= 0) return \"\";\n\tconst fitted = widthOf(value) > width ? truncateAnsi(value, width, \"\") : value;\n\tconst current = widthOf(fitted);\n\treturn current < width ? fitted + \" \".repeat(width - current) : fitted;\n}\n\nfunction isNativeBorderLine(line: string): boolean {\n\tconst stripped = stripAnsi(line);\n\treturn /^─{2,}$/.test(stripped) || /^─── [↑↓] \\d+ more /.test(stripped);\n}\n\n/**\n * Remove `count` leading visible characters from an ANSI-rendered editor line,\n * preserving escape sequences (CSI/OSC/APC/DCS) verbatim. Used to hide the\n * bash-mode `!` prefix; the CURSOR_MARKER and cursor-block sequences pass\n * through unchanged so hardware-cursor placement stays aligned.\n */\nfunction stripLeadingVisibleChars(line: string, count: number): string {\n\tif (count <= 0 || line.length === 0) return line;\n\tlet output = \"\";\n\tlet stripped = 0;\n\tlet index = 0;\n\twhile (index < line.length) {\n\t\tconst char = line[index] ?? \"\";\n\t\tif (char === \"\\x1b\") {\n\t\t\tconst start = index;\n\t\t\tindex++;\n\t\t\tconst intro = line[index];\n\t\t\tif (intro === \"[\") {\n\t\t\t\tindex++;\n\t\t\t\twhile (index < line.length) {\n\t\t\t\t\tconst byte = line[index] ?? \"\";\n\t\t\t\t\tindex++;\n\t\t\t\t\tif (byte >= \"@\" && byte <= \"~\") break;\n\t\t\t\t}\n\t\t\t} else if (intro === \"]\" || intro === \"_\" || intro === \"^\" || intro === \"P\") {\n\t\t\t\tindex++;\n\t\t\t\twhile (index < line.length) {\n\t\t\t\t\tconst byte = line[index] ?? \"\";\n\t\t\t\t\tif (byte === \"\\x1b\" && line[index + 1] === \"\\\\\") {\n\t\t\t\t\t\tindex += 2;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tindex++;\n\t\t\t\t\tif (byte === \"\\x07\") break;\n\t\t\t\t}\n\t\t\t} else if (intro !== undefined) {\n\t\t\t\tindex++;\n\t\t\t}\n\t\t\toutput += line.slice(start, index);\n\t\t\tcontinue;\n\t\t}\n\t\tif (stripped < count) {\n\t\t\tstripped++;\n\t\t\tindex++;\n\t\t\tcontinue;\n\t\t}\n\t\toutput += char;\n\t\tindex++;\n\t}\n\treturn output;\n}\n\nfunction semanticTheme(theme: PiEditorTheme, config: NormalizedPiStyleConfig): ResolvedTheme {\n\tconst editorTheme = theme;\n\treturn resolveTheme(\n\t\t{\n\t\t\tfg: (token) => {\n\t\t\t\tif (token === \"borderActive\" || token.startsWith(\"thinking\")) return editorTheme.borderColor(\"\");\n\t\t\t\treturn \"\";\n\t\t\t},\n\t\t},\n\t\tconfig,\n\t);\n}\n\n/**\n * A thin CustomEditor treatment: all text, cursor, paste, autocomplete, history,\n * and keybinding state remains owned by Pi's editor implementation.\n */\nexport class StyledEditor extends CustomEditor implements EditorComponent {\n\tprivate config: NormalizedPiStyleConfig;\n\tprivate snapshot: StatusSnapshot;\n\tprivate readonly piTheme: PiEditorTheme;\n\tprivate readonly fullTheme: EditorOptions[\"fullTheme\"];\n\tprivate readonly onSnapshot: (snapshot: StatusSnapshot) => void;\n\tprivate semantic: ResolvedTheme;\n\tprivate disposed = false;\n\n\tconstructor(tui: Tui, theme: PiEditorTheme, keybindings: Keybindings, options: EditorOptions) {\n\t\tsuper(tui, theme, keybindings);\n\t\tthis.config = options.config;\n\t\tthis.snapshot = options.snapshot;\n\t\tthis.piTheme = theme;\n\t\tthis.fullTheme = options.fullTheme;\n\t\tthis.onSnapshot = options.onSnapshot;\n\t\tthis.semantic = semanticTheme(theme, options.config);\n\t\tthis.setPaddingX(0);\n\t}\n\n\tupdate(snapshot: StatusSnapshot): void {\n\t\tif (this.disposed) return;\n\t\tthis.snapshot = snapshot;\n\t\tthis.invalidate();\n\t}\n\n\tconfigure(config: NormalizedPiStyleConfig): void {\n\t\tif (this.disposed) return;\n\t\tthis.config = config;\n\t\tthis.semantic = semanticTheme(this.piTheme, config);\n\t\tthis.invalidate();\n\t}\n\n\toverride handleInput(data: string): void {\n\t\tif (this.disposed) return;\n\t\tsuper.handleInput(data);\n\t\tthis.onSnapshot({ ...this.snapshot });\n\t}\n\n\toverride invalidate(): void {\n\t\tsuper.invalidate();\n\t\tthis.semantic = semanticTheme(this.piTheme, this.config);\n\t\tthis.tui.requestRender();\n\t}\n\n\toverride render(width: number): string[] {\n\t\tif (width <= 0) return [];\n\t\tconst nativeLines = super.render(width);\n\t\tconst style = this.styleFor(width);\n\t\t// Autocomplete (slash menu / @-mentions) restructure: Pi draws the\n\t\t// suggestions after its own bottom border, which pushes the below-editor\n\t\t// widgets (status line) down. Re-frame the native output so the dropdown\n\t\t// lives INSIDE the input box, keeping the footer directly below the input.\n\t\t// Native layout: [top border, text lines, bottom border, dropdown lines...].\n\t\tif ((this as unknown as { autocompleteState?: unknown }).autocompleteState) {\n\t\t\tconst prompt = this.prompt();\n\t\t\tconst padding = this.paddingFor(width, style);\n\t\t\tconst promptWidth = widthOf(prompt) + 1;\n\t\t\tconst prefix = `${\" \".repeat(padding)}${prompt} `;\n\t\t\tconst continuation = \" \".repeat(padding + promptWidth);\n\t\t\tconst borderIndex = nativeLines.slice(1).findIndex((line) => isNativeBorderLine(line));\n\t\t\tconst split = borderIndex >= 0 ? borderIndex + 1 : nativeLines.length;\n\t\t\tconst body = nativeLines.slice(1, split);\n\t\t\tconst dropdown = nativeLines.slice(split);\n\t\t\tconst border = this.borderFor();\n\t\t\tconst kind = this.frameKind(style);\n\t\t\tconst renderWidth = width - (kind === \"rounded\" ? 2 : 0);\n\t\t\tconst sideColor = kind === \"rounded\" ? this.borderColorFor() : undefined;\n\t\t\tconst wrap = (line: string) =>\n\t\t\t\tkind === \"rounded\" && sideColor ? `${sideColor(\"│\")}${line}${sideColor(\"│\")}` : line;\n\t\t\tconst bashHidden = this.bashHiddenCount();\n\t\t\tconst renderedBody = body.map((line, index) => {\n\t\t\t\tconst source = index === 0 && bashHidden > 0 ? stripLeadingVisibleChars(line, bashHidden) : line;\n\t\t\t\treturn wrap(widthSafe(`${index === 0 ? prefix : continuation}${source}`, renderWidth));\n\t\t\t});\n\t\t\tconst dropdownLines = dropdown.map((line) => wrap(widthSafe(line, renderWidth)));\n\t\t\tif (kind === \"rounded\") {\n\t\t\t\treturn [\n\t\t\t\t\tborder(`╭${\"─\".repeat(Math.max(0, width - 2))}╮`),\n\t\t\t\t\t...renderedBody,\n\t\t\t\t\t...dropdownLines,\n\t\t\t\t\tborder(`╰${\"─\".repeat(Math.max(0, width - 2))}╯`),\n\t\t\t\t];\n\t\t\t}\n\t\t\treturn [border(\"─\".repeat(width)), ...renderedBody, ...dropdownLines, border(\"─\".repeat(width))];\n\t\t}\n\t\tif (style === \"native\") return nativeLines.map((line) => widthSafe(line, width));\n\n\t\tconst prompt = this.prompt();\n\t\tconst promptWidth = widthOf(prompt) + 1;\n\t\tconst padding = this.paddingFor(width, style);\n\t\tconst kind = this.frameKind(style);\n\t\tconst sideReserve = kind === \"rounded\" ? 2 : 0;\n\t\tconst renderWidth = Math.max(1, width - sideReserve);\n\t\tconst innerWidth = Math.max(1, renderWidth - promptWidth - padding * 2);\n\t\tconst innerLines = super.render(innerWidth);\n\t\tif (innerLines.length === 0) return [];\n\n\t\tconst body = innerLines.slice(1, -1);\n\t\tconst prefix = `${\" \".repeat(padding)}${prompt} `;\n\t\tconst continuation = \" \".repeat(padding + promptWidth);\n\t\tconst hint = this.config.editor.hint;\n\t\tconst showHint = hint !== \"\" && this.getText() === \"\";\n\t\tconst bashHidden = this.bashHiddenCount();\n\t\tconst renderedBody = body.map((line, index) => {\n\t\t\tconst lead = index === 0 ? prefix : continuation;\n\t\t\tconst source = index === 0 && bashHidden > 0 ? stripLeadingVisibleChars(line, bashHidden) : line;\n\t\t\tlet content = `${lead}${source}`;\n\t\t\t// Empty-input hint: the cursor block (first cell of the native empty\n\t\t\t// line) stays at the input position, the dim hint trails it. The native\n\t\t\t// line is pre-padded to renderWidth with literal spaces; drop them from\n\t\t\t// the raw end (safe: no ANSI follows the padding) before appending the\n\t\t\t// hint, or the hint is truncated away by widthSafe. Typing any character\n\t\t\t// makes the text non-empty and the hint disappears.\n\t\t\tif (showHint && index === 0 && line) {\n\t\t\t\tlet end = content.length;\n\t\t\t\twhile (end > 0 && content[end - 1] === \" \") end--;\n\t\t\t\tif (end < content.length) content = content.slice(0, end);\n\t\t\t\tcontent += this.semantic.apply(\"hint\", hint);\n\t\t\t}\n\t\t\treturn widthSafe(content, renderWidth);\n\t\t});\n\t\tconst metadata = this.metadata(width, style);\n\t\tconst framed = this.frame(width, style, renderedBody, metadata);\n\t\treturn framed.map((line) => widthSafe(line, width));\n\t}\n\n\tdispose(): void {\n\t\tif (this.disposed) return;\n\t\tthis.disposed = true;\n\t\tthis.invalidate();\n\t}\n\n\tprivate prompt(): string {\n\t\tif (this.isBashMode()) {\n\t\t\t// Bash mode (`!` prefix): the prompt glyph becomes the bash icon and the\n\t\t\t// leading `!` is hidden from the input text. The glyph takes the live\n\t\t\t// border color (pi sets editor.borderColor to the bashMode color).\n\t\t\tconst glyph = this.semantic.glyph(\"bashPrompt\");\n\t\t\treturn this.borderColor(glyph);\n\t\t}\n\t\tconst configured = this.config.theme.glyphs.prompt;\n\t\tif (configured) return configured;\n\t\treturn this.semantic.mode === \"ascii\" ? \">\" : \"❯\";\n\t}\n\n\t/** Pi's bash mode: the input starts with `!` after optional whitespace. */\n\tprivate isBashMode(): boolean {\n\t\treturn this.getText().trimStart().startsWith(\"!\");\n\t}\n\n\t/**\n\t * Number of leading `!` characters to hide from the displayed input while\n\t * bash mode is active. Characters under the cursor are never hidden, so the\n\t * native cursor block stays visible when the cursor sits on a `!`.\n\t */\n\tprivate bashHiddenCount(): number {\n\t\tconst text = this.getText();\n\t\tlet index = 0;\n\t\twhile (index < text.length && (text[index] === \" \" || text[index] === \"\\t\")) index++;\n\t\tconst runStart = index;\n\t\twhile (index < text.length && text[index] === \"!\") index++;\n\t\tconst run = index - runStart;\n\t\tif (run === 0) return 0;\n\t\tconst cursor = this.getCursor();\n\t\tconst position = cursor.line === 0 ? cursor.col : Number.POSITIVE_INFINITY;\n\t\treturn Math.min(run, Math.max(0, position - runStart));\n\t}\n\n\tprivate styleFor(width: number): \"compact\" | \"boxed\" | \"dock\" | \"native\" {\n\t\tif (width < 20) return \"native\";\n\t\tif ([\"compact\", \"boxed\", \"dock\", \"native\"].includes(this.config.editor.style)) {\n\t\t\tif (this.config.editor.style === \"native\") return \"native\";\n\t\t\tif (width < 40 && this.config.editor.style !== \"compact\") return \"compact\";\n\t\t\treturn this.config.editor.style as \"compact\" | \"boxed\" | \"dock\";\n\t\t}\n\t\treturn \"compact\";\n\t}\n\n\t/**\n\t * Resolve the frame treatment for a style: horizontal bars for compact,\n\t * full-width bars for boxed, an outlined box for dock, and a rounded box\n\t * with side borders (`╭─╮ │ │ ╰─╯`) for `frame: \"rounded\"`.\n\t */\n\tprivate frameKind(\n\t\tstyle: \"compact\" | \"boxed\" | \"dock\" | \"native\",\n\t): \"compact\" | \"boxed\" | \"outline\" | \"rounded\" | \"native\" {\n\t\tconst frame = this.config.editor.frame;\n\t\tif (style === \"compact\" || frame === \"line\" || frame === \"solid\") return \"compact\";\n\t\tif (style === \"boxed\") return \"boxed\";\n\t\tif (frame === \"native\") return \"native\";\n\t\tif (frame === \"rounded\") return \"rounded\";\n\t\treturn \"outline\";\n\t}\n\n\tprivate paddingFor(width: number, style: \"compact\" | \"boxed\" | \"dock\" | \"native\"): number {\n\t\tif (width < 50) return 0;\n\t\treturn style === \"boxed\" ? 2 : style === \"dock\" ? 1 : 1;\n\t}\n\n\tprivate borderFor(): (line: string) => string {\n\t\treturn (line: string) => this.borderColorFor()(line);\n\t}\n\n\t/** Raw border color function (thinking-synced) WITHOUT full-width padding, for single glyphs. */\n\tprivate borderColorFor(): (line: string) => string {\n\t\t// While bash mode is active pi keeps editor.borderColor set to the\n\t\t// bashMode color (its native updateEditorBorderColor path); prefer it over\n\t\t// the thinking-level color so the whole frame switches to the bash color.\n\t\tif (this.isBashMode()) return this.borderColor;\n\t\tconst level = this.snapshot.thinkingLevel;\n\t\tconst thinking = this.fullTheme?.getThinkingBorderColor?.(level ?? \"off\");\n\t\treturn thinking ?? this.piTheme.borderColor;\n\t}\n\n\tprivate frame(\n\t\twidth: number,\n\t\tstyle: \"compact\" | \"boxed\" | \"dock\" | \"native\",\n\t\tbody: string[],\n\t\tmetadata: string[],\n\t): string[] {\n\t\tconst border = this.borderFor();\n\t\tconst kind = this.frameKind(style);\n\t\tif (kind === \"compact\") {\n\t\t\t// Match Pi's native editor: a horizontal border above and below the input.\n\t\t\treturn [border(\"─\".repeat(width)), ...body, border(\"─\".repeat(width)), ...metadata];\n\t\t}\n\t\tif (kind === \"boxed\") {\n\t\t\tconst glyph = this.config.editor.frame === \"halfblock\" ? \"▀\" : \"━\";\n\t\t\treturn [border(glyph.repeat(width)), ...body, border(glyph.repeat(width)), ...metadata];\n\t\t}\n\t\tif (kind === \"native\") return body;\n\t\tconst inner = Math.max(0, width - 2);\n\t\tif (kind === \"rounded\") {\n\t\t\t// Rounded box with vertical side borders: `╭─╮ / │ text │ / ╰─╯`.\n\t\t\t// Body lines were rendered at width - 2; re-fit defensively, then wrap.\n\t\t\t// Side glyphs use the raw border color (no full-width padding, unlike border()).\n\t\t\tconst sideColor = this.borderColorFor();\n\t\t\tconst side = (line: string) => `${sideColor(\"│\")}${widthSafe(line, inner)}${sideColor(\"│\")}`;\n\t\t\treturn [border(`╭${\"─\".repeat(inner)}╮`), ...body.map(side), border(`╰${\"─\".repeat(inner)}╯`), ...metadata];\n\t\t}\n\t\treturn [border(`┌${\"─\".repeat(inner)}┐`), ...body, border(`└${\"─\".repeat(inner)}┘`), ...metadata];\n\t}\n\n\tprivate metadata(width: number, style: \"compact\" | \"boxed\" | \"dock\" | \"native\"): string[] {\n\t\tif (!this.config.editor.showMetadata || width < 60) return [];\n\t\tconst percent = contextPercent(this.snapshot.context ?? {});\n\t\tif (percent === undefined) return [];\n\t\tconst label = `ctx ${Math.round(percent)}%`;\n\t\treturn [this.piTheme.borderColor(` ${style === \"boxed\" ? \"· \" : \"\"}${label}`)];\n\t}\n}\n\nexport function installEditor(options: {\n\thost: EditorHost;\n\tconfig: NormalizedPiStyleConfig;\n\tgeneration: number;\n\tinitialSnapshot: StatusSnapshot;\n\tisCurrent?: () => boolean;\n}): EditorInstallation | undefined {\n\tif (!options.host.setEditorComponent) return undefined;\n\tconst previous = options.host.getEditorComponent?.();\n\tif (previous && options.config.compatibility.preferExistingEditor) {\n\t\treturn {\n\t\t\tgeneration: options.generation,\n\t\t\tinstalledFactory: previous,\n\t\t\tpreviousFactory: previous,\n\t\t\tpreservedPrevious: true,\n\t\t\tupdate() {},\n\t\t\tconfigure() {},\n\t\t\tdispose() {},\n\t\t};\n\t}\n\tlet config = options.config;\n\tlet snapshot = options.initialSnapshot;\n\tlet disposed = false;\n\tconst components = new Set<StyledEditor>();\n\tconst factory = ((tui: Tui, theme: PiEditorTheme, keybindings: Keybindings) => {\n\t\tconst editor = new StyledEditor(tui, theme, keybindings, {\n\t\t\tconfig,\n\t\t\tsnapshot,\n\t\t\ttheme,\n\t\t\t...(options.host.theme ? { fullTheme: options.host.theme } : {}),\n\t\t\tonSnapshot: (next) => {\n\t\t\t\tif (!disposed && options.isCurrent?.() !== false) snapshot = next;\n\t\t\t},\n\t\t});\n\t\tcomponents.add(editor);\n\t\treturn editor;\n\t}) as EditorFactory;\n\ttry {\n\t\toptions.host.setEditorComponent(factory);\n\t} catch {\n\t\toptions.host.notify?.(\"pi-style editor unavailable; keeping the native editor\", \"warning\");\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tgeneration: options.generation,\n\t\tinstalledFactory: factory,\n\t\tpreviousFactory: previous,\n\t\tpreservedPrevious: false,\n\t\tupdate(next) {\n\t\t\tif (disposed || options.isCurrent?.() === false) return;\n\t\t\tsnapshot = next;\n\t\t\tfor (const component of components) component.update(next);\n\t\t},\n\t\tconfigure(next) {\n\t\t\tif (disposed || options.isCurrent?.() === false) return;\n\t\t\tconfig = next;\n\t\t\tfor (const component of components) component.configure(next);\n\t\t},\n\t\tdispose() {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\tfor (const component of components) component.dispose();\n\t\t\tcomponents.clear();\n\t\t\tif (options.host.getEditorComponent?.() === factory) {\n\t\t\t\toptions.host.setEditorComponent(previous);\n\t\t\t}\n\t\t},\n\t};\n}\n","import type { NormalizedPiStyleConfig } from \"./config-types.js\";\n\nexport type GlyphMode = \"nerd\" | \"unicode\" | \"ascii\";\nexport type SemanticToken =\n\t| \"surface\"\n\t| \"surfaceRaised\"\n\t| \"surfaceMuted\"\n\t| \"text\"\n\t| \"muted\"\n\t| \"dim\"\n\t| \"accent\"\n\t| \"accentStrong\"\n\t| \"border\"\n\t| \"borderMuted\"\n\t| \"borderActive\"\n\t| \"success\"\n\t| \"warning\"\n\t| \"error\"\n\t| \"model\"\n\t| \"thinking\"\n\t| \"thinkingMinimal\"\n\t| \"thinkingLow\"\n\t| \"thinkingMedium\"\n\t| \"thinkingHigh\"\n\t| \"thinkingXhigh\"\n\t| \"thinkingMax\"\n\t| \"path\"\n\t| \"gitClean\"\n\t| \"gitDirty\"\n\t| \"contextLow\"\n\t| \"contextMedium\"\n\t| \"contextHigh\"\n\t| \"contextCritical\"\n\t| \"tokens\"\n\t| \"cache\"\n\t| \"cost\"\n\t| \"time\"\n\t| \"separator\"\n\t| \"hint\";\n\n/** Structural view of Pi's theme. fg/bg follow Pi's `(color, text) => string` shape. */\nexport interface ActiveTheme {\n\tfg?: (color: string, text: string) => string;\n\tbg?: (color: string, text: string) => string;\n\tcolors?: Record<string, string>;\n}\n\nexport interface ResolvedTheme {\n\t/** ANSI color prefix for a semantic token, or \"\" when uncolored. */\n\treadonly color: (token: SemanticToken) => string;\n\t/** Prefix + text + reset; returns plain text when the token is uncolored. */\n\treadonly apply: (token: SemanticToken, text: string) => string;\n\t/** Rainbow gradient text (used for high thinking levels); plain when uncolored. */\n\treadonly rainbow: (text: string) => string;\n\treadonly glyph: (name: keyof typeof GLYPHS.unicode) => string;\n\treadonly mode: GlyphMode;\n\treadonly noColor: boolean;\n}\n\n/**\n * Default semantic colors — hex values render without any Pi theme; theme names resolve through Pi's theme.\n */\nconst SEMANTIC_COLORS: Record<SemanticToken, string> = {\n\tsurface: \"\",\n\tsurfaceRaised: \"\",\n\tsurfaceMuted: \"\",\n\ttext: \"text\",\n\tmuted: \"muted\",\n\tdim: \"dim\",\n\taccent: \"accent\",\n\taccentStrong: \"accent\",\n\tborder: \"border\",\n\tborderMuted: \"borderMuted\",\n\tborderActive: \"borderAccent\",\n\tsuccess: \"success\",\n\twarning: \"warning\",\n\terror: \"error\",\n\tmodel: \"#d787af\",\n\tthinking: \"thinkingOff\",\n\tthinkingMinimal: \"thinkingMinimal\",\n\tthinkingLow: \"thinkingLow\",\n\tthinkingMedium: \"thinkingMedium\",\n\tthinkingHigh: \"thinkingHigh\",\n\tthinkingXhigh: \"thinkingXhigh\",\n\tthinkingMax: \"thinkingMax\",\n\tpath: \"#00afaf\",\n\tgitClean: \"success\",\n\tgitDirty: \"warning\",\n\tcontextLow: \"dim\",\n\tcontextMedium: \"warning\",\n\tcontextHigh: \"error\",\n\tcontextCritical: \"error\",\n\ttokens: \"muted\",\n\tcache: \"muted\",\n\tcost: \"text\",\n\ttime: \"muted\",\n\tseparator: \"dim\",\n\thint: \"#8a8a8a\",\n};\n\nconst GLYPHS = {\n\tnerd: {\n\t\tpi: \"π\",\n\t\tgit: \"\\uE0A0\",\n\t\tpath: \"\\uF07B\",\n\t\tcontext: \"\\u{F035B}\",\n\t\tseparator: \"\\uE0B0\",\n\t\tpowerlineLeft: \"\\uE0B0\",\n\t\tpowerlineRight: \"\\uE0B2\",\n\t\tpowerlineThinLeft: \"\\uE0B1\",\n\t\tpowerlineThinRight: \"\\uE0B3\",\n\t\tbatchOpen: \"\\u{F111}\",\n\t\tbashPrompt: \"\\u{F12A}\",\n\t},\n\tunicode: {\n\t\tpi: \"π\",\n\t\tgit: \"⎇\",\n\t\tpath: \"⌂\",\n\t\tcontext: \"◫\",\n\t\tseparator: \"│\",\n\t\tpowerlineLeft: \"›\",\n\t\tpowerlineRight: \"‹\",\n\t\tpowerlineThinLeft: \"│\",\n\t\tpowerlineThinRight: \"│\",\n\t\tbatchOpen: \"●\",\n\t\tbashPrompt: \"$\",\n\t},\n\tascii: {\n\t\tpi: \"pi\",\n\t\tgit: \"git\",\n\t\tpath: \"path\",\n\t\tcontext: \"ctx\",\n\t\tseparator: \"|\",\n\t\tpowerlineLeft: \">\",\n\t\tpowerlineRight: \"<\",\n\t\tpowerlineThinLeft: \"|\",\n\t\tpowerlineThinRight: \"|\",\n\t\tbatchOpen: \"v\",\n\t\tbashPrompt: \"$\",\n\t},\n} as const;\n\nfunction isHex(color: string): color is `#${string}` {\n\treturn /^#[0-9a-fA-F]{6}$/.test(color);\n}\n\nexport function hexToAnsiPrefix(hex: string): string {\n\tconst value = hex.replace(\"#\", \"\");\n\tconst r = Number.parseInt(value.slice(0, 2), 16);\n\tconst g = Number.parseInt(value.slice(2, 4), 16);\n\tconst b = Number.parseInt(value.slice(4, 6), 16);\n\treturn `\\x1b[38;2;${r};${g};${b}m`;\n}\n\n/** Rainbow gradient for high thinking levels. */\nconst RAINBOW_COLORS = [\n\t\"#b281d6\",\n\t\"#d787af\",\n\t\"#febc38\",\n\t\"#e4c00f\",\n\t\"#89d281\",\n\t\"#00afaf\",\n\t\"#178fb9\",\n\t\"#b281d6\",\n] as const;\n\nfunction rainbowAnsi(text: string): string {\n\tlet result = \"\";\n\tlet colorIndex = 0;\n\tfor (const char of text) {\n\t\tif (char === \" \" || char === \":\") {\n\t\t\tresult += char;\n\t\t} else {\n\t\t\tresult += hexToAnsiPrefix(RAINBOW_COLORS[colorIndex % RAINBOW_COLORS.length] ?? \"#b281d6\") + char;\n\t\t\tcolorIndex++;\n\t\t}\n\t}\n\treturn `${result}\\x1b[0m`;\n}\n\nfunction colorPrefixFor(\n\tactive: ActiveTheme | undefined,\n\tconfig: NormalizedPiStyleConfig,\n\tnoColor: boolean,\n\ttoken: SemanticToken,\n): string {\n\tif (noColor) return \"\";\n\tconst raw = config.theme.colors[token] ?? SEMANTIC_COLORS[token];\n\tif (!raw) return \"\";\n\tif (isHex(raw)) return hexToAnsiPrefix(raw);\n\tif (active?.fg) {\n\t\ttry {\n\t\t\t// Pi's fg returns `\\x1b[38;5;Nm` + text + `\\x1b[39m`; keep only the prefix.\n\t\t\tconst styled = active.fg(raw, \"\");\n\t\t\treturn styled.endsWith(\"\\x1b[39m\") ? styled.slice(0, -5) : styled;\n\t\t} catch {\n\t\t\treturn \"\";\n\t\t}\n\t}\n\treturn \"\";\n}\n\nexport function detectGlyphMode(\n\tconfig: NormalizedPiStyleConfig,\n\tenv: Record<string, string | undefined> = {},\n): GlyphMode {\n\tif (env.PI_STYLE_NERD_FONTS === \"1\") return \"nerd\";\n\tif (env.PI_STYLE_NERD_FONTS === \"0\") return \"unicode\";\n\tif (config.theme.nerdFonts === \"on\") return \"nerd\";\n\tif (config.theme.nerdFonts === \"off\") return \"unicode\";\n\tif (env.GHOSTTY_RESOURCES_DIR) return \"nerd\";\n\t// Conservative heuristic: known terminals commonly ship with a Nerd Font. An explicit override stays authoritative.\n\tconst term = (env.TERM_PROGRAM ?? \"\").toLowerCase();\n\tif ([\"iterm\", \"wezterm\", \"kitty\", \"ghostty\", \"alacritty\", \"warp\"].some((name) => term.includes(name))) {\n\t\treturn \"nerd\";\n\t}\n\treturn config.preset === \"ascii\" ? \"ascii\" : \"unicode\";\n}\n\nexport function resolveTheme(\n\tactive: ActiveTheme | undefined,\n\tconfig: NormalizedPiStyleConfig,\n\tenv: Record<string, string | undefined> = {},\n): ResolvedTheme {\n\tconst noColor = Object.hasOwn(env, \"NO_COLOR\") && env.NO_COLOR !== \"\" && config.theme.colors.colorOverride !== \"on\";\n\tconst mode = config.preset === \"ascii\" ? \"ascii\" : detectGlyphMode(config, env);\n\tconst color = (token: SemanticToken) => colorPrefixFor(active, config, noColor, token);\n\treturn {\n\t\tmode,\n\t\tnoColor,\n\t\tcolor,\n\t\tapply: (token, text) => {\n\t\t\tconst prefix = color(token);\n\t\t\treturn prefix ? `${prefix}${text}\\x1b[0m` : text;\n\t\t},\n\t\trainbow: (text) => (noColor ? text : rainbowAnsi(text)),\n\t\tglyph: (name) => config.theme.glyphs[name] ?? GLYPHS[mode][name],\n\t};\n}\nexport { GLYPHS };\n","import { hexToAnsiPrefix, type ResolvedTheme } from \"../../domain/theme.js\";\nimport { fitAnsiWidth, parseAnsiFgToRgb, visibleWidth } from \"../../shared/ansi.js\";\n\n/**\n * Compact startup logo header. Renders the block-art Pi logo with a\n * per-character accent gradient plus side details, with stacked/truncated\n * fallbacks for narrow widths. Pure render: color comes only from the\n * resolved theme.\n */\n\nexport const PI_LOGO_LINES = [\n\t\"████████████╗\",\n\t\"████████████║\",\n\t\"████╔═══████║\",\n\t\"████║ ████║\",\n\t\"████████╬═══████╗\",\n\t\"████████║ ████║ \",\n\t\"████╔═══╝ ████║\",\n\t\"████║ ████║\",\n\t\"╚═══╝ ╚═══╝\",\n] as const;\n\nconst LOGO_PALETTE_STEPS = 24;\nconst LOGO_MAX_DARKEN = 0.18;\nconst LOGO_MAX_LIGHTEN = 0.18;\nconst LOGO_ROW_PHASE_STEP = 0.12;\nconst LOGO_GAP = \" \";\n/** Minimum side-detail width before the logo collapses to stacked lines. */\nconst LOGO_SIDE_DETAIL_MIN_WIDTH = 12;\n\ntype Rgb = { r: number; g: number; b: number };\n\nfunction clampChannel(value: number): number {\n\treturn Math.max(0, Math.min(255, Math.round(value)));\n}\n\nfunction interpolateRgb(start: Rgb, end: Rgb, factor: number): Rgb {\n\treturn {\n\t\tr: clampChannel(start.r + (end.r - start.r) * factor),\n\t\tg: clampChannel(start.g + (end.g - start.g) * factor),\n\t\tb: clampChannel(start.b + (end.b - start.b) * factor),\n\t};\n}\n\nfunction darkenRgb(rgb: Rgb, amount: number): Rgb {\n\treturn {\n\t\tr: clampChannel(rgb.r * (1 - amount)),\n\t\tg: clampChannel(rgb.g * (1 - amount)),\n\t\tb: clampChannel(rgb.b * (1 - amount)),\n\t};\n}\n\nfunction lightenRgb(rgb: Rgb, amount: number): Rgb {\n\treturn {\n\t\tr: clampChannel(rgb.r + (255 - rgb.r) * amount),\n\t\tg: clampChannel(rgb.g + (255 - rgb.g) * amount),\n\t\tb: clampChannel(rgb.b + (255 - rgb.b) * amount),\n\t};\n}\n\nfunction buildLogoPalette(accent: Rgb): Rgb[] {\n\treturn Array.from({ length: LOGO_PALETTE_STEPS }, (_, index) => {\n\t\tconst progress = index / LOGO_PALETTE_STEPS;\n\t\tconst wave = -Math.cos(progress * Math.PI * 2);\n\t\treturn wave < 0 ? darkenRgb(accent, LOGO_MAX_DARKEN * -wave) : lightenRgb(accent, LOGO_MAX_LIGHTEN * wave);\n\t});\n}\n\nfunction sampleLogoGradient(palette: Rgb[], position: number): Rgb {\n\tconst wrapped = ((position % 1) + 1) % 1;\n\tconst scaled = wrapped * palette.length;\n\tconst baseIndex = Math.floor(scaled) % palette.length;\n\tconst nextIndex = (baseIndex + 1) % palette.length;\n\tconst base = palette[baseIndex];\n\tconst next = palette[nextIndex];\n\tif (!base || !next) return { r: 0, g: 0, b: 0 };\n\treturn interpolateRgb(base, next, scaled - Math.floor(scaled));\n}\n\nfunction renderLogoGradientLine(line: string, palette: Rgb[], phase: number): string {\n\tconst characters = [...line];\n\tconst span = Math.max(characters.length - 1, 1);\n\treturn characters\n\t\t.map((character, index) => {\n\t\t\tif (character === \" \") return character;\n\t\t\tconst color = sampleLogoGradient(palette, index / span + phase);\n\t\t\treturn `${hexToAnsiPrefix(rgbToHex(color))}${character}`;\n\t\t})\n\t\t.join(\"\");\n}\n\nfunction rgbToHex(rgb: Rgb): string {\n\treturn `#${[rgb.r, rgb.g, rgb.b].map((channel) => channel.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\nlet logoGradientCacheKey: string | undefined;\nlet logoGradientCacheLines: string[] | undefined;\n\n/** Accent RGB resolved from the active theme, or undefined when uncolored. */\nexport function resolveAccentRgb(resolved: ResolvedTheme): Rgb | undefined {\n\tconst accentAnsi = resolved.color(\"accent\");\n\tif (!accentAnsi) return undefined;\n\treturn parseAnsiFgToRgb(accentAnsi);\n}\n\n/** The block-art logo lines, gradient-styled when an accent color is resolvable. */\nexport function styledLogoLines(resolved: ResolvedTheme): string[] {\n\tconst accent = resolveAccentRgb(resolved);\n\tif (!accent) return [...PI_LOGO_LINES];\n\tconst cacheKey = `${resolved.color(\"accent\")}|${resolved.mode}`;\n\tif (cacheKey === logoGradientCacheKey && logoGradientCacheLines) return logoGradientCacheLines;\n\tconst palette = buildLogoPalette(accent);\n\tlogoGradientCacheLines = PI_LOGO_LINES.map((line, rowIndex) =>\n\t\trenderLogoGradientLine(line, palette, rowIndex * LOGO_ROW_PHASE_STEP),\n\t);\n\tlogoGradientCacheKey = cacheKey;\n\treturn logoGradientCacheLines;\n}\n\n/**\n * Assemble the compact startup header: gradient logo with side details when\n * wide enough, stacked logo + details next, and a minimal title/status pair\n * for very narrow terminals. Every returned line fits within `width`.\n */\nexport function compactLogoHeader(\n\tresolved: ResolvedTheme,\n\tdetails: readonly [title: string, hints: string, status: string],\n\twidth: number,\n): string[] {\n\tconst logoLines = styledLogoLines(resolved);\n\tconst logoWidth = Math.max(...PI_LOGO_LINES.map((line) => visibleWidth(line)));\n\tconst safeWidth = Math.max(1, width);\n\tconst detailWidth = safeWidth - logoWidth - visibleWidth(LOGO_GAP);\n\n\tif (detailWidth >= LOGO_SIDE_DETAIL_MIN_WIDTH) {\n\t\tconst detailStartRow = Math.max(0, Math.floor((PI_LOGO_LINES.length - details.length) / 2));\n\t\treturn PI_LOGO_LINES.map((plainLine, index) => {\n\t\t\tconst logoPadding = \" \".repeat(Math.max(0, logoWidth - visibleWidth(plainLine)));\n\t\t\tconst detailIndex = index - detailStartRow;\n\t\t\tconst detailText = details[detailIndex];\n\t\t\tconst detail = detailText ? fitAnsiWidth(detailText, detailWidth) : \"\";\n\t\t\treturn `${logoLines[index]}${logoPadding}${detail ? `${LOGO_GAP}${detail}` : \"\"}`;\n\t\t});\n\t}\n\n\tif (safeWidth >= logoWidth) {\n\t\treturn [...logoLines, ...details.map((detail) => fitAnsiWidth(detail, safeWidth))];\n\t}\n\n\treturn [details[0], details[2]].map((detail) => fitAnsiWidth(detail, safeWidth));\n}\n","import type { Component, OverlayHandle, OverlayOptions } from \"@earendil-works/pi-tui\";\nimport type { NormalizedPiStyleConfig } from \"../../domain/config-types.js\";\nimport type { StatusSnapshot } from \"../../domain/status.js\";\nimport { type ActiveTheme, type ResolvedTheme, resolveTheme } from \"../../domain/theme.js\";\nimport { fitAnsiWidth, truncateAnsi, visibleWidth } from \"../../shared/ansi.js\";\nimport { compactLogoHeader } from \"./logo.js\";\n\nexport type StartupReason = \"startup\" | \"reload\" | \"new\" | \"resume\" | \"fork\";\n\nexport interface StartupDetailItem {\n\treadonly kind: \"system\" | \"append\" | \"context\";\n\treadonly path: string;\n\treadonly words: number;\n\treadonly lines: number;\n}\n\nexport interface StartupToolItem {\n\treadonly source: string;\n\treadonly name: string;\n}\n\nexport interface StartupResources {\n\treadonly contextFiles?: number;\n\treadonly extensions?: number;\n\treadonly skills?: number;\n\treadonly prompts?: number;\n\treadonly tools?: number;\n\treadonly models?: number;\n\treadonly details?: readonly StartupDetailItem[];\n\treadonly toolDetails?: readonly StartupToolItem[];\n\treadonly error?: string;\n}\n\nexport interface StartupSnapshot extends StatusSnapshot {\n\treadonly reason: StartupReason;\n\treadonly project?: string | undefined;\n\treadonly startupProvider?: string | undefined;\n\treadonly resources?: StartupResources | undefined;\n\treadonly preset?: string | undefined;\n\treadonly compatibility?: string | undefined;\n}\n\nexport type StartupTheme = ActiveTheme;\n\nfunction activeThemeFromPi(theme: unknown): ActiveTheme {\n\tif (!theme || typeof theme !== \"object\") return {};\n\tconst candidate = theme as { fg?: (token: string, text?: string) => string; colors?: Record<string, string> };\n\treturn {\n\t\t...(candidate.colors ? { colors: candidate.colors } : {}),\n\t\t...(candidate.fg ? { fg: (color: string, text: string) => candidate.fg?.(color, text) ?? text } : {}),\n\t};\n}\n\nexport interface StartupHost {\n\tsetHeader?: (factory: ((tui: unknown, theme: unknown) => Component & { dispose?(): void }) | undefined) => void;\n\tsetWidget?: (key: string, content: unknown, options?: unknown) => void;\n\tcustom?: <T>(\n\t\tfactory: (\n\t\t\ttui: unknown,\n\t\t\ttheme: unknown,\n\t\t\tkeybindings: unknown,\n\t\t\tdone: (value: T) => void,\n\t\t) => Component & { dispose?(): void },\n\t\toptions?: { overlay?: boolean; overlayOptions?: OverlayOptions; onHandle?: (handle: OverlayHandle) => void },\n\t) => Promise<T>;\n\tonTerminalInput?: (handler: (...args: readonly unknown[]) => unknown) => () => void;\n\treadonly mode?: string;\n\treadonly hasUI?: boolean;\n\t/** Optional public-adapter capability used to avoid overwriting a later header owner. */\n\tgetHeaderFactory?: () => unknown;\n}\n\nexport interface StartupInstallation {\n\treadonly generation: number;\n\tupdate(snapshot: StartupSnapshot): void;\n\tdismiss(): void;\n\tconfigure(config: NormalizedPiStyleConfig): void;\n\tdispose(): void;\n}\n\nexport interface StartupInstallOptions {\n\thost: StartupHost;\n\tconfig: NormalizedPiStyleConfig;\n\tsnapshot: StartupSnapshot;\n\tgeneration: number;\n\trequestRender?: () => void;\n\ttimeoutMs?: number;\n\tisCurrent?: () => boolean;\n}\n\nexport const STARTUP_WIDGET_KEY = \"pi-style.startup\";\nconst owners = new WeakMap<object, Map<string, symbol>>();\n\nfunction ownerMap(host: object): Map<string, symbol> {\n\tlet map = owners.get(host);\n\tif (!map) {\n\t\tmap = new Map();\n\t\towners.set(host, map);\n\t}\n\treturn map;\n}\n\nfunction safeCall(fn: () => void): boolean {\n\ttry {\n\t\tfn();\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction shouldShow(reason: StartupReason, mode: \"off\" | \"compact\" | \"overlay\"): boolean {\n\tif (mode === \"off\") return false;\n\treturn reason === \"startup\" || reason === \"reload\" || reason === \"new\" || reason === \"resume\" || reason === \"fork\";\n}\n\nfunction overlayAllowed(reason: StartupReason): boolean {\n\treturn reason === \"startup\";\n}\n\nfunction resourceChipRows(resources: StartupResources | undefined): { label: string; count: number }[] {\n\tif (!resources) return [];\n\tconst rows: { label: string; count: number }[] = [];\n\tif (resources.contextFiles !== undefined) rows.push({ label: \"context\", count: resources.contextFiles });\n\tif (resources.extensions !== undefined) rows.push({ label: \"extensions\", count: resources.extensions });\n\tif (resources.skills !== undefined) rows.push({ label: \"skills\", count: resources.skills });\n\tif (resources.prompts !== undefined) rows.push({ label: \"prompts\", count: resources.prompts });\n\tif (resources.tools !== undefined) rows.push({ label: \"tools\", count: resources.tools });\n\tif (resources.models !== undefined) rows.push({ label: \"models\", count: resources.models });\n\treturn rows;\n}\n\nconst PANEL_SIDE_PADDING = 2;\nconst PANEL_MIN_WIDTH = 64;\nconst PANEL_OUTER_WIDTH = PANEL_SIDE_PADDING * 2 + 2;\n/** Panels render only when the surface is wide enough to keep the box intact. */\nconst MIN_PANELS_WIDTH = PANEL_MIN_WIDTH + PANEL_OUTER_WIDTH;\nconst RESOURCE_ROW_GAP = \" · \";\nconst CONTEXT_KIND_RANK: Record<StartupDetailItem[\"kind\"], number> = { system: 0, append: 1, context: 2 };\n\n/** `◆ Resources` summary chips. */\nfunction renderResourceChips(resolved: ResolvedTheme, resources: StartupResources | undefined): string {\n\tconst rows = resourceChipRows(resources);\n\tif (rows.length === 0) return \"\";\n\tconst marker = resolved.apply(\"accent\", \"◆ Resources\");\n\tconst chips = rows.map((row, index) => {\n\t\tconst label = resolved.apply(index === 0 ? \"text\" : \"muted\", row.label);\n\t\tconst count = resolved.apply(\"success\", String(row.count));\n\t\treturn `${label} ${count}`;\n\t});\n\treturn [marker, ...chips].join(resolved.apply(\"dim\", RESOURCE_ROW_GAP));\n}\n\nfunction sortedContextItems(items: readonly StartupDetailItem[]): StartupDetailItem[] {\n\treturn [...items].sort((a, b) => (CONTEXT_KIND_RANK[a.kind] ?? 9) - (CONTEXT_KIND_RANK[b.kind] ?? 9));\n}\n\nfunction renderPanelBorder(resolved: ResolvedTheme, left: string, right: string, panelWidth: number): string {\n\treturn resolved.apply(\"dim\", `${left}${\"─\".repeat(panelWidth + PANEL_SIDE_PADDING * 2)}${right}`);\n}\n\nfunction renderPanelLine(resolved: ResolvedTheme, content: string, panelWidth: number): string {\n\tconst sidePadding = \" \".repeat(PANEL_SIDE_PADDING);\n\tconst padding = \" \".repeat(Math.max(0, panelWidth - visibleWidth(content)));\n\treturn `${resolved.apply(\"dim\", \"│\")}${sidePadding}${content}${padding}${sidePadding}${resolved.apply(\"dim\", \"│\")}`;\n}\n\n/** Boxed System & Context table. */\nfunction renderSystemContextPanel(\n\tresolved: ResolvedTheme,\n\titems: readonly StartupDetailItem[],\n\tminTotalWidth: number,\n): string[] {\n\tconst sorted = sortedContextItems(items);\n\tconst titleLine = resolved.apply(\"accent\", \"System & Context\");\n\tif (sorted.length === 0) return [];\n\tconst typeHeader = \"Type\";\n\tconst pathHeader = \"Path\";\n\tconst metricLabel = \"Words/Lines\";\n\tconst typeWidth = Math.max(typeHeader.length, ...sorted.map((item) => visibleWidth(item.kind)));\n\tconst divider = resolved.apply(\"muted\", \" | \");\n\tconst dividerWidth = visibleWidth(divider);\n\tconst metricWidth = Math.max(metricLabel.length, ...sorted.map((item) => `${item.words}/${item.lines}`.length));\n\tconst fixedColumnsWidth = typeWidth + dividerWidth + dividerWidth + metricWidth;\n\tconst panelWidth = Math.max(PANEL_MIN_WIDTH, minTotalWidth - PANEL_OUTER_WIDTH, visibleWidth(titleLine));\n\tconst pathWidth = Math.max(pathHeader.length, panelWidth - fixedColumnsWidth);\n\tconst header = `${resolved.apply(\"text\", typeHeader.padEnd(typeWidth))}${divider}${resolved.apply(\n\t\t\"text\",\n\t\tpathHeader.padEnd(pathWidth),\n\t)}${divider}${resolved.apply(\"text\", metricLabel.padStart(metricWidth))}`;\n\tconst separator = `${resolved.apply(\"dim\", \"─\".repeat(typeWidth))}${divider}${resolved.apply(\n\t\t\"dim\",\n\t\t\"─\".repeat(pathWidth),\n\t)}${divider}${resolved.apply(\"dim\", \"─\".repeat(metricWidth))}`;\n\tconst lines = [\n\t\trenderPanelBorder(resolved, \"╭\", \"╮\", panelWidth),\n\t\trenderPanelLine(resolved, titleLine, panelWidth),\n\t\trenderPanelLine(resolved, header, panelWidth),\n\t\trenderPanelLine(resolved, separator, panelWidth),\n\t];\n\tfor (const item of sorted) {\n\t\tconst metric = `${item.words}/${item.lines}`;\n\t\tconst typePadding = \" \".repeat(Math.max(0, typeWidth - visibleWidth(item.kind)));\n\t\tconst path = fitAnsiWidth(item.path, pathWidth);\n\t\tconst pathPadding = \" \".repeat(Math.max(0, pathWidth - visibleWidth(path)));\n\t\tconst metricPadding = \" \".repeat(Math.max(0, metricWidth - visibleWidth(metric)));\n\t\tlines.push(\n\t\t\trenderPanelLine(\n\t\t\t\tresolved,\n\t\t\t\t`${resolved.apply(\"text\", item.kind)}${typePadding}${divider}${resolved.apply(\n\t\t\t\t\t\"text\",\n\t\t\t\t\tpath,\n\t\t\t\t)}${pathPadding}${divider}${metricPadding}${resolved.apply(\"text\", metric)}`,\n\t\t\t\tpanelWidth,\n\t\t\t),\n\t\t);\n\t}\n\tlines.push(renderPanelBorder(resolved, \"╰\", \"╯\", panelWidth));\n\treturn lines;\n}\n\nfunction groupToolDetails(tools: readonly StartupToolItem[]): { source: string; names: string[] }[] {\n\tconst groups = new Map<string, Set<string>>();\n\tfor (const tool of tools) {\n\t\tconst source = tool.source.trim() || \"extension\";\n\t\tconst name = tool.name.trim();\n\t\tif (!name) continue;\n\t\tlet names = groups.get(source);\n\t\tif (!names) {\n\t\t\tnames = new Set();\n\t\t\tgroups.set(source, names);\n\t\t}\n\t\tnames.add(name);\n\t}\n\treturn [...groups.entries()]\n\t\t.map(([source, names]) => ({ source, names: [...names].sort((a, b) => a.localeCompare(b)) }))\n\t\t.sort((a, b) => {\n\t\t\tif (a.source === \"core\") return -1;\n\t\t\tif (b.source === \"core\") return 1;\n\t\t\treturn a.source.localeCompare(b.source);\n\t\t});\n}\n\n/** Boxed Available Tools table. */\nfunction renderToolsPanel(resolved: ResolvedTheme, tools: readonly StartupToolItem[], minTotalWidth: number): string[] {\n\tconst groups = groupToolDetails(tools);\n\tif (groups.length === 0) return [];\n\tconst titleLine = resolved.apply(\"accent\", \"Available Tools\");\n\tconst sourceHeader = \"Source\";\n\tconst countHeader = \"Count\";\n\tconst toolsHeader = \"Tools\";\n\tconst countWidth = Math.max(countHeader.length, ...groups.map((group) => String(group.names.length).length));\n\tconst divider = resolved.apply(\"muted\", \" | \");\n\tconst dividerWidth = visibleWidth(divider);\n\tconst panelWidth = Math.max(PANEL_MIN_WIDTH, minTotalWidth - PANEL_OUTER_WIDTH, visibleWidth(titleLine));\n\tconst availableTextWidth = Math.max(\n\t\tsourceHeader.length + toolsHeader.length,\n\t\tpanelWidth - countWidth - dividerWidth * 2,\n\t);\n\tconst maxSourceWidth = Math.max(sourceHeader.length, ...groups.map((group) => visibleWidth(group.source)));\n\tconst sourceWidth = Math.min(maxSourceWidth, Math.max(sourceHeader.length, Math.floor(availableTextWidth * 0.28)));\n\tconst toolsWidth = Math.max(toolsHeader.length, availableTextWidth - sourceWidth);\n\tconst header = `${resolved.apply(\"text\", sourceHeader.padEnd(sourceWidth))}${divider}${resolved.apply(\n\t\t\"text\",\n\t\tcountHeader.padStart(countWidth),\n\t)}${divider}${resolved.apply(\"text\", toolsHeader.padEnd(toolsWidth))}`;\n\tconst separator = `${resolved.apply(\"dim\", \"─\".repeat(sourceWidth))}${divider}${resolved.apply(\n\t\t\"dim\",\n\t\t\"─\".repeat(countWidth),\n\t)}${divider}${resolved.apply(\"dim\", \"─\".repeat(toolsWidth))}`;\n\tconst lines = [\n\t\trenderPanelBorder(resolved, \"╭\", \"╮\", panelWidth),\n\t\trenderPanelLine(resolved, titleLine, panelWidth),\n\t\trenderPanelLine(resolved, header, panelWidth),\n\t\trenderPanelLine(resolved, separator, panelWidth),\n\t];\n\tfor (const group of groups) {\n\t\tconst count = String(group.names.length);\n\t\tconst toolList = fitAnsiWidth(group.names.join(\", \"), toolsWidth);\n\t\tconst source = fitAnsiWidth(group.source, sourceWidth);\n\t\tconst sourcePadding = \" \".repeat(Math.max(0, sourceWidth - visibleWidth(source)));\n\t\tconst countPadding = \" \".repeat(Math.max(0, countWidth - count.length));\n\t\tlines.push(\n\t\t\trenderPanelLine(\n\t\t\t\tresolved,\n\t\t\t\t`${resolved.apply(\"text\", source)}${sourcePadding}${divider}${countPadding}${resolved.apply(\n\t\t\t\t\t\"success\",\n\t\t\t\t\tcount,\n\t\t\t\t)}${divider}${resolved.apply(\"text\", toolList)}`,\n\t\t\t\tpanelWidth,\n\t\t\t),\n\t\t);\n\t}\n\tlines.push(renderPanelBorder(resolved, \"╰\", \"╯\", panelWidth));\n\treturn lines;\n}\n\n/** Left margin for the whole startup block so it does not touch the terminal edge. */\nconst STARTUP_INDENT = \" \";\n/** Blank rows above the block, separating it from the status line / terminal top. */\nconst STARTUP_PADDING_TOP = 2;\n/** Blank rows below the block, separating it from the editor / chat. */\nconst STARTUP_PADDING_BOTTOM = 2;\n\nfunction styledLines(\n\ttheme: ActiveTheme,\n\tconfig: NormalizedPiStyleConfig,\n\tsnapshot: StartupSnapshot,\n\toverlay: boolean,\n\twidth: number,\n): string[] {\n\tif (width <= 0 || config.startup.mode === \"off\") return [];\n\tconst resolved = resolveTheme(theme, config);\n\tconst lines: string[] = [];\n\tconst indentWidth = visibleWidth(STARTUP_INDENT);\n\tconst bodyWidth = Math.max(1, width - indentWidth);\n\tconst indent = (content: string): string => `${STARTUP_INDENT}${content}`;\n\n\t// Breathing room above the block (separates it from the status line / terminal top).\n\tlines.push(...Array.from({ length: STARTUP_PADDING_TOP }, () => \"\"));\n\n\tconst logoTitle = resolved.mode === \"ascii\" ? \"pi-style\" : `${resolved.glyph(\"pi\")} pi-style`;\n\tlines.push(\n\t\t...compactLogoHeader(\n\t\t\tresolved,\n\t\t\t[\n\t\t\t\tresolved.apply(\"accent\", logoTitle),\n\t\t\t\tresolved.apply(\"muted\", \"/ commands · ! bash\"),\n\t\t\t\tresolved.apply(\"success\", \"● ready\"),\n\t\t\t],\n\t\t\tbodyWidth,\n\t\t).map(indent),\n\t);\n\n\tconst info: string[] = [];\n\tif (config.startup.showResources) {\n\t\tconst chips = renderResourceChips(resolved, snapshot.resources);\n\t\tif (chips) info.push(chips);\n\t\tif (snapshot.resources?.error)\n\t\t\tinfo.push(resolved.apply(\"muted\", `resources unavailable · ${snapshot.resources.error}`));\n\t}\n\tif (info.length > 0) lines.push(\"\", ...info.map(indent));\n\n\tconst expanded = overlay || config.startup.alwaysExpanded;\n\tif (expanded && bodyWidth >= MIN_PANELS_WIDTH && config.startup.showResources) {\n\t\tconst contextItems = snapshot.resources?.details ?? [];\n\t\tconst toolItems = snapshot.resources?.toolDetails ?? [];\n\t\tif (contextItems.length > 0) {\n\t\t\tlines.push(\"\");\n\t\t\tlines.push(...renderSystemContextPanel(resolved, contextItems, bodyWidth).map(indent));\n\t\t}\n\t\tif (toolItems.length > 0) {\n\t\t\tlines.push(\"\");\n\t\t\tlines.push(...renderToolsPanel(resolved, toolItems, bodyWidth).map(indent));\n\t\t}\n\t}\n\n\t// Breathing room below the block (separates it from the editor / chat).\n\tlines.push(...Array.from({ length: STARTUP_PADDING_BOTTOM }, () => \"\"));\n\tif (overlay) lines.push(indent(resolved.apply(\"dim\", \"enter prompt to continue · esc dismiss\")));\n\n\treturn lines.map((line) => (visibleWidth(line) <= width ? line : truncateAnsi(line, width, \"\")));\n}\n\nclass StartupComponent implements Component {\n\tprivate snapshot: StartupSnapshot;\n\tprivate config: NormalizedPiStyleConfig;\n\tprivate readonly theme: ActiveTheme;\n\tprivate readonly overlay: boolean;\n\tprivate readonly requestRender: () => void;\n\n\tconstructor(\n\t\ttheme: ActiveTheme,\n\t\tconfig: NormalizedPiStyleConfig,\n\t\tsnapshot: StartupSnapshot,\n\t\toverlay: boolean,\n\t\trequestRender: () => void,\n\t) {\n\t\tthis.theme = theme;\n\t\tthis.config = config;\n\t\tthis.snapshot = snapshot;\n\t\tthis.overlay = overlay;\n\t\tthis.requestRender = requestRender;\n\t}\n\n\tsetSnapshot(snapshot: StartupSnapshot): void {\n\t\tthis.snapshot = snapshot;\n\t\tthis.invalidate();\n\t}\n\n\tsetConfig(config: NormalizedPiStyleConfig): void {\n\t\tthis.config = config;\n\t\tthis.invalidate();\n\t}\n\n\trender(width: number): string[] {\n\t\treturn styledLines(this.theme, this.config, this.snapshot, this.overlay, width);\n\t}\n\n\tinvalidate(): void {\n\t\tthis.requestRender();\n\t}\n}\n\nexport function renderStartup(\n\tsnapshot: StartupSnapshot,\n\tconfig: NormalizedPiStyleConfig,\n\ttheme: ActiveTheme,\n\twidth: number,\n\toverlay = false,\n): string[] {\n\treturn styledLines(theme, config, snapshot, overlay, width);\n}\n\nexport function installStartup(options: StartupInstallOptions): StartupInstallation | undefined {\n\tconst { host } = options;\n\tif (options.config.startup.mode === \"off\" || !shouldShow(options.snapshot.reason, options.config.startup.mode))\n\t\treturn undefined;\n\tif (!host.hasUI || host.mode !== \"tui\") return undefined;\n\tconst token = Symbol(\"pi-style.startup\");\n\tconst map = ownerMap(host as object);\n\tlet config = options.config;\n\tlet snapshot = options.snapshot;\n\tlet disposed = false;\n\tlet dismissed = false;\n\tlet headerInstalled = false;\n\tlet installedHeaderFactory: unknown;\n\tlet widgetInstalled = false;\n\tlet overlayHandle: OverlayHandle | undefined;\n\tlet removeInput: (() => void) | undefined;\n\tlet timeout: ReturnType<typeof setTimeout> | undefined;\n\tlet overlayDone: ((value: undefined) => void) | undefined;\n\tconst components: StartupComponent[] = [];\n\tconst timeoutMs = options.timeoutMs;\n\tconst component = (theme: unknown, isOverlay: boolean, tui: { requestRender?: () => void }) => {\n\t\tconst result = new StartupComponent(activeThemeFromPi(theme), config, snapshot, isOverlay, () => {\n\t\t\ttui.requestRender?.();\n\t\t\toptions.requestRender?.();\n\t\t});\n\t\tcomponents.push(result);\n\t\treturn result;\n\t};\n\tconst clearTimer = () => {\n\t\tif (timeout) clearTimeout(timeout);\n\t\ttimeout = undefined;\n\t};\n\tconst dismiss = () => {\n\t\tif (disposed || dismissed) return;\n\t\tdismissed = true;\n\t\tclearTimer();\n\t\toverlayHandle?.hide();\n\t\toverlayHandle = undefined;\n\t\toverlayDone?.(undefined);\n\t\toverlayDone = undefined;\n\t};\n\tconst clearHeader = () => {\n\t\tif (!headerInstalled || map.get(\"header\") !== token) return;\n\t\tconst current = host.getHeaderFactory?.();\n\t\tif (host.getHeaderFactory && current !== installedHeaderFactory) return;\n\t\tif (host.setHeader) safeCall(() => host.setHeader?.(undefined));\n\t\tmap.delete(\"header\");\n\t};\n\tconst clearWidget = () => {\n\t\tif (!widgetInstalled || map.get(STARTUP_WIDGET_KEY) !== token) return;\n\t\tif (host.setWidget) safeCall(() => host.setWidget?.(STARTUP_WIDGET_KEY, undefined));\n\t\tmap.delete(STARTUP_WIDGET_KEY);\n\t};\n\tconst mountCompact = (): boolean => {\n\t\tconst factory = (tui: unknown, theme: unknown) => component(theme, false, tui as { requestRender?: () => void });\n\t\t// Pi's public `setHeader` is the intended startup-header surface (\"shown at\n\t\t// startup, above chat\"). Prefer it so the startup renders at the top of the\n\t\t// terminal rather than inside the editor area. The injected ownership\n\t\t// adapter, when present, still guards against overwriting a later owner;\n\t\t// the widget remains the fallback when the header API is unavailable.\n\t\tlet currentHeader: unknown = Symbol(\"unreadable\");\n\t\tconst observable =\n\t\t\thost.getHeaderFactory &&\n\t\t\tsafeCall(() => {\n\t\t\t\tcurrentHeader = host.getHeaderFactory?.();\n\t\t\t});\n\t\tconst headerAvailable = host.setHeader !== undefined && (!observable || currentHeader === undefined);\n\t\tif (headerAvailable && safeCall(() => host.setHeader?.(factory))) {\n\t\t\tinstalledHeaderFactory = factory;\n\t\t\theaderInstalled = true;\n\t\t\tmap.set(\"header\", token);\n\t\t\treturn true;\n\t\t}\n\t\tif (host.setWidget && safeCall(() => host.setWidget?.(STARTUP_WIDGET_KEY, factory, { placement: \"aboveEditor\" }))) {\n\t\t\twidgetInstalled = true;\n\t\t\tmap.set(STARTUP_WIDGET_KEY, token);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t};\n\tconst mountOverlay = () => {\n\t\tif (!host.custom || !overlayAllowed(snapshot.reason)) {\n\t\t\tmountCompact();\n\t\t\treturn;\n\t\t}\n\t\tconst overlayOptions: OverlayOptions = {\n\t\t\tanchor: \"center\",\n\t\t\twidth: \"80%\",\n\t\t\tmaxHeight: \"60%\",\n\t\t\tminWidth: 40,\n\t\t\tvisible: (width, height) => width >= 40 && height >= 8,\n\t\t};\n\t\tvoid host\n\t\t\t.custom<undefined>(\n\t\t\t\t(tui, theme, _keybindings, done) => {\n\t\t\t\t\toverlayDone = done;\n\t\t\t\t\treturn component(theme, true, tui as { requestRender?: () => void });\n\t\t\t\t},\n\t\t\t\t{ overlay: true, overlayOptions, onHandle: (handle) => (overlayHandle = handle) },\n\t\t\t)\n\t\t\t.catch(() => {\n\t\t\t\tif (!disposed && !dismissed) {\n\t\t\t\t\tclearTimer();\n\t\t\t\t\tmountCompact();\n\t\t\t\t}\n\t\t\t});\n\t};\n\tconst installation: StartupInstallation = {\n\t\tgeneration: options.generation,\n\t\tupdate(next) {\n\t\t\tif (disposed || options.isCurrent?.() === false) return;\n\t\t\tsnapshot = next;\n\t\t\tfor (const item of components) item.setSnapshot(next);\n\t\t\toptions.requestRender?.();\n\t\t},\n\t\tdismiss,\n\t\tconfigure(next) {\n\t\t\tif (disposed || options.isCurrent?.() === false) return;\n\t\t\tconfig = next;\n\t\t\tfor (const item of components) item.setConfig(next);\n\t\t\tif (next.startup.mode === \"off\") {\n\t\t\t\tdismiss();\n\t\t\t\tclearHeader();\n\t\t\t\tclearWidget();\n\t\t\t}\n\t\t\toptions.requestRender?.();\n\t\t},\n\t\tdispose() {\n\t\t\tif (disposed) return;\n\t\t\tdismiss();\n\t\t\tdisposed = true;\n\t\t\tremoveInput?.();\n\t\t\tremoveInput = undefined;\n\t\t\tclearHeader();\n\t\t\tclearWidget();\n\t\t\tmap.delete(\"installation\");\n\t\t},\n\t};\n\tmap.set(\"installation\", token);\n\tremoveInput = host.onTerminalInput?.(() => dismiss());\n\tif (config.startup.mode === \"compact\" && !mountCompact()) {\n\t\tinstallation.dispose();\n\t\treturn undefined;\n\t}\n\tif (config.startup.mode === \"overlay\") mountOverlay();\n\tif (config.startup.mode === \"overlay\" && timeoutMs !== undefined && timeoutMs >= 0) {\n\t\ttimeout = setTimeout(() => dismiss(), timeoutMs);\n\t}\n\treturn installation;\n}\n","import type {\n\tSegmentContext,\n\tSegmentRenderResult,\n\tStatusLayout,\n\tStatusRenderResult,\n\tStatusSegment,\n\tStatusSegmentId,\n\tStatusSnapshot,\n} from \"../domain/status.js\";\nimport type { ResolvedTheme } from \"../domain/theme.js\";\nimport { truncateAnsi, visibleWidth } from \"../shared/ansi.js\";\n\nexport interface StatusRendererOptions {\n\treadonly separator?: string;\n\treadonly padding?: string;\n\treadonly segments: ReadonlyMap<StatusSegmentId, StatusSegment>;\n\treadonly theme: ResolvedTheme;\n\treadonly options?: Readonly<\n\t\tRecord<string, { readonly disabled?: boolean; readonly [key: string]: unknown } | undefined>\n\t>;\n}\n\ninterface Candidate {\n\treadonly id: StatusSegmentId;\n\treadonly segment: StatusSegment;\n\treadonly result: SegmentRenderResult;\n\tcontent: string;\n\tcompact: boolean;\n\tmoved: boolean;\n}\n\nfunction uniqueLayout(layout: StatusLayout): StatusLayout {\n\tconst seen = new Set<StatusSegmentId>();\n\tconst dedupe = (items: readonly StatusSegmentId[]) =>\n\t\titems.filter((id) => {\n\t\t\tif (seen.has(id)) return false;\n\t\t\tseen.add(id);\n\t\t\treturn true;\n\t\t});\n\treturn { left: dedupe(layout.left), right: dedupe(layout.right), secondary: dedupe(layout.secondary) };\n}\n\nfunction renderGroup(items: readonly Candidate[], separator: string, padding: string): string {\n\treturn items\n\t\t.map((item) => item.content)\n\t\t.filter(Boolean)\n\t\t.join(`${padding}${separator}${padding}`);\n}\n\nfunction widthOf(items: readonly Candidate[], separator: string, padding: string): number {\n\treturn visibleWidth(renderGroup(items, separator, padding));\n}\n\nexport function renderStatus(\n\tlayout: StatusLayout,\n\tsnapshot: StatusSnapshot,\n\twidth: number,\n\toptions: StatusRendererOptions,\n): StatusRenderResult {\n\tif (width <= 0) return { primary: \"\", lines: [], visibleSegments: [] };\n\tconst separator = options.separator ?? \"│\";\n\tconst padding = options.padding ?? \" \";\n\tconst normalized = uniqueLayout(layout);\n\tconst context: SegmentContext = { snapshot, theme: options.theme, options: options.options ?? {}, width };\n\tconst candidates = new Map<StatusSegmentId, Candidate>();\n\tfor (const id of [...normalized.left, ...normalized.right, ...normalized.secondary]) {\n\t\tif (candidates.has(id)) continue;\n\t\tconst segment = options.segments.get(id);\n\t\tif (!segment || options.options?.[id]?.disabled) continue;\n\t\ttry {\n\t\t\tconst result = segment.render(context);\n\t\t\tif (!result.visible || !result.content) continue;\n\t\t\tcandidates.set(id, { id, segment, result, content: result.content, compact: false, moved: false });\n\t\t} catch {\n\t\t\t// A broken optional segment must not break the status row.\n\t\t}\n\t}\n\tconst primary = [...normalized.left, ...normalized.right]\n\t\t.map((id) => candidates.get(id))\n\t\t.filter((candidate): candidate is Candidate => candidate !== undefined)\n\t\t.sort(\n\t\t\t(a, b) =>\n\t\t\t\t(b.segment.essential ? 1 : 0) - (a.segment.essential ? 1 : 0) ||\n\t\t\t\tb.segment.defaultPriority - a.segment.defaultPriority,\n\t\t);\n\tconst secondary = normalized.secondary\n\t\t.map((id) => candidates.get(id))\n\t\t.filter((candidate): candidate is Candidate => candidate !== undefined);\n\tconst visible: Candidate[] = [];\n\tconst overflow: Candidate[] = [];\n\tfor (const candidate of primary) {\n\t\tvisible.push(candidate);\n\t\tif (widthOf(visible, separator, padding) <= width) continue;\n\t\tif (candidate.result.compactContent && !candidate.compact) {\n\t\t\tcandidate.content = candidate.result.compactContent;\n\t\t\tcandidate.compact = true;\n\t\t\tif (widthOf(visible, separator, padding) <= width) continue;\n\t\t}\n\t\tvisible.pop();\n\t\tif (candidate.segment.overflow !== \"drop\" && candidate.segment.overflow !== \"primary\") {\n\t\t\tcandidate.moved = true;\n\t\t\toverflow.push(candidate);\n\t\t}\n\t}\n\tfor (const candidate of [...overflow].sort((a, b) => b.segment.defaultPriority - a.segment.defaultPriority))\n\t\tsecondary.push(candidate);\n\t// Right-aligned trailing group: layout.right candidates render flush to the\n\t// right edge, mirroring Pi's native footer (model • effort on the far right).\n\t// Group order follows the layout declaration; the priority sort above only\n\t// decides what drops on overflow.\n\tconst visibleIds = new Set(visible.map((candidate) => candidate.id));\n\tconst groupOf = (group: readonly StatusSegmentId[]) =>\n\t\tgroup\n\t\t\t.map((id) => candidates.get(id))\n\t\t\t.filter((candidate): candidate is Candidate => candidate !== undefined && visibleIds.has(candidate.id));\n\tconst leftVisible = groupOf(normalized.left);\n\tconst rightVisible = groupOf(normalized.right);\n\tconst leftText = renderGroup(leftVisible, separator, padding);\n\tconst rightText = renderGroup(rightVisible, separator, padding);\n\tlet primaryText: string;\n\tif (!rightText) {\n\t\tprimaryText = leftText;\n\t} else {\n\t\tconst core = leftText ? `${leftText}${padding}${separator}${padding}` : \"\";\n\t\tconst gap = Math.max(2, width - visibleWidth(core) - visibleWidth(rightText));\n\t\tprimaryText = `${core}${\" \".repeat(gap)}${rightText}`;\n\t}\n\tif (visibleWidth(primaryText) > width) primaryText = truncateAnsi(primaryText, width);\n\tconst secondaryVisible: Candidate[] = [];\n\tfor (const candidate of [...secondary].sort((a, b) => b.segment.defaultPriority - a.segment.defaultPriority)) {\n\t\tsecondaryVisible.push(candidate);\n\t\tif (widthOf(secondaryVisible, separator, padding) > width) secondaryVisible.pop();\n\t}\n\tconst secondaryText = renderGroup(secondaryVisible, separator, padding);\n\tconst lines = secondaryText ? [primaryText, secondaryText] : primaryText ? [primaryText] : [];\n\treturn {\n\t\tprimary: primaryText,\n\t\t...(secondaryText ? { secondary: secondaryText } : {}),\n\t\tlines,\n\t\tvisibleSegments: [...visible, ...secondaryVisible].map((candidate) => candidate.id),\n\t};\n}\n","import type { NormalizedPiStyleConfig } from \"../../domain/config-types.js\";\nimport { createBuiltinSegments, type SegmentContext, type StatusSnapshot } from \"../../domain/status.js\";\nimport { renderStatus } from \"../../domain/status-renderer.js\";\nimport { type ResolvedTheme, resolveTheme } from \"../../domain/theme.js\";\nimport { visibleWidth } from \"../../shared/ansi.js\";\n\nexport const PRIMARY_WIDGET_KEY = \"pi-style.status.primary\";\nexport const SECONDARY_WIDGET_KEY = \"pi-style.status.secondary\";\n\ntype WidgetPlacement = \"aboveEditor\" | \"belowEditor\";\ntype RenderComponent = { render(width: number): string[]; invalidate(): void; dispose?(): void };\ntype WidgetFactory = (tui: { requestRender?: () => void }, theme: ActivePiTheme) => RenderComponent;\n\n/** Read-only view of Pi's footer data provider, kept out of the domain layer. */\nexport interface FooterDataProviderView {\n\tgetGitBranch(): string | null;\n\tgetExtensionStatuses(): ReadonlyMap<string, string>;\n\tonBranchChange(callback: () => void): () => void;\n}\n\ntype FooterFactory = (\n\ttui: { requestRender?: (force?: boolean) => void },\n\t// The footer renders nothing, so the theme is intentionally untyped.\n\ttheme: unknown,\n\tfooterData: FooterDataProviderView,\n) => RenderComponent;\n\n/** Minimal structural view of Pi's theme, kept out of the domain layer. */\nexport interface ActivePiTheme {\n\tfg?: (token: string, text: string) => string;\n\tcolors?: Record<string, string>;\n}\n\nexport interface StatusLineWidgetHost {\n\tsetWidget(\n\t\tkey: string,\n\t\tcontent: string[] | WidgetFactory | undefined,\n\t\toptions?: { placement?: WidgetPlacement },\n\t): void;\n\t/** Replace the native Pi footer with a pi-style owned component; undefined restores it. */\n\tsetFooter(factory: FooterFactory | undefined): void;\n}\n\nexport interface StatusLineInstallation {\n\treadonly generation: number;\n\treadonly primaryKey: typeof PRIMARY_WIDGET_KEY;\n\treadonly secondaryKey: typeof SECONDARY_WIDGET_KEY;\n\tupdate(snapshot: StatusSnapshot): void;\n\tconfigure(config: NormalizedPiStyleConfig): void;\n\tdispose(): void;\n}\n\nexport interface StatusLineInstallOptions {\n\thost: StatusLineWidgetHost;\n\tconfig: NormalizedPiStyleConfig;\n\tgeneration: number;\n\tinitialSnapshot: StatusSnapshot;\n\tisCurrent?: () => boolean;\n\t/** Force a full terminal redraw (clear screen + scrollback) on the first footer mount. */\n\tclearOnStartup?: boolean;\n}\n\ninterface Ownership {\n\ttoken: symbol;\n\tgeneration: number;\n}\n\nconst ownership = new WeakMap<object, Map<string, Ownership>>();\nconst activeInstallations = new WeakMap<object, Map<number, StatusLineInstallation>>();\n\nfunction ownerMap(host: object): Map<string, Ownership> {\n\tlet map = ownership.get(host);\n\tif (!map) {\n\t\tmap = new Map();\n\t\townership.set(host, map);\n\t}\n\treturn map;\n}\nfunction installationMap(host: object): Map<number, StatusLineInstallation> {\n\tlet map = activeInstallations.get(host);\n\tif (!map) {\n\t\tmap = new Map();\n\t\tactiveInstallations.set(host, map);\n\t}\n\treturn map;\n}\nfunction safeWidget(\n\thost: StatusLineWidgetHost,\n\tkey: string,\n\tcontent: string[] | WidgetFactory | undefined,\n\tplacement?: WidgetPlacement,\n): boolean {\n\ttry {\n\t\thost.setWidget(key, content, placement ? { placement } : undefined);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\nfunction placementFor(config: NormalizedPiStyleConfig): WidgetPlacement {\n\treturn config.placement === \"below\" ? \"belowEditor\" : \"aboveEditor\";\n}\nfunction separatorsFor(config: NormalizedPiStyleConfig, theme: ResolvedTheme): string {\n\tconst style = config.statusLine.separator;\n\tif (style === \"powerline\") return theme.apply(\"separator\", theme.glyph(\"powerlineLeft\"));\n\tif (style === \"powerline-thin\" || style === \"\" || style === undefined) {\n\t\treturn theme.apply(\"separator\", theme.glyph(\"powerlineThinLeft\"));\n\t}\n\tif (style === \"none\") return \" \";\n\treturn theme.apply(\"separator\", style);\n}\n\nexport function installStatusLine(options: StatusLineInstallOptions): StatusLineInstallation {\n\tconst existing = installationMap(options.host).get(options.generation);\n\tif (existing) return existing;\n\tconst token = Symbol(\"pi-style.status-line\");\n\tconst owners = ownerMap(options.host);\n\tlet config = options.config;\n\tlet snapshot: StatusSnapshot = options.initialSnapshot;\n\tlet disposed = false;\n\tlet primaryComponent: RenderComponent | undefined;\n\tlet secondaryComponent: RenderComponent | undefined;\n\tlet footerData: FooterDataProviderView | undefined;\n\tlet footerOwner = false;\n\tlet footerUnsubscribe: (() => void) | undefined;\n\tlet clearedOnStartup = false;\n\tconst segments = new Map(createBuiltinSegments());\n\tfor (const item of config.statusLine.customItems) {\n\t\tif (!item.id || !item.statusKey) continue;\n\t\tsegments.set(item.id, {\n\t\t\tid: item.id,\n\t\t\tdefaultPriority: item.priority ?? 40,\n\t\t\toverflow: \"secondary\",\n\t\t\trender: ({ snapshot }: SegmentContext) => {\n\t\t\t\tconst status = snapshot.extensionStatuses?.find(\n\t\t\t\t\t(entry: { readonly key: string; readonly value: string }) => entry.key === item.statusKey,\n\t\t\t\t);\n\t\t\t\tif (!status) return { visible: false, content: \"\" };\n\t\t\t\treturn { visible: true, content: `${item.label ? `${item.label}:` : \"\"}${status.value}`, truncatable: true };\n\t\t\t},\n\t\t});\n\t}\n\n\tconst render = (activeTheme: ActivePiTheme, width: number, secondary: boolean): string[] => {\n\t\tif (width <= 0 || !config.enabled || !config.statusLine.enabled) return [];\n\t\tconst resolved = resolveTheme(\n\t\t\tactiveTheme.colors || activeTheme.fg\n\t\t\t\t? {\n\t\t\t\t\t\t...(activeTheme.colors ? { colors: activeTheme.colors } : {}),\n\t\t\t\t\t\t// Call through the theme instance so `this` binds correctly inside Pi's fg().\n\t\t\t\t\t\t...(activeTheme.fg ? { fg: (color: string, text: string) => activeTheme.fg?.(color, text) ?? text } : {}),\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\t\tconfig,\n\t\t);\n\t\tconst result = renderStatus(config.statusLine.layout, effectiveSnapshot(snapshot), width, {\n\t\t\tseparator: separatorsFor(config, resolved),\n\t\t\tsegments,\n\t\t\ttheme: resolved,\n\t\t\toptions: {\n\t\t\t\t...Object.fromEntries(config.statusLine.disabledSegments.map((id) => [id, { disabled: true }])),\n\t\t\t\tcontext_bar: { width: config.statusLine.contextBarWidth },\n\t\t\t},\n\t\t});\n\t\tconst lines = secondary ? result.lines.slice(1) : result.lines.slice(0, 1);\n\t\tconst rendered = lines.filter((line) => visibleWidth(line) <= width);\n\t\tif (!secondary && rendered.length > 0 && config.statusLine.bottomMargin > 0) {\n\t\t\t// Blank rows below the primary row keep the status line off the terminal edge.\n\t\t\treturn [...rendered, ...Array.from({ length: config.statusLine.bottomMargin }, () => \"\")];\n\t\t}\n\t\treturn rendered;\n\t};\n\t/** Merge authoritative native footer data (branch + extension statuses) into the snapshot. */\n\tconst effectiveSnapshot = (input: StatusSnapshot): StatusSnapshot => {\n\t\tif (!footerData) return input;\n\t\tconst statuses = footerData.getExtensionStatuses();\n\t\tconst extensionStatuses = statuses.size > 0 ? [...statuses].map(([key, value]) => ({ key, value })) : undefined;\n\t\tconst branch = footerData.getGitBranch();\n\t\tconst git = branch && input.git ? { ...input.git, branch } : input.git;\n\t\treturn {\n\t\t\t...input,\n\t\t\t...(extensionStatuses ? { extensionStatuses } : {}),\n\t\t\t...(git ? { git } : {}),\n\t\t};\n\t};\n\tconst releaseFooterData = (): void => {\n\t\tfooterUnsubscribe?.();\n\t\tfooterUnsubscribe = undefined;\n\t\tfooterData = undefined;\n\t};\n\tconst footerFactory: FooterFactory = (tui, _theme, data) => {\n\t\tfooterData = data;\n\t\tfooterUnsubscribe?.();\n\t\tfooterUnsubscribe = data.onBranchChange(() => {\n\t\t\tprimaryComponent?.invalidate();\n\t\t\tsecondaryComponent?.invalidate();\n\t\t\ttui.requestRender?.();\n\t\t});\n\t\tif (options.clearOnStartup && !clearedOnStartup) {\n\t\t\tclearedOnStartup = true;\n\t\t\t// Force a full redraw on the first frame: clears the screen and scrollback.\n\t\t\ttui.requestRender?.(true);\n\t\t}\n\t\treturn {\n\t\t\t// The native footer is replaced by an empty component; visible status lives in widgets.\n\t\t\trender() {\n\t\t\t\treturn [];\n\t\t\t},\n\t\t\tinvalidate() {\n\t\t\t\ttui.requestRender?.();\n\t\t\t},\n\t\t\tdispose() {\n\t\t\t\treleaseFooterData();\n\t\t\t},\n\t\t};\n\t};\n\tconst mountFooter = (): void => {\n\t\tif (disposed || options.isCurrent?.() === false) return;\n\t\tif (!config.enabled || !config.statusLine.enabled) {\n\t\t\tclearFooter();\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\toptions.host.setFooter(footerFactory);\n\t\t\tfooterOwner = true;\n\t\t} catch {\n\t\t\tfooterOwner = false;\n\t\t}\n\t};\n\tconst clearFooter = (): void => {\n\t\tif (!footerOwner) return;\n\t\tfooterOwner = false;\n\t\treleaseFooterData();\n\t\ttry {\n\t\t\toptions.host.setFooter(undefined);\n\t\t} catch {\n\t\t\t// Best-effort restore; cleanup must never throw.\n\t\t}\n\t};\n\tconst factory =\n\t\t(secondary: boolean): WidgetFactory =>\n\t\t(tui, theme) => {\n\t\t\tconst currentTheme = theme;\n\t\t\tconst component: RenderComponent = {\n\t\t\t\trender(width) {\n\t\t\t\t\tconst lines = render(currentTheme, width, secondary);\n\t\t\t\t\treturn lines;\n\t\t\t\t},\n\t\t\t\tinvalidate() {\n\t\t\t\t\t// Pi supplies a fresh theme to the factory on theme replacement. Do not retain\n\t\t\t\t\t// pre-rendered ANSI strings; the next render reads the current component theme.\n\t\t\t\t\tprimaryComponent = secondary ? primaryComponent : component;\n\t\t\t\t\tsecondaryComponent = secondary ? component : secondaryComponent;\n\t\t\t\t\tif (tui.requestRender) tui.requestRender();\n\t\t\t\t},\n\t\t\t\tdispose() {},\n\t\t\t};\n\t\t\tif (secondary) secondaryComponent = component;\n\t\t\telse primaryComponent = component;\n\t\t\treturn component;\n\t\t};\n\tconst claim = (key: string) => owners.set(key, { token, generation: options.generation });\n\tconst mount = () => {\n\t\tif (disposed || options.isCurrent?.() === false) return;\n\t\tif (!config.enabled || !config.statusLine.enabled) {\n\t\t\tclear(PRIMARY_WIDGET_KEY);\n\t\t\tclear(SECONDARY_WIDGET_KEY);\n\t\t\tclearFooter();\n\t\t\treturn;\n\t\t}\n\t\tif (safeWidget(options.host, PRIMARY_WIDGET_KEY, factory(false), placementFor(config))) claim(PRIMARY_WIDGET_KEY);\n\t\tif (safeWidget(options.host, SECONDARY_WIDGET_KEY, factory(true), \"belowEditor\")) claim(SECONDARY_WIDGET_KEY);\n\t\tmountFooter();\n\t};\n\tfunction clear(key: string): void {\n\t\tconst current = owners.get(key);\n\t\tif (current?.token !== token || current.generation !== options.generation) return;\n\t\tif (safeWidget(options.host, key, undefined)) owners.delete(key);\n\t}\n\tconst installation: StatusLineInstallation = {\n\t\tgeneration: options.generation,\n\t\tprimaryKey: PRIMARY_WIDGET_KEY,\n\t\tsecondaryKey: SECONDARY_WIDGET_KEY,\n\t\tupdate(next) {\n\t\t\tif (disposed || options.isCurrent?.() === false) return;\n\t\t\tsnapshot = next;\n\t\t\tprimaryComponent?.invalidate();\n\t\t\tsecondaryComponent?.invalidate();\n\t\t},\n\t\tconfigure(next) {\n\t\t\tif (disposed || options.isCurrent?.() === false) return;\n\t\t\tconst placementChanged = placementFor(next) !== placementFor(config);\n\t\t\tconst enabledChanged = next.enabled !== config.enabled || next.statusLine.enabled !== config.statusLine.enabled;\n\t\t\tconfig = next;\n\t\t\tif (placementChanged || enabledChanged) {\n\t\t\t\tclear(PRIMARY_WIDGET_KEY);\n\t\t\t\tclear(SECONDARY_WIDGET_KEY);\n\t\t\t\tclearFooter();\n\t\t\t\tprimaryComponent = undefined;\n\t\t\t\tsecondaryComponent = undefined;\n\t\t\t\tmount();\n\t\t\t} else {\n\t\t\t\tprimaryComponent?.invalidate();\n\t\t\t\tsecondaryComponent?.invalidate();\n\t\t\t}\n\t\t},\n\t\tdispose() {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\tclear(PRIMARY_WIDGET_KEY);\n\t\t\tclear(SECONDARY_WIDGET_KEY);\n\t\t\tclearFooter();\n\t\t\tinstallationMap(options.host).delete(options.generation);\n\t\t},\n\t};\n\tinstallationMap(options.host).set(options.generation, installation);\n\tmount();\n\treturn installation;\n}\n","export interface Disposable {\n\tdispose(): void | Promise<void>;\n}\n\nexport class DisposableStore implements Disposable {\n\tprivate readonly items: Disposable[] = [];\n\tprivate disposed = false;\n\tadd<T extends Disposable>(item: T): T {\n\t\tif (this.disposed) {\n\t\t\tvoid item.dispose();\n\t\t\treturn item;\n\t\t}\n\t\tthis.items.push(item);\n\t\treturn item;\n\t}\n\taddCallback(callback: () => void | Promise<void>): void {\n\t\tthis.add({ dispose: callback });\n\t}\n\tget size(): number {\n\t\treturn this.items.length;\n\t}\n\tasync dispose(): Promise<void> {\n\t\tif (this.disposed) return;\n\t\tthis.disposed = true;\n\t\tfor (let i = this.items.length - 1; i >= 0; i--) await this.items[i]?.dispose();\n\t\tthis.items.length = 0;\n\t}\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type {\n\tContextProvider,\n\tGitCommandResult,\n\tGitCommandRunner,\n\tGitProvider,\n\tUsageProvider,\n} from \"../domain/providers.js\";\nimport type { ContextSnapshot, GitSnapshot, UsageSnapshot } from \"../domain/status.js\";\n\nconst execFileAsync = promisify(execFile);\nconst EMPTY_USAGE: UsageSnapshot = Object.freeze({\n\tinputTokens: 0,\n\toutputTokens: 0,\n\tcacheReadTokens: 0,\n\tcacheWriteTokens: 0,\n\tstreaming: false,\n\tsubscriptionMode: \"unknown\",\n});\n\nexport class NodeGitCommandRunner implements GitCommandRunner {\n\tasync run(args: readonly string[], cwd: string, timeoutMs: number, signal?: AbortSignal): Promise<GitCommandResult> {\n\t\tif (signal?.aborted) return { stdout: \"\", stderr: \"git command aborted\", code: 1 };\n\t\ttry {\n\t\t\tconst result = await execFileAsync(\"git\", [...args], {\n\t\t\t\tcwd,\n\t\t\t\ttimeout: timeoutMs,\n\t\t\t\tmaxBuffer: 1024 * 1024,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t\treturn { stdout: result.stdout, stderr: result.stderr, code: 0 };\n\t\t} catch (error) {\n\t\t\tconst failure = error as { stdout?: string; stderr?: string; code?: number; signal?: string };\n\t\t\treturn {\n\t\t\t\tstdout: failure.stdout ?? \"\",\n\t\t\t\tstderr: failure.stderr ?? (failure.signal ? `git terminated by ${failure.signal}` : \"git command failed\"),\n\t\t\t\tcode: failure.code ?? 1,\n\t\t\t};\n\t\t}\n\t}\n}\n\ninterface GitEntry {\n\tvalue: GitSnapshot;\n\texpiresAt: number;\n\tretryAt: number;\n\tgeneration: number;\n\tpromise?: Promise<GitSnapshot>;\n\tcontroller?: AbortController;\n\tneedsRefresh?: boolean;\n\tresultReady: boolean;\n}\n\nexport interface GitProviderStats {\n\treadonly entries: number;\n\treadonly inFlight: number;\n\treadonly refreshes: number;\n\treadonly disposed: boolean;\n}\n\nexport interface GitProviderClock {\n\tnow(): number;\n}\n\nexport class CachedGitProvider implements GitProvider {\n\tprivate readonly cache = new Map<string, GitEntry>();\n\tprivate disposed = false;\n\tprivate refreshCount = 0;\n\tconstructor(\n\t\tprivate readonly runner: GitCommandRunner = new NodeGitCommandRunner(),\n\t\tprivate readonly ttlMs = 1000,\n\t\tprivate readonly timeoutMs = 800,\n\t\tprivate readonly maxBackoffMs = 5000,\n\t\tprivate readonly clock: GitProviderClock = { now: () => Date.now() },\n\t) {}\n\tget stats(): GitProviderStats {\n\t\treturn {\n\t\t\tentries: this.cache.size,\n\t\t\tinFlight: [...this.cache.values()].filter((entry) => entry.promise).length,\n\t\t\trefreshes: this.refreshCount,\n\t\t\tdisposed: this.disposed,\n\t\t};\n\t}\n\tasync get(cwd: string): Promise<GitSnapshot> {\n\t\tif (this.disposed) return unavailableGit(\"provider disposed\");\n\t\tconst now = this.clock.now();\n\t\tconst current = this.cache.get(cwd);\n\t\tif (current && current.expiresAt > now && !current.needsRefresh) return current.value;\n\t\tif (current?.promise) return current.resultReady ? current.value : current.promise;\n\t\tif (current && current.retryAt > now) return current.value;\n\t\tconst stale = current?.value;\n\t\tconst entry: GitEntry = current ?? {\n\t\t\tvalue: refreshingGit(),\n\t\t\texpiresAt: 0,\n\t\t\tretryAt: 0,\n\t\t\tgeneration: 0,\n\t\t\tresultReady: false,\n\t\t};\n\t\tentry.needsRefresh = false;\n\t\tentry.resultReady = Boolean(stale);\n\t\tentry.value = stale ? { ...stale, refreshing: true } : refreshingGit();\n\t\tentry.controller = new AbortController();\n\t\tentry.promise = this.refresh(cwd, entry, stale, entry.controller.signal);\n\t\tthis.cache.set(cwd, entry);\n\t\treturn stale ? entry.value : entry.promise;\n\t}\n\tinvalidate(cwd?: string): void {\n\t\tconst keys = cwd === undefined ? [...this.cache.keys()] : [cwd];\n\t\tfor (const key of keys) {\n\t\t\tconst entry = this.cache.get(key);\n\t\t\tif (!entry) continue;\n\t\t\tentry.generation++;\n\t\t\tentry.expiresAt = 0;\n\t\t\tif (entry.promise) entry.needsRefresh = true;\n\t\t\telse this.cache.delete(key);\n\t\t}\n\t}\n\tdispose(): void {\n\t\tif (this.disposed) return;\n\t\tthis.disposed = true;\n\t\tfor (const entry of this.cache.values()) entry.controller?.abort();\n\t\tthis.cache.clear();\n\t}\n\tprivate async refresh(\n\t\tcwd: string,\n\t\tentry: GitEntry,\n\t\tstale: GitSnapshot | undefined,\n\t\tsignal: AbortSignal,\n\t): Promise<GitSnapshot> {\n\t\tthis.refreshCount++;\n\t\tconst generation = entry.generation;\n\t\tlet value: GitSnapshot;\n\t\ttry {\n\t\t\tconst result = await this.runner.run([\"status\", \"--porcelain=v1\", \"--branch\"], cwd, this.timeoutMs, signal);\n\t\t\tif (result.code !== 0) {\n\t\t\t\tvalue = stale\n\t\t\t\t\t? { ...stale, refreshing: false, error: result.stderr.trim() || \"git status failed\" }\n\t\t\t\t\t: unavailableGit(result.stderr.trim() || \"git status failed\");\n\t\t\t} else value = parseGitStatus(result.stdout);\n\t\t} catch (error) {\n\t\t\tvalue = stale ? { ...stale, refreshing: false, error: String(error) } : unavailableGit(String(error));\n\t\t}\n\t\tif (this.disposed || this.cache.get(cwd) !== entry) return value;\n\t\tconst invalidated = entry.generation !== generation || entry.needsRefresh;\n\t\tdelete entry.promise;\n\t\tdelete entry.controller;\n\t\tentry.value = value;\n\t\tentry.resultReady = true;\n\t\tif (invalidated) {\n\t\t\tentry.needsRefresh = false;\n\t\t\tentry.expiresAt = 0;\n\t\t\tvoid this.get(cwd);\n\t\t\treturn value;\n\t\t}\n\t\tentry.retryAt = value.error ? this.clock.now() + Math.min(this.maxBackoffMs, Math.max(this.ttlMs, 100)) : 0;\n\t\tentry.expiresAt = this.clock.now() + this.ttlMs;\n\t\tif (entry.needsRefresh) {\n\t\t\tentry.needsRefresh = false;\n\t\t\tvoid this.get(cwd);\n\t\t}\n\t\treturn value;\n\t}\n}\n\nfunction refreshingGit(): GitSnapshot {\n\treturn Object.freeze({ available: false, branch: null, staged: 0, unstaged: 0, untracked: 0, refreshing: true });\n}\nfunction unavailableGit(error: string): GitSnapshot {\n\treturn Object.freeze({\n\t\tavailable: false,\n\t\tbranch: null,\n\t\tstaged: 0,\n\t\tunstaged: 0,\n\t\tuntracked: 0,\n\t\trefreshing: false,\n\t\terror,\n\t});\n}\nexport function parseGitStatus(output: string): GitSnapshot {\n\tconst lines = output.split(\"\\n\").filter(Boolean);\n\tconst header = lines.find((line) => line.startsWith(\"## \"))?.slice(3) ?? \"\";\n\tif (!header) return unavailableGit(\"not a git repository\");\n\tconst branch = header.split(\"...\")[0]?.replace(/^HEAD \\(no branch\\)$/, \"detached\") ?? null;\n\tlet staged = 0;\n\tlet unstaged = 0;\n\tlet untracked = 0;\n\tfor (const line of lines) {\n\t\tif (line.startsWith(\"## \")) continue;\n\t\tif (line.startsWith(\"??\")) {\n\t\t\tuntracked++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.length < 2) continue;\n\t\tif (line[0] !== \" \") staged++;\n\t\tif (line[1] !== \" \") unstaged++;\n\t}\n\tconst ahead = /\\[ahead (\\d+)\\]/.exec(header)?.[1];\n\tconst behind = /\\[behind (\\d+)\\]/.exec(header)?.[1];\n\treturn Object.freeze({\n\t\tavailable: true,\n\t\tbranch: branch || null,\n\t\tstaged,\n\t\tunstaged,\n\t\tuntracked,\n\t\t...(ahead ? { ahead: Number(ahead) } : {}),\n\t\t...(behind ? { behind: Number(behind) } : {}),\n\t\trefreshing: false,\n\t});\n}\n\nexport class InMemoryUsageProvider implements UsageProvider {\n\tprivate readonly values = new Map<string, UsageSnapshot>();\n\tprivate readonly events = new Map<string, Set<string>>();\n\tprivate readonly finalized = new Map<string, Set<string>>();\n\tget(sessionId: string): UsageSnapshot {\n\t\treturn this.values.get(sessionId) ?? EMPTY_USAGE;\n\t}\n\trecord(\n\t\tsessionId: string,\n\t\tusage: Partial<UsageSnapshot>,\n\t\toptions: { eventId?: string; finalized?: boolean } = {},\n\t): void {\n\t\tif (options.eventId) {\n\t\t\tconst ids = this.events.get(sessionId) ?? new Set<string>();\n\t\t\tconst finalized = this.finalized.get(sessionId) ?? new Set<string>();\n\t\t\tif (finalized.has(options.eventId) || (ids.has(options.eventId) && !options.finalized)) return;\n\t\t\tids.add(options.eventId);\n\t\t\tthis.events.set(sessionId, ids);\n\t\t\tif (options.finalized) {\n\t\t\t\tfinalized.add(options.eventId);\n\t\t\t\tthis.finalized.set(sessionId, finalized);\n\t\t\t}\n\t\t}\n\t\tconst current = this.get(sessionId);\n\t\tconst next = {\n\t\t\t...current,\n\t\t\t...usage,\n\t\t\tstreaming: options.finalized ? false : (usage.streaming ?? current.streaming),\n\t\t};\n\t\tthis.values.set(sessionId, Object.freeze(next));\n\t}\n\treset(sessionId?: string): void {\n\t\tif (sessionId === undefined) {\n\t\t\tthis.values.clear();\n\t\t\tthis.events.clear();\n\t\t\tthis.finalized.clear();\n\t\t\treturn;\n\t\t}\n\t\tthis.values.delete(sessionId);\n\t\tthis.events.delete(sessionId);\n\t\tthis.finalized.delete(sessionId);\n\t}\n}\n\nexport class InMemoryContextProvider implements ContextProvider {\n\tprivate readonly values = new Map<string, ContextSnapshot>();\n\tget(sessionId: string): ContextSnapshot | undefined {\n\t\treturn this.values.get(sessionId);\n\t}\n\tset(sessionId: string, context: ContextSnapshot): void {\n\t\tthis.values.set(sessionId, Object.freeze({ ...context }));\n\t}\n\tclear(sessionId?: string): void {\n\t\tif (sessionId === undefined) this.values.clear();\n\t\telse this.values.delete(sessionId);\n\t}\n}\n","export type UpdateClass = \"immediate\" | \"coalesced\" | \"deferred\" | \"delayed-retry\";\nexport interface SchedulerHost {\n\trequestRender(): void;\n}\n\nexport class RenderScheduler {\n\tprivate stopped = false;\n\tprivate immediateQueued = false;\n\tprivate coalescedTimer: ReturnType<typeof setTimeout> | undefined;\n\tprivate deferredTimer: ReturnType<typeof setTimeout> | undefined;\n\tprivate retryTimer: ReturnType<typeof setTimeout> | undefined;\n\tconstructor(\n\t\tprivate readonly host: SchedulerHost,\n\t\tprivate readonly generation: number,\n\t\tprivate readonly isCurrent: (generation: number) => boolean = (current) => current === this.generation,\n\t) {}\n\tschedule(kind: UpdateClass): void {\n\t\tif (this.stopped || !this.isCurrent(this.generation)) return;\n\t\tif (kind === \"immediate\") {\n\t\t\tif (this.immediateQueued) return;\n\t\t\tthis.immediateQueued = true;\n\t\t\tqueueMicrotask(() => {\n\t\t\t\tthis.immediateQueued = false;\n\t\t\t\tthis.render();\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tconst target = kind === \"coalesced\" ? \"coalescedTimer\" : kind === \"deferred\" ? \"deferredTimer\" : \"retryTimer\";\n\t\tif (this[target] !== undefined) return;\n\t\tconst delay = kind === \"coalesced\" ? 16 : kind === \"deferred\" ? 50 : 100;\n\t\tthis[target] = setTimeout(() => {\n\t\t\tthis[target] = undefined;\n\t\t\tthis.render();\n\t\t}, delay);\n\t}\n\tprivate render(): void {\n\t\tif (!this.stopped && this.isCurrent(this.generation)) this.host.requestRender();\n\t}\n\tcancel(): void {\n\t\tthis.stopped = true;\n\t\tif (this.coalescedTimer !== undefined) clearTimeout(this.coalescedTimer);\n\t\tif (this.deferredTimer !== undefined) clearTimeout(this.deferredTimer);\n\t\tif (this.retryTimer !== undefined) clearTimeout(this.retryTimer);\n\t\tthis.coalescedTimer = undefined;\n\t\tthis.deferredTimer = undefined;\n\t\tthis.retryTimer = undefined;\n\t}\n}\n","import type { StatusSnapshot } from \"../domain/status.js\";\n\nexport interface UiSnapshot extends StatusSnapshot {\n\treadonly revision: number;\n\treadonly generation: number;\n}\n\nexport function createSnapshot(generation: number, revision = 0, values: StatusSnapshot = {}): UiSnapshot {\n\treturn Object.freeze({ generation, revision, ...values });\n}\n\nexport function replaceSnapshot(current: UiSnapshot, generation: number, values: StatusSnapshot): UiSnapshot {\n\tif (current.generation !== generation) return current;\n\treturn createSnapshot(generation, current.revision + 1, values);\n}\n","import type { ExtensionContext, ExtensionUIContext } from \"@earendil-works/pi-coding-agent\";\nimport { diffConfig } from \"../domain/config-diff.js\";\nimport type { NormalizedPiStyleConfig } from \"../domain/config-types.js\";\nimport type { GitCommandRunner } from \"../domain/providers.js\";\nimport type { StatusSnapshot } from \"../domain/status.js\";\nimport { normalizeThinkingLevel } from \"../domain/status.js\";\nimport { installEditor } from \"../features/editor/index.js\";\nimport {\n\tinstallStartup,\n\ttype StartupHost,\n\ttype StartupReason,\n\ttype StartupResources,\n\ttype StartupSnapshot,\n} from \"../features/startup/index.js\";\nimport { installStatusLine } from \"../features/status-line/index.js\";\nimport { DisposableStore } from \"../shared/disposable-store.js\";\nimport { CachedGitProvider, InMemoryContextProvider, InMemoryUsageProvider } from \"./providers.js\";\nimport { RenderScheduler } from \"./render-scheduler.js\";\nimport { createSnapshot, replaceSnapshot, type UiSnapshot } from \"./snapshot.js\";\n\nexport interface RuntimeInstallationState {\n\treadonly status: \"installed\" | \"disabled\" | \"failed\";\n\treadonly editor: \"installed\" | \"preserved\" | \"disabled\" | \"failed\";\n\treadonly startup: \"installed\" | \"disabled\" | \"failed\";\n}\n\nexport interface PiStyleRuntime {\n\tgeneration: number;\n\treadonly providerIdentity: { git: object; context: object; usage: object };\n\treadonly installationState: RuntimeInstallationState;\n\tmode: ExtensionContext[\"mode\"];\n\thasUI: boolean;\n\tdisposed: boolean;\n\tsnapshot: UiSnapshot;\n\tdisposables: DisposableStore;\n\tscheduler: RenderScheduler;\n\tupdate(values: StatusSnapshot): void;\n\tupdateStartupResources(resources: StartupResources): void;\n\tdismissStartup(): void;\n\tinvalidateGit(): void;\n\tconfigure(config: NormalizedPiStyleConfig): void;\n\tdispose(): void;\n}\n\nexport interface RuntimeHost {\n\treadonly mode: ExtensionContext[\"mode\"];\n\treadonly hasUI: boolean;\n\treadonly ui?: ExtensionUIContext;\n\treadonly cwd?: string;\n\treadonly model?: { id?: string; name?: string; provider?: string; reasoning?: boolean } | undefined;\n\treadonly thinkingLevel?: string | undefined;\n\treadonly config: NormalizedPiStyleConfig;\n\treadonly startupReason?: StartupReason;\n\treadonly provider?: string;\n\treadonly requestRender?: () => void;\n\treadonly resources?: StartupResources;\n\treadonly extensionStatusProvider?: () => readonly import(\"../domain/status.js\").ExtensionStatus[] | undefined;\n\treadonly gitRunner?: GitCommandRunner;\n\tgetContextUsage?:\n\t\t| (() => { tokens: number | null; contextWindow: number; percent: number | null } | undefined)\n\t\t| undefined;\n}\n\nexport function createPiStyleRuntime(\n\thost: RuntimeHost,\n\tgeneration: number,\n\trequestRender: () => void = () => {},\n): PiStyleRuntime {\n\tlet disposed = false;\n\tconst extensionStatuses = (): readonly import(\"../domain/status.js\").ExtensionStatus[] | undefined => {\n\t\tif (!host.extensionStatusProvider) return undefined;\n\t\ttry {\n\t\t\treturn host.extensionStatusProvider();\n\t\t} catch {\n\t\t\thost.ui?.notify?.(\"pi-style extension statuses unavailable; provider recovery required\", \"warning\");\n\t\t\treturn [];\n\t\t}\n\t};\n\tlet currentConfig = host.config;\n\tconst disposables = new DisposableStore();\n\tconst scheduler = new RenderScheduler({ requestRender }, generation, () => !disposed);\n\tconst git = new CachedGitProvider(host.gitRunner);\n\tconst contextProvider = new InMemoryContextProvider();\n\tconst usageProvider = new InMemoryUsageProvider();\n\tconst usage = host.getContextUsage?.();\n\tconst initialStatuses = extensionStatuses();\n\tconst initialValues = {\n\t\t...(initialStatuses ? { extensionStatuses: initialStatuses } : {}),\n\t\t...(host.model?.name || host.model?.id ? { model: host.model.name ?? host.model.id } : {}),\n\t\t...(host.model?.provider ? { provider: host.model.provider } : {}),\n\t\t...(host.model?.reasoning !== undefined ? { reasoning: host.model.reasoning } : {}),\n\t\t...(host.thinkingLevel ? { thinkingLevel: normalizeThinkingLevel(host.thinkingLevel) } : {}),\n\t\t...(host.cwd ? { cwd: host.cwd } : {}),\n\t\t...(usage\n\t\t\t? {\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\t...(usage.tokens !== null ? { currentTokens: usage.tokens } : {}),\n\t\t\t\t\t\twindowTokens: usage.contextWindow,\n\t\t\t\t\t\t...(usage.percent !== null ? { percent: usage.percent } : {}),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n\tlet currentSnapshot = createSnapshot(generation, 0, initialValues);\n\tlet statusLine: ReturnType<typeof installStatusLine> | undefined;\n\tlet editor: ReturnType<typeof installEditor> | undefined;\n\tlet startup: ReturnType<typeof installStartup> | undefined;\n\tlet installationState: RuntimeInstallationState = {\n\t\tstatus: \"disabled\",\n\t\teditor: \"disabled\",\n\t\tstartup: \"disabled\",\n\t};\n\tconst startupSnapshot = (config: NormalizedPiStyleConfig): StartupSnapshot => ({\n\t\t...currentSnapshot,\n\t\treason: host.startupReason ?? \"startup\",\n\t\t...(host.provider ? { startupProvider: host.provider } : {}),\n\t\t...(host.cwd ? { project: host.cwd.split(/[\\\\/]/).filter(Boolean).at(-1) } : {}),\n\t\tpreset: config.preset,\n\t\t...(host.resources ? { resources: host.resources } : {}),\n\t});\n\tconst installStatus = () => {\n\t\tif (!host.hasUI || host.mode !== \"tui\" || !host.ui || !currentConfig.enabled || !currentConfig.statusLine.enabled) {\n\t\t\tinstallationState = { ...installationState, status: \"disabled\" };\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tstatusLine = installStatusLine({\n\t\t\t\thost: host.ui,\n\t\t\t\tconfig: currentConfig,\n\t\t\t\tgeneration,\n\t\t\t\tinitialSnapshot: currentSnapshot,\n\t\t\t\tisCurrent: () => !disposed,\n\t\t\t\tclearOnStartup: host.startupReason === \"startup\",\n\t\t\t});\n\t\t\tif (statusLine) {\n\t\t\t\tdisposables.add(statusLine);\n\t\t\t\tinstallationState = { ...installationState, status: \"installed\" };\n\t\t\t} else installationState = { ...installationState, status: \"failed\" };\n\t\t} catch (error) {\n\t\t\thost.ui.notify?.(\n\t\t\t\t`pi-style status unavailable: ${error instanceof Error ? error.message : \"installation failed\"}`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\tstatusLine = undefined;\n\t\t\tinstallationState = { ...installationState, status: \"failed\" };\n\t\t}\n\t};\n\tconst installEditorFeature = () => {\n\t\tif (!host.hasUI || host.mode !== \"tui\" || !host.ui || !currentConfig.enabled || !currentConfig.editor.enabled) {\n\t\t\tinstallationState = { ...installationState, editor: \"disabled\" };\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\teditor = installEditor({\n\t\t\t\thost: host.ui,\n\t\t\t\tconfig: currentConfig,\n\t\t\t\tgeneration,\n\t\t\t\tinitialSnapshot: currentSnapshot,\n\t\t\t\tisCurrent: () => !disposed,\n\t\t\t});\n\t\t\tif (editor) {\n\t\t\t\tdisposables.add(editor);\n\t\t\t\tinstallationState = { ...installationState, editor: editor.preservedPrevious ? \"preserved\" : \"installed\" };\n\t\t\t} else installationState = { ...installationState, editor: \"failed\" };\n\t\t} catch (error) {\n\t\t\thost.ui.notify?.(\n\t\t\t\t`pi-style editor unavailable: ${error instanceof Error ? error.message : \"installation failed\"}`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\teditor = undefined;\n\t\t\tinstallationState = { ...installationState, editor: \"failed\" };\n\t\t}\n\t};\n\tconst installStartupFeature = () => {\n\t\tif (\n\t\t\t!host.hasUI ||\n\t\t\thost.mode !== \"tui\" ||\n\t\t\t!host.ui ||\n\t\t\t!currentConfig.enabled ||\n\t\t\tcurrentConfig.startup.mode === \"off\"\n\t\t) {\n\t\t\tinstallationState = { ...installationState, startup: \"disabled\" };\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tstartup = installStartup({\n\t\t\t\thost: { ...(host.ui as unknown as StartupHost), mode: host.mode, hasUI: host.hasUI },\n\t\t\t\tconfig: currentConfig,\n\t\t\t\tsnapshot: startupSnapshot(currentConfig),\n\t\t\t\tgeneration,\n\t\t\t\trequestRender,\n\t\t\t\ttimeoutMs: 3000,\n\t\t\t\tisCurrent: () => !disposed,\n\t\t\t});\n\t\t\tif (startup) {\n\t\t\t\tdisposables.add(startup);\n\t\t\t\tinstallationState = { ...installationState, startup: \"installed\" };\n\t\t\t} else installationState = { ...installationState, startup: \"failed\" };\n\t\t} catch (error) {\n\t\t\thost.ui.notify?.(\n\t\t\t\t`pi-style startup unavailable: ${error instanceof Error ? error.message : \"installation failed\"}`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\tstartup = undefined;\n\t\t\tinstallationState = { ...installationState, startup: \"failed\" };\n\t\t}\n\t};\n\tconst disposeFeature = (label: string, dispose: (() => void) | undefined): void => {\n\t\tif (!dispose) return;\n\t\ttry {\n\t\t\tdispose();\n\t\t} catch (error) {\n\t\t\thost.ui?.notify?.(`pi-style ${label} cleanup failed; preserving the current owner`, \"warning\");\n\t\t\tvoid error;\n\t\t}\n\t};\n\tconst disposeStatus = () => {\n\t\tdisposeFeature(\"status\", statusLine?.dispose);\n\t\tstatusLine = undefined;\n\t\tinstallationState = { ...installationState, status: \"disabled\" };\n\t};\n\tconst disposeEditor = () => {\n\t\tdisposeFeature(\"editor\", editor?.dispose);\n\t\teditor = undefined;\n\t\tinstallationState = { ...installationState, editor: \"disabled\" };\n\t};\n\tconst disposeStartup = () => {\n\t\tdisposeFeature(\"startup\", startup?.dispose);\n\t\tstartup = undefined;\n\t\tinstallationState = { ...installationState, startup: \"disabled\" };\n\t};\n\tinstallStatus();\n\tinstallEditorFeature();\n\tinstallStartupFeature();\n\tif (host.cwd && currentConfig.enabled && currentConfig.statusLine.enabled) {\n\t\tvoid git.get(host.cwd).then((value) => {\n\t\t\tif (disposed) return;\n\t\t\tcurrentSnapshot = replaceSnapshot(currentSnapshot, generation, { ...currentSnapshot, git: value });\n\t\t\tstatusLine?.update(currentSnapshot);\n\t\t\teditor?.update(currentSnapshot);\n\t\t\tstartup?.update({\n\t\t\t\t...currentSnapshot,\n\t\t\t\treason: host.startupReason ?? \"startup\",\n\t\t\t\t...(host.provider ? { startupProvider: host.provider } : {}),\n\t\t\t\t...(host.cwd ? { project: host.cwd.split(/[\\\\/]/).filter(Boolean).at(-1) } : {}),\n\t\t\t\tpreset: currentConfig.preset,\n\t\t\t\t...(host.resources ? { resources: host.resources } : {}),\n\t\t\t});\n\t\t\trequestRender();\n\t\t});\n\t}\n\tif (usage) {\n\t\tcontextProvider.set(\"active\", {\n\t\t\t...(usage.tokens !== null ? { currentTokens: usage.tokens } : {}),\n\t\t\twindowTokens: usage.contextWindow,\n\t\t\t...(usage.percent !== null ? { percent: usage.percent } : {}),\n\t\t});\n\t}\n\treturn {\n\t\tgeneration,\n\t\tproviderIdentity: { git, context: contextProvider, usage: usageProvider },\n\t\tget installationState() {\n\t\t\treturn installationState;\n\t\t},\n\t\tmode: host.mode,\n\t\thasUI: host.hasUI,\n\t\tsnapshot: currentSnapshot,\n\t\tdisposables,\n\t\tscheduler,\n\t\tupdateStartupResources(resources) {\n\t\t\tif (disposed) return;\n\t\t\tstartup?.update({\n\t\t\t\t...currentSnapshot,\n\t\t\t\treason: host.startupReason ?? \"startup\",\n\t\t\t\t...(host.provider ? { startupProvider: host.provider } : {}),\n\t\t\t\t...(host.cwd ? { project: host.cwd.split(/[\\\\/]/).filter(Boolean).at(-1) } : {}),\n\t\t\t\tpreset: currentConfig.preset,\n\t\t\t\tresources,\n\t\t\t});\n\t\t\trequestRender();\n\t\t},\n\t\tdismissStartup() {\n\t\t\tstartup?.dismiss();\n\t\t},\n\t\tupdate(values) {\n\t\t\tif (disposed) return;\n\t\t\tconst liveUsage = host.getContextUsage?.();\n\t\t\tconst context = liveUsage\n\t\t\t\t? {\n\t\t\t\t\t\t...(liveUsage.tokens !== null ? { currentTokens: liveUsage.tokens } : {}),\n\t\t\t\t\t\twindowTokens: liveUsage.contextWindow,\n\t\t\t\t\t\t...(liveUsage.percent !== null ? { percent: liveUsage.percent } : {}),\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\t\t\tconst statuses = extensionStatuses();\n\t\t\tcurrentSnapshot = replaceSnapshot(currentSnapshot, generation, {\n\t\t\t\t...currentSnapshot,\n\t\t\t\t...values,\n\t\t\t\t...(context ? { context } : {}),\n\t\t\t\t...(statuses ? { extensionStatuses: statuses } : {}),\n\t\t\t});\n\t\t\tstatusLine?.update(currentSnapshot);\n\t\t\teditor?.update(currentSnapshot);\n\t\t\tstartup?.update({\n\t\t\t\t...currentSnapshot,\n\t\t\t\treason: host.startupReason ?? \"startup\",\n\t\t\t\t...(host.provider ? { startupProvider: host.provider } : {}),\n\t\t\t\t...(host.cwd ? { project: host.cwd.split(/[\\\\/]/).filter(Boolean).at(-1) } : {}),\n\t\t\t\tpreset: currentConfig.preset,\n\t\t\t\t...(host.resources ? { resources: host.resources } : {}),\n\t\t\t});\n\t\t},\n\t\tconfigure(nextConfig) {\n\t\t\tif (disposed) return;\n\t\t\tconst previous = currentConfig;\n\t\t\tconst impactPlan = diffConfig(previous, nextConfig);\n\t\t\tif (impactPlan.impacts.length === 0) return;\n\t\t\tcurrentConfig = nextConfig;\n\t\t\tconst statusChanged =\n\t\t\t\tJSON.stringify(previous.statusLine) !== JSON.stringify(nextConfig.statusLine) ||\n\t\t\t\tprevious.placement !== nextConfig.placement ||\n\t\t\t\tprevious.enabled !== nextConfig.enabled;\n\t\t\tconst editorChanged =\n\t\t\t\tJSON.stringify(previous.editor) !== JSON.stringify(nextConfig.editor) ||\n\t\t\t\tprevious.enabled !== nextConfig.enabled;\n\t\t\tconst startupChanged =\n\t\t\t\tJSON.stringify(previous.startup) !== JSON.stringify(nextConfig.startup) ||\n\t\t\t\tprevious.enabled !== nextConfig.enabled;\n\t\t\tif (statusChanged) {\n\t\t\t\tdisposeStatus();\n\t\t\t\tcurrentConfig = nextConfig;\n\t\t\t\tinstallStatus();\n\t\t\t}\n\t\t\tif (editorChanged) {\n\t\t\t\tdisposeEditor();\n\t\t\t\tcurrentConfig = nextConfig;\n\t\t\t\tinstallEditorFeature();\n\t\t\t}\n\t\t\tif (startupChanged) {\n\t\t\t\tdisposeStartup();\n\t\t\t\tcurrentConfig = nextConfig;\n\t\t\t\tinstallStartupFeature();\n\t\t\t}\n\t\t\tstatusLine?.configure(nextConfig);\n\t\t\teditor?.configure(nextConfig);\n\t\t\tstartup?.configure(nextConfig);\n\t\t},\n\t\tinvalidateGit() {\n\t\t\tif (disposed || !host.cwd || !currentConfig.enabled || !currentConfig.statusLine.enabled) return;\n\t\t\tgit.invalidate(host.cwd);\n\t\t\tvoid git.get(host.cwd).then((value) => {\n\t\t\t\tif (disposed) return;\n\t\t\t\tcurrentSnapshot = replaceSnapshot(currentSnapshot, generation, { ...currentSnapshot, git: value });\n\t\t\t\tstatusLine?.update(currentSnapshot);\n\t\t\t\teditor?.update(currentSnapshot);\n\t\t\t\tstartup?.update({\n\t\t\t\t\t...currentSnapshot,\n\t\t\t\t\treason: host.startupReason ?? \"startup\",\n\t\t\t\t\t...(host.provider ? { startupProvider: host.provider } : {}),\n\t\t\t\t\t...(host.cwd ? { project: host.cwd.split(/[\\\\/]/).filter(Boolean).at(-1) } : {}),\n\t\t\t\t\tpreset: currentConfig.preset,\n\t\t\t\t});\n\t\t\t\trequestRender();\n\t\t\t});\n\t\t},\n\t\tget disposed() {\n\t\t\treturn disposed;\n\t\t},\n\t\tdispose() {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\tscheduler.cancel();\n\t\t\t// UI surfaces are restored synchronously so teardown is deterministic;\n\t\t\t// the store then disposes the (already disposed) feature instances idempotently.\n\t\t\tdisposeStatus();\n\t\t\tdisposeEditor();\n\t\t\tdisposeStartup();\n\t\t\tgit.dispose();\n\t\t\tcontextProvider.clear();\n\t\t\tusageProvider.reset();\n\t\t\tvoid disposables.dispose();\n\t\t},\n\t};\n}\n\nexport class PiStyleRuntimeController {\n\tprivate activeRuntime: PiStyleRuntime | undefined;\n\tprivate nextGeneration = 0;\n\n\tstart(ctx: RuntimeHost): PiStyleRuntime {\n\t\tthis.stop();\n\t\tthis.activeRuntime = createPiStyleRuntime(ctx, ++this.nextGeneration);\n\t\treturn this.activeRuntime;\n\t}\n\n\tstop(): void {\n\t\tthis.activeRuntime?.dispose();\n\t\tthis.activeRuntime = undefined;\n\t}\n\n\tget current(): PiStyleRuntime | undefined {\n\t\treturn this.activeRuntime;\n\t}\n}\n","import { boundedDiagnostics } from \"../domain/config-diagnostics.js\";\nimport { DEFAULT_CONFIG, normalizeConfig, resolveConfigDetailed } from \"../domain/config-normalization.js\";\nimport type { NormalizedPiStyleConfig } from \"../domain/config-types.js\";\nimport type { StartupDetailItem, StartupReason } from \"../features/startup/index.js\";\nimport { createDoctor, type DoctorOperationalState } from \"./doctor.js\";\nimport { PiStyleRuntimeController } from \"./runtime.js\";\n\nexport interface StartupResourceDiscovery {\n\treadonly skillPaths?: readonly string[];\n\treadonly promptPaths?: readonly string[];\n\treadonly themePaths?: readonly string[];\n\t/** Raw system prompt text; word/line counts are computed outside render. */\n\treadonly systemPrompt?: string;\n\t/** Context files with pre-computed word/line counts (discovery outside render). */\n\treadonly contextDetails?: readonly { path: string; words: number; lines: number }[];\n\t/** Active tools with compact source labels (discovery outside render). */\n\treadonly toolDetails?: readonly { source: string; name: string }[];\n\treadonly models?: number;\n}\n\nfunction countWords(text: string): number {\n\treturn text.match(/[\\p{L}\\p{N}_]+/gu)?.length ?? 0;\n}\n\nfunction countLines(text: string): number {\n\tif (text.length === 0) return 0;\n\tconst lines = text.split(/\\r\\n|\\r|\\n/).length;\n\treturn /\\r\\n$|\\r$|\\n$/.test(text) ? lines - 1 : lines;\n}\n\nfunction toStartupResources(resources: StartupResourceDiscovery) {\n\tconst details: StartupDetailItem[] = [];\n\tif (resources.systemPrompt) {\n\t\tconst words = countWords(resources.systemPrompt);\n\t\tconst lines = countLines(resources.systemPrompt);\n\t\tif (words > 0 && lines > 0) details.push({ kind: \"system\", path: \"system prompt\", words, lines });\n\t}\n\tfor (const file of resources.contextDetails ?? []) {\n\t\tif (file.words > 0 && file.lines > 0) {\n\t\t\tdetails.push({ kind: \"context\", path: file.path, words: file.words, lines: file.lines });\n\t\t}\n\t}\n\treturn {\n\t\t...(resources.promptPaths ? { contextFiles: resources.promptPaths.length } : {}),\n\t\t...(resources.themePaths ? { extensions: resources.themePaths.length } : {}),\n\t\t...(resources.skillPaths ? { skills: resources.skillPaths.length } : {}),\n\t\t...(resources.models !== undefined ? { models: resources.models } : {}),\n\t\t...(resources.toolDetails && resources.toolDetails.length > 0\n\t\t\t? { tools: resources.toolDetails.length, toolDetails: resources.toolDetails }\n\t\t\t: {}),\n\t\t...(details.length > 0 ? { details } : {}),\n\t};\n}\n\nexport interface ConfigReloadPort {\n\tload(trusted: boolean): Promise<{\n\t\treadonly config?: unknown;\n\t\treadonly diagnostics?: readonly import(\"../domain/config-diagnostics.js\").ConfigDiagnostic[];\n\t\treadonly sources?: Readonly<Record<string, string>>;\n\t\treadonly rawSources?: {\n\t\t\tdefaults?: unknown;\n\t\t\tglobal?: unknown;\n\t\t\tproject?: unknown;\n\t\t\tenvironment?: Record<string, string | undefined>;\n\t\t};\n\t\treadonly productPolicy?: { corePatchGate: \"omitted\" | \"allow\" | \"deny\" };\n\t}>;\n}\n\nexport interface AppHost {\n\treadonly mode: \"tui\" | \"rpc\" | \"json\" | \"print\";\n\treadonly hasUI: boolean;\n\treadonly ui?: Parameters<PiStyleRuntimeController[\"start\"]>[0][\"ui\"];\n\treadonly cwd?: string;\n\treadonly model?: { id?: string; name?: string; provider?: string; reasoning?: boolean };\n\treadonly thinkingLevel?: string;\n\treadonly getContextUsage?: () => { tokens: number | null; contextWindow: number; percent: number | null } | undefined;\n\treadonly projectTrusted?: boolean;\n\treadonly extensionStatusProvider?: () => readonly import(\"../domain/status.js\").ExtensionStatus[] | undefined;\n\treadonly gitRunner?: import(\"../domain/providers.js\").GitCommandRunner;\n}\n\nexport interface PiStyleApp {\n\treadonly runtime: PiStyleRuntimeController;\n\treadonly config: NormalizedPiStyleConfig;\n\treadonly productPolicy: { corePatchGate: \"omitted\" | \"allow\" | \"deny\" };\n\tsessionStart(ctx: AppHost, reason?: StartupReason, resources?: StartupResourceDiscovery): void;\n\tsetResources(resources: StartupResourceDiscovery): void;\n\tapplySession(patch: unknown): void;\n\tsetProjectTrusted(trusted: boolean): void;\n\tsetOperationalState(state: DoctorOperationalState): void;\n\tsetProductPolicy(policy: { corePatchGate: \"omitted\" | \"allow\" | \"deny\" }): void;\n\treload(): Promise<void>;\n\tdoctor(): Readonly<Record<string, unknown>>;\n\tsessionShutdown(): void;\n\tupdate(\n\t\tvalues: import(\"../domain/status.js\").StatusSnapshot,\n\t\tkind?: import(\"./render-scheduler.js\").UpdateClass,\n\t): void;\n}\n\nfunction submittedSessionPaths(value: unknown, prefix = \"\"): readonly string[] {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return [];\n\treturn Object.entries(value).flatMap(([key, nested]) => {\n\t\tconst path = prefix ? `${prefix}.${key}` : key;\n\t\treturn [path, ...submittedSessionPaths(nested, path)];\n\t});\n}\nfunction composeSources(\n\tdurable: Readonly<Record<string, string>>,\n\tresolved: Readonly<Record<string, string>>,\n\tsession: unknown,\n): Readonly<Record<string, string>> {\n\tconst next = { ...durable, ...resolved };\n\tfor (const path of submittedSessionPaths(session)) {\n\t\tconst effectiveSource = resolved[path];\n\t\tif (effectiveSource === undefined) delete next[path];\n\t\telse next[path] = effectiveSource;\n\t}\n\treturn next;\n}\n\nfunction mergePatch(base: unknown, patch: unknown): unknown {\n\tif (patch === undefined) return base;\n\tif (\n\t\ttypeof base !== \"object\" ||\n\t\tbase === null ||\n\t\tArray.isArray(base) ||\n\t\ttypeof patch !== \"object\" ||\n\t\tpatch === null ||\n\t\tArray.isArray(patch)\n\t)\n\t\treturn patch;\n\tconst result: Record<string, unknown> = { ...(base as Record<string, unknown>) };\n\tfor (const [key, value] of Object.entries(patch as Record<string, unknown>))\n\t\tresult[key] = mergePatch(result[key], value);\n\treturn result;\n}\n\nexport function createPiStyleApp(\n\tinitialConfig?: unknown,\n\treloadPort?: ConfigReloadPort,\n\tonConfigChange?: (config: NormalizedPiStyleConfig) => void,\n): PiStyleApp {\n\tconst runtime = new PiStyleRuntimeController();\n\tlet config = initialConfig === undefined ? DEFAULT_CONFIG : normalizeConfig(initialConfig);\n\tlet diagnostics: readonly import(\"../domain/config-diagnostics.js\").ConfigDiagnostic[] = [];\n\tlet durableDiagnostics: readonly import(\"../domain/config-diagnostics.js\").ConfigDiagnostic[] = [];\n\tlet durableSources: Readonly<Record<string, string>> = {};\n\tlet sources: Readonly<Record<string, string>> = {};\n\tlet trusted = true;\n\tlet resources: StartupResourceDiscovery | undefined;\n\tlet operational: DoctorOperationalState = {};\n\tlet sessionPatch: unknown;\n\tlet rawSources: {\n\t\tdefaults?: unknown;\n\t\tglobal?: unknown;\n\t\tproject?: unknown;\n\t\tenvironment?: Record<string, string | undefined>;\n\t} = { defaults: initialConfig ?? DEFAULT_CONFIG };\n\tlet productPolicy: { corePatchGate: \"omitted\" | \"allow\" | \"deny\" } = { corePatchGate: \"omitted\" };\n\tconst resolveAll = () => resolveConfigDetailed({ ...rawSources, session: sessionPatch, projectTrusted: trusted });\n\tconst resolveProductPolicy = () => {\n\t\tconst values = [rawSources.global, trusted ? rawSources.project : undefined, sessionPatch];\n\t\tfor (const value of values) {\n\t\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) continue;\n\t\t\tconst compatibility = (value as Record<string, unknown>).compatibility;\n\t\t\tif (\n\t\t\t\tcompatibility &&\n\t\t\t\ttypeof compatibility === \"object\" &&\n\t\t\t\t!Array.isArray(compatibility) &&\n\t\t\t\tObject.hasOwn(compatibility, \"allowCorePatches\") &&\n\t\t\t\t(compatibility as Record<string, unknown>).allowCorePatches === false\n\t\t\t)\n\t\t\t\treturn { corePatchGate: \"deny\" as const };\n\t\t}\n\t\treturn { corePatchGate: \"omitted\" as const };\n\t};\n\treturn {\n\t\truntime,\n\t\tget config() {\n\t\t\treturn config;\n\t\t},\n\t\tget productPolicy() {\n\t\t\treturn productPolicy;\n\t\t},\n\t\tsessionStart(ctx, reason = \"startup\", discoveredResources) {\n\t\t\ttrusted = ctx.projectTrusted ?? true;\n\t\t\tresources = discoveredResources;\n\t\t\toperational = {\n\t\t\t\t...operational,\n\t\t\t\tprovider: ctx.extensionStatusProvider\n\t\t\t\t\t? { status: \"configured\", recovery: \"provider will be checked on first snapshot\" }\n\t\t\t\t\t: { status: \"unavailable\", recovery: \"inject a capability-safe provider\" },\n\t\t\t\tinstallations: {\n\t\t\t\t\tstatus: config.enabled && config.statusLine.enabled ? \"active\" : \"disabled\",\n\t\t\t\t\teditor: config.enabled && config.editor.enabled ? \"active\" : \"disabled\",\n\t\t\t\t\tstartup: config.enabled && config.startup.mode !== \"off\" ? \"active\" : \"disabled\",\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst statusProvider = ctx.extensionStatusProvider\n\t\t\t\t? () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = ctx.extensionStatusProvider?.();\n\t\t\t\t\t\t\toperational = { ...operational, provider: { status: \"available\" } };\n\t\t\t\t\t\t\treturn result;\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\toperational = {\n\t\t\t\t\t\t\t\t...operational,\n\t\t\t\t\t\t\t\tprovider: { status: \"unavailable\", recovery: \"provider threw; retry after recovery\" },\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tctx.ui?.notify?.(\"pi-style extension statuses unavailable; provider recovery required\", \"warning\");\n\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\t\t\truntime.start({\n\t\t\t\tmode: ctx.mode,\n\t\t\t\thasUI: ctx.hasUI,\n\t\t\t\t...(ctx.ui ? { ui: ctx.ui } : {}),\n\t\t\t\t...(ctx.cwd ? { cwd: ctx.cwd } : {}),\n\t\t\t\t...(ctx.model ? { model: ctx.model } : {}),\n\t\t\t\t...(ctx.thinkingLevel ? { thinkingLevel: ctx.thinkingLevel } : {}),\n\t\t\t\tconfig,\n\t\t\t\tstartupReason: reason,\n\t\t\t\t...(resources ? { resources: toStartupResources(resources) } : {}),\n\t\t\t\t...(ctx.getContextUsage ? { getContextUsage: ctx.getContextUsage } : {}),\n\t\t\t\t...(ctx.projectTrusted !== undefined ? { projectTrusted: ctx.projectTrusted } : {}),\n\t\t\t\t...(ctx.gitRunner ? { gitRunner: ctx.gitRunner } : {}),\n\t\t\t\t...(statusProvider ? { extensionStatusProvider: statusProvider } : {}),\n\t\t\t});\n\t\t},\n\t\tsetResources(next) {\n\t\t\tresources = next;\n\t\t\truntime.current?.updateStartupResources(toStartupResources(next));\n\t\t},\n\t\tapplySession(patch) {\n\t\t\tsessionPatch = mergePatch(sessionPatch, patch);\n\t\t\tconst resolved = resolveAll();\n\t\t\tconfig = resolved.config;\n\t\t\tdiagnostics = boundedDiagnostics([...durableDiagnostics, ...resolved.diagnostics]);\n\t\t\tsources = composeSources(durableSources, resolved.sources, sessionPatch);\n\t\t\tproductPolicy = resolveProductPolicy();\n\t\t\toperational = {\n\t\t\t\t...operational,\n\t\t\t\tauthorization: { ...(operational.authorization ?? {}), productCorePatchGate: productPolicy.corePatchGate },\n\t\t\t};\n\t\t\truntime.current?.configure(config);\n\t\t\toperational = {\n\t\t\t\t...operational,\n\t\t\t\tinstallations: { ...(operational.installations ?? {}), configChange: \"reconciled\" },\n\t\t\t};\n\t\t\tonConfigChange?.(config);\n\t\t},\n\t\tsetProjectTrusted(nextTrusted) {\n\t\t\ttrusted = nextTrusted;\n\t\t},\n\t\tsetOperationalState(state) {\n\t\t\toperational = { ...operational, ...state };\n\t\t},\n\t\tsetProductPolicy(policy) {\n\t\t\tproductPolicy = policy;\n\t\t\toperational = {\n\t\t\t\t...operational,\n\t\t\t\tauthorization: { ...(operational.authorization ?? {}), productCorePatchGate: policy.corePatchGate },\n\t\t\t};\n\t\t},\n\t\tsessionShutdown() {\n\t\t\truntime.stop();\n\t\t},\n\t\tupdate(values, kind = \"coalesced\") {\n\t\t\tconst active = runtime.current;\n\t\t\tif (!active) return;\n\t\t\tactive.update(values);\n\t\t\tactive.scheduler.schedule(kind);\n\t\t},\n\t\treload() {\n\t\t\tif (!reloadPort) {\n\t\t\t\truntime.current?.configure(config);\n\t\t\t\treturn Promise.resolve();\n\t\t\t}\n\t\t\treturn reloadPort.load(trusted).then((result) => {\n\t\t\t\tdurableDiagnostics = boundedDiagnostics(result.diagnostics ?? []);\n\t\t\t\tdurableSources = result.sources ?? {};\n\t\t\t\tdiagnostics = durableDiagnostics;\n\t\t\t\tsources = durableSources;\n\t\t\t\tif (result.config !== undefined) {\n\t\t\t\t\trawSources = result.rawSources ?? { defaults: result.config };\n\t\t\t\t\tproductPolicy = resolveProductPolicy();\n\t\t\t\t\tconst resolved = resolveAll();\n\t\t\t\t\tconfig = resolved.config;\n\t\t\t\t\tdiagnostics = boundedDiagnostics([...durableDiagnostics, ...resolved.diagnostics]);\n\t\t\t\t\tsources = composeSources(durableSources, resolved.sources, sessionPatch);\n\t\t\t\t\tonConfigChange?.(config);\n\t\t\t\t\toperational = {\n\t\t\t\t\t\t...operational,\n\t\t\t\t\t\tauthorization: { ...(operational.authorization ?? {}), productCorePatchGate: productPolicy.corePatchGate },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\truntime.current?.configure(config);\n\t\t\t\tonConfigChange?.(config);\n\t\t\t});\n\t\t},\n\t\tdoctor() {\n\t\t\treturn createDoctor({\n\t\t\t\tconfig,\n\t\t\t\toperational,\n\t\t\t\tdiagnostics,\n\t\t\t\tsources,\n\t\t\t\tsurfaces: {\n\t\t\t\t\tstatus: operational.installations?.status ?? \"unknown\",\n\t\t\t\t\teditor: operational.installations?.editor ?? \"unknown\",\n\t\t\t\t\tstartup: operational.installations?.startup ?? \"unknown\",\n\t\t\t\t\tassistantMessage: operational.compatibility?.assistantMessage ?? \"unknown\",\n\t\t\t\t\tspecialBlocks: operational.compatibility?.specialBlocks ?? \"unknown\",\n\t\t\t\t\ttools: operational.compatibility?.tools ?? \"unknown\",\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t};\n}\n","// Special message-block presentation: compaction, skill invocation, branch\n// summary, and extension custom (MCP) messages, rendered as boxed blocks.\n//\n// These patches are pure delegates: the compatibility probe installs them\n// through its reversible, generation-tracked wrapper and restores the native\n// identity on shutdown. The delegate receives the native method and falls back\n// to it whenever the theme or component shape is unavailable.\n\nimport { keyText } from \"@earendil-works/pi-coding-agent\";\nimport { Markdown, type MarkdownTheme } from \"@earendil-works/pi-tui\";\nimport type { BoxTheme } from \"../../shared/box.js\";\nimport { setFullTheme } from \"../../shared/theme-extras.js\";\nimport { renderBoxedMessageBlock } from \"./boxed-block.js\";\n\nlet cachedTheme: BoxTheme | undefined;\n\nexport function setSpecialBlockTheme(theme: BoxTheme | undefined): void {\n\tcachedTheme = theme;\n\tif (theme) setFullTheme(theme);\n}\n\nexport type SpecialBlockSubtype =\n\t| \"native-compaction-message\"\n\t| \"native-branch-message\"\n\t| \"native-skill-message\"\n\t| \"native-custom-message\";\n\nexport type SpecialBlockCtor = { prototype?: unknown };\n\nexport interface SpecialBlockCtors {\n\tCompactionSummaryMessageComponent?: SpecialBlockCtor;\n\tSkillInvocationMessageComponent?: SpecialBlockCtor;\n\tBranchSummaryMessageComponent?: SpecialBlockCtor;\n\tCustomMessageComponent?: SpecialBlockCtor;\n}\n\n/** Structural view of the native message components as used by the patches. */\ninterface MessageBlockInstance {\n\tmessage?: {\n\t\ttokensBefore?: unknown;\n\t\tsummary?: unknown;\n\t\tcustomType?: unknown;\n\t\tcontent?: unknown;\n\t};\n\tskillBlock?: { name?: unknown; content?: unknown };\n\texpanded?: unknown;\n\t_expanded?: unknown;\n\tmarkdownTheme?: unknown;\n\tbox?: { clear(): void; addChild(child: unknown): void; setBgFn?(fn: (text: string) => string): void };\n\tcustomComponent?: unknown;\n\tcustomRenderer?: unknown;\n\tclear?(): void;\n\taddChild(child: unknown): void;\n\tremoveChild(child: unknown): void;\n\tsetBgFn?(fn: (text: string) => string): void;\n}\n\nconst EXPAND_HINT = \"Ctrl+O to expand\";\n\nfunction expandHint(): string {\n\ttry {\n\t\tconst text = keyText(\"app.tools.expand\");\n\t\treturn text ? `${text} to expand` : EXPAND_HINT;\n\t} catch {\n\t\treturn EXPAND_HINT;\n\t}\n}\n\nfunction createMarkdownBody(\n\ttext: string,\n\tmarkdownTheme: MarkdownTheme | undefined,\n\ttheme: BoxTheme,\n): (contentWidth: number) => string[] {\n\tconst md = new Markdown(text || \"\", 0, 0, markdownTheme as MarkdownTheme, {\n\t\tcolor: (t: string) => theme.fg(\"customMessageText\", t),\n\t});\n\treturn (contentWidth: number) => md.render(contentWidth);\n}\n\n/**\n * Neutralize the native customMessageBg fill for boxed blocks: the boxed block\n * owns its visual boundary, so the parent background is removed (the box sits\n * directly on the terminal/page background).\n */\nfunction neutralizeMessageBlockBackground(target: { setBgFn?(fn: (text: string) => string): void } | undefined): void {\n\tif (!target) return;\n\tif (typeof target.setBgFn === \"function\") target.setBgFn((text) => text);\n}\n\nfunction patchCompaction(instance: MessageBlockInstance, _original: () => void, theme: BoxTheme): boolean {\n\tconst tokensBefore = instance.message?.tokensBefore;\n\tif (tokensBefore == null) return false;\n\n\tif (typeof instance.clear === \"function\") instance.clear();\n\n\tconst expanded = Boolean(instance.expanded);\n\tconst summary = typeof instance.message?.summary === \"string\" ? instance.message.summary : \"\";\n\tconst markdownTheme = instance.markdownTheme as MarkdownTheme | undefined;\n\n\tneutralizeMessageBlockBackground(instance as { setBgFn?(fn: (text: string) => string): void });\n\n\tconst body = expanded && summary && markdownTheme ? createMarkdownBody(summary, markdownTheme, theme) : () => [];\n\n\tconst tokenStr = Number(tokensBefore).toLocaleString();\n\tneutralizeMessageBlockBackground(instance as { setBgFn?(fn: (text: string) => string): void });\n\tconst block = renderBoxedMessageBlock(theme, {\n\t\tkind: \"Compaction\",\n\t\ttitle: `${tokenStr} tokens`,\n\t\t...(expanded ? {} : { right: expandHint() }),\n\t\tbody,\n\t\ticon: \"⊟\",\n\t\thasDivider: expanded,\n\t});\n\tinstance.addChild(block);\n\treturn true;\n}\n\nfunction patchSkill(instance: MessageBlockInstance, _original: () => void, theme: BoxTheme): boolean {\n\tconst skillName = instance.skillBlock?.name;\n\tif (typeof skillName !== \"string\" || !skillName) return false;\n\n\tif (typeof instance.clear === \"function\") instance.clear();\n\n\tconst expanded = Boolean(instance.expanded);\n\tconst content = typeof instance.skillBlock?.content === \"string\" ? instance.skillBlock.content : \"\";\n\tconst markdownTheme = instance.markdownTheme as MarkdownTheme | undefined;\n\n\tneutralizeMessageBlockBackground(instance as { setBgFn?(fn: (text: string) => string): void });\n\n\tconst body = expanded && content && markdownTheme ? createMarkdownBody(content, markdownTheme, theme) : () => [];\n\n\tconst block = renderBoxedMessageBlock(theme, {\n\t\tkind: \"Skill\",\n\t\ttitle: skillName,\n\t\t...(expanded ? {} : { right: expandHint() }),\n\t\tbody,\n\t\ticon: \"⊟\",\n\t\thasDivider: expanded,\n\t});\n\tinstance.addChild(block);\n\treturn true;\n}\n\nfunction patchBranch(instance: MessageBlockInstance, _original: () => void, theme: BoxTheme): boolean {\n\tif (instance.message == null) return false;\n\n\tif (typeof instance.clear === \"function\") instance.clear();\n\n\tconst expanded = Boolean(instance.expanded);\n\tconst summary = typeof instance.message?.summary === \"string\" ? instance.message.summary : \"\";\n\tconst markdownTheme = instance.markdownTheme as MarkdownTheme | undefined;\n\n\tneutralizeMessageBlockBackground(instance as { setBgFn?(fn: (text: string) => string): void });\n\n\tconst body = expanded && summary && markdownTheme ? createMarkdownBody(summary, markdownTheme, theme) : () => [];\n\n\tconst block = renderBoxedMessageBlock(theme, {\n\t\tkind: \"Branch\",\n\t\t...(expanded ? {} : { right: expandHint() }),\n\t\tbody,\n\t\ticon: \"⊟\",\n\t\thasDivider: expanded,\n\t});\n\tinstance.addChild(block);\n\treturn true;\n}\n\nfunction attachCustomMessageBlock(instance: MessageBlockInstance, block: unknown): boolean {\n\tif (instance.box && typeof instance.box.clear === \"function\" && typeof instance.box.addChild === \"function\") {\n\t\tinstance.addChild(instance.box);\n\t\tinstance.box.clear();\n\t\tinstance.box.addChild(block);\n\t\treturn true;\n\t}\n\tinstance.customComponent = block;\n\tinstance.addChild(instance.customComponent);\n\treturn true;\n}\n\nfunction patchCustomMessage(instance: MessageBlockInstance, _original: () => void, theme: BoxTheme): boolean {\n\t// Remove previous content component\n\tif (instance.customComponent) {\n\t\tinstance.removeChild(instance.customComponent);\n\t\tinstance.customComponent = undefined;\n\t}\n\tif (instance.box) instance.removeChild(instance.box);\n\n\t// The boxed shell owns its boundary; drop the native customMessageBg fill.\n\tneutralizeMessageBlockBackground(instance.box);\n\tneutralizeMessageBlockBackground(instance as { setBgFn?(fn: (text: string) => string): void });\n\n\tconst rawCustomType = instance.message?.customType;\n\tconst customType = typeof rawCustomType === \"string\" ? rawCustomType : \"Custom\";\n\n\t// Try custom renderer first, but keep the special block shell/background owned here.\n\tif (typeof instance.customRenderer === \"function\") {\n\t\ttry {\n\t\t\tconst component = (instance.customRenderer as (message: unknown, options: object, theme: unknown) => unknown)(\n\t\t\t\tinstance.message,\n\t\t\t\t{ expanded: instance._expanded },\n\t\t\t\ttheme,\n\t\t\t);\n\t\t\tif (component && typeof (component as { render?: unknown }).render === \"function\") {\n\t\t\t\tconst block = renderBoxedMessageBlock(theme, {\n\t\t\t\t\tkind: \"Custom\",\n\t\t\t\t\ttitle: customType,\n\t\t\t\t\tbody: (contentWidth) => (component as { render(width: number): string[] }).render(contentWidth),\n\t\t\t\t\ticon: \"⊟\",\n\t\t\t\t\thasDivider: \"auto\",\n\t\t\t\t\tcache: false,\n\t\t\t\t});\n\t\t\t\tattachCustomMessageBlock(instance, block);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Fall through to default rendering\n\t\t}\n\t}\n\n\t// Default rendering: use boxed message block\n\n\t// Extract text content\n\tconst rawContent = instance.message?.content;\n\tlet text: string;\n\tif (typeof rawContent === \"string\") {\n\t\ttext = rawContent;\n\t} else if (Array.isArray(rawContent)) {\n\t\ttext = rawContent\n\t\t\t.filter((c: unknown) => {\n\t\t\t\tif (!c || typeof c !== \"object\") return false;\n\t\t\t\treturn (c as { type?: unknown }).type === \"text\";\n\t\t\t})\n\t\t\t.map((c) => String((c as { text?: unknown }).text ?? \"\"))\n\t\t\t.join(\"\\n\");\n\t} else {\n\t\ttext = \"\";\n\t}\n\n\tconst markdownTheme = instance.markdownTheme as MarkdownTheme | undefined;\n\n\tconst body = text && markdownTheme ? createMarkdownBody(text, markdownTheme, theme) : () => [];\n\n\tconst block = renderBoxedMessageBlock(theme, {\n\t\tkind: \"Custom\",\n\t\ttitle: customType,\n\t\tbody,\n\t\ticon: \"⊟\",\n\t\thasDivider: Boolean(text),\n\t});\n\n\tattachCustomMessageBlock(instance, block);\n\treturn true;\n}\n\n/**\n * Delegate invoked by the compatibility probe's wrapper for each special block\n * method. Falls back to the native implementation when the theme cache is\n * empty or the component shape is unsupported.\n */\nexport function renderSpecialMessageBlock(\n\tsubtype: SpecialBlockSubtype,\n\toriginal: unknown,\n\tthisArg: object,\n\targs: unknown[],\n): unknown {\n\tconst instance = thisArg as unknown as MessageBlockInstance;\n\tconst base = original as (this: object, ...rest: unknown[]) => unknown;\n\tconst applyBase = () => base.apply(thisArg, args);\n\tconst theme = cachedTheme;\n\tif (!theme) return applyBase();\n\ttry {\n\t\tlet handled = false;\n\t\tif (subtype === \"native-compaction-message\") handled = patchCompaction(instance, applyBase, theme);\n\t\telse if (subtype === \"native-skill-message\") handled = patchSkill(instance, applyBase, theme);\n\t\telse if (subtype === \"native-branch-message\") handled = patchBranch(instance, applyBase, theme);\n\t\telse if (subtype === \"native-custom-message\") handled = patchCustomMessage(instance, applyBase, theme);\n\t\treturn handled ? undefined : applyBase();\n\t} catch {\n\t\treturn applyBase();\n\t}\n}\n","// Boxed message-block shell (skill/compaction/branch/custom/MCP blocks).\n// Returns only border/content lines with foreground styling; the parent Box\n// applies the customMessageBg background (the native components already set\n// that bgFn).\n\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport type { BoxTheme } from \"../../shared/box.js\";\nimport { boxBlankLine, boxBorder, boxInnerWidth, boxLabeledBorder, boxLine, boxWidth } from \"../../shared/box.js\";\n\nexport type MessageBlockOptions = {\n\tkind: string;\n\ttitle?: string;\n\tright?: string;\n\tbody: (contentWidth: number) => string[];\n\thasDivider?: boolean | \"auto\";\n\ticon?: string;\n\tcache?: boolean;\n};\n\nfunction formatMessageBlockTitle(theme: BoxTheme, kind: string, title?: string, icon = \"➔\"): string {\n\tconst rawTitle = title ? `${icon} ${kind} · ${title}` : `${icon} ${kind}`;\n\tconst coloredTitle = theme.fg(\"accent\", rawTitle);\n\treturn typeof theme?.bold === \"function\" ? theme.bold(coloredTitle) : coloredTitle;\n}\n\n/**\n * Render a boxed message block.\n *\n * The title is embedded in the rounded top border, the body sits between\n * blank padding rows, and the expand hint (when present) is embedded at the\n * right end of the bottom border — no inset dividers.\n *\n * Returns only border/content lines with foreground styling. Background is\n * applied by the parent Box (all patched components extend Box with a\n * customMessageBg bgFn), so this helper must NOT apply background itself —\n * that would create a double-background conflict.\n */\nexport function renderBoxedMessageBlock(theme: BoxTheme, options: MessageBlockOptions): Component {\n\tconst { kind, title, right, body, icon = \"➔\", cache: shouldCache = true } = options;\n\tlet cache: { width: number; lines: string[] } | null = null;\n\n\treturn {\n\t\tinvalidate() {\n\t\t\tcache = null;\n\t\t},\n\t\trender(width: number): string[] {\n\t\t\tif (shouldCache && cache?.width === width) return cache.lines;\n\n\t\t\tconst renderedWidth = boxWidth(width);\n\t\t\tconst contentWidth = boxInnerWidth(renderedWidth);\n\t\t\tconst titleLine = formatMessageBlockTitle(theme, kind, title, icon);\n\t\t\tconst bodyLines = body(contentWidth);\n\n\t\t\tconst lines: string[] = [\n\t\t\t\tboxLabeledBorder(theme, \"╭\", \"╮\", titleLine, undefined, renderedWidth),\n\t\t\t\tboxBlankLine(theme, renderedWidth),\n\t\t\t\t...bodyLines.map((line) => boxLine(theme, line, renderedWidth)),\n\t\t\t];\n\t\t\tif (bodyLines.length > 0) lines.push(boxBlankLine(theme, renderedWidth));\n\t\t\tif (right) {\n\t\t\t\tlines.push(boxLabeledBorder(theme, \"╰\", \"╯\", \"\", theme.fg(\"dim\", right), renderedWidth));\n\t\t\t} else {\n\t\t\t\tlines.push(boxBorder(theme, \"╰\", \"╯\", renderedWidth));\n\t\t\t}\n\n\t\t\tif (shouldCache) cache = { width, lines };\n\t\t\treturn lines;\n\t\t},\n\t};\n}\n","// Boxed presentation for Pi's native direct bash execution (`!command` /\n// `!!command` prefix in the input box). The native BashExecutionComponent draws\n// plain full-width top/bottom bars; a fingerprint-certified additive render\n// patch (see pi/compatibility-probe.ts) installs an own `render` on the\n// prototype that re-frames the output into the same rounded box used by the\n// boxed tool presentation: `╭─ ➔ Bash ◌ ─╮`, boxed `$ command` + output body,\n// `╰─ Exit 0 ─╯`.\n//\n// The renderer is a pure delegate: it falls back to the native (inherited\n// Container) rendering whenever the theme cache is empty or the component\n// shape is unsupported. Nothing about the native instance is mutated — the\n// box is computed per render from the live component state.\n\nimport type { BoxTheme } from \"../../shared/box.js\";\nimport {\n\tboxBlankLine,\n\tboxInnerWidth,\n\tboxLabeledBorder,\n\tboxLine,\n\tboxWidth,\n\tformatBoxedRunningStatus,\n} from \"../../shared/box.js\";\nimport { getThemeExtra } from \"../../shared/theme-extras.js\";\n\nlet cachedTheme: BoxTheme | undefined;\n\n/** Provide the active theme for the boxed bash execution display (session start / theme change). */\nexport function setBashExecutionTheme(theme: BoxTheme | undefined): void {\n\tcachedTheme = theme;\n}\n\n/** Structural view of the native BashExecutionComponent as used by the patch. */\ninterface BashExecutionInstance {\n\tcommand: string;\n\tstatus: \"running\" | \"cancelled\" | \"error\" | \"complete\";\n\texitCode?: number | null;\n\tcontentContainer: { render(width: number): string[] };\n\t/** Wall-clock start captured on the first boxed render for the live `◌ Running · Ns` footer. */\n\tpiStyleStart?: number;\n}\n\nconst TOP_LEFT = \"╭\";\nconst TOP_RIGHT = \"╮\";\nconst BOTTOM_LEFT = \"╰\";\nconst BOTTOM_RIGHT = \"╯\";\n\nfunction bashTitleColor(theme: BoxTheme): string {\n\t// Honors the `bashPromptColor` theme extra, falling back to the bashMode\n\t// semantic color (the same source the boxed bash tool title uses).\n\tconst extra = getThemeExtra(theme, \"bashPromptColor\");\n\treturn extra || \"bashMode\";\n}\n\nfunction boldOf(theme: BoxTheme): (text: string) => string {\n\treturn typeof theme?.bold === \"function\" ? theme.bold : (text: string) => text;\n}\n\n/** `➔ Bash ◌/✓/✗` — the same title language as the boxed bash tool call. */\nfunction bashBoxTitle(theme: BoxTheme, host: BashExecutionInstance): string {\n\tconst name = \"Bash\";\n\tconst bold = boldOf(theme);\n\tconst prefix = theme.fg(bashTitleColor(theme), `➔ ${name}`);\n\tif (host.status === \"running\") return bold(`${prefix} ${theme.fg(\"text\", \"◌\")}`);\n\tif (host.status === \"cancelled\") return bold(theme.fg(\"warning\", `➔ ${name} ✗`));\n\tif (host.status === \"error\") return bold(theme.fg(\"error\", `➔ ${name} ✗`));\n\treturn bold(`${prefix} ${theme.fg(\"success\", \"✓\")}`);\n}\n\n/** Bottom-border label: live running status with elapsed, or the terminal state. */\nfunction bashBoxFooter(theme: BoxTheme, host: BashExecutionInstance): string {\n\tif (host.status === \"running\") {\n\t\tconst elapsed = typeof host.piStyleStart === \"number\" ? (Date.now() - host.piStyleStart) / 1000 : undefined;\n\t\treturn formatBoxedRunningStatus(theme, elapsed);\n\t}\n\tif (host.status === \"cancelled\") return theme.fg(\"warning\", \"Cancelled\");\n\tif (host.status === \"error\") return theme.fg(\"error\", `Exit ${host.exitCode ?? \"?\"}`);\n\treturn theme.fg(\"text\", \"Exit 0\");\n}\n\n/**\n * Render a BashExecutionComponent as the rounded box. Returns undefined so the\n * caller falls back to the native rendering whenever the theme is unavailable\n * or the component shape is not the certified layout.\n */\nexport function renderBashExecutionBox(instance: unknown, args: unknown[]): string[] | undefined {\n\tconst theme = cachedTheme;\n\tconst width = args[0];\n\tif (!theme || typeof width !== \"number\" || !Number.isFinite(width) || width <= 0) return undefined;\n\tconst host = instance as BashExecutionInstance;\n\tconst content = host.contentContainer;\n\tif (!content || typeof content.render !== \"function\") return undefined;\n\ttry {\n\t\tif (host.piStyleStart === undefined) host.piStyleStart = Date.now();\n\t\tconst renderedWidth = boxWidth(width);\n\t\tconst inner = boxInnerWidth(renderedWidth);\n\t\t// The native Text children render one leading padding space per line;\n\t\t// drop it so boxLine's own side padding produces symmetric borders.\n\t\tconst wrapped = content\n\t\t\t.render(inner)\n\t\t\t.map((line) => boxLine(theme, line.startsWith(\" \") ? line.slice(1) : line, renderedWidth));\n\t\treturn [\n\t\t\t\"\",\n\t\t\tboxLabeledBorder(theme, TOP_LEFT, TOP_RIGHT, bashBoxTitle(theme, host), undefined, renderedWidth),\n\t\t\tboxBlankLine(theme, renderedWidth),\n\t\t\t...wrapped,\n\t\t\tboxBlankLine(theme, renderedWidth),\n\t\t\tboxLabeledBorder(theme, BOTTOM_LEFT, BOTTOM_RIGHT, bashBoxFooter(theme, host), undefined, renderedWidth),\n\t\t];\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n","// Boxed bash tool renderer\n// (renderCall/renderResult only).\n\nimport { highlightCode } from \"@earendil-works/pi-coding-agent\";\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport { stripAnsi } from \"../../../shared/ansi.js\";\nimport type { BoxTheme } from \"../../../shared/box.js\";\nimport {\n\tboxedToolWidthKey,\n\tformatBoxedRunningStatus,\n\tformatBoxedWords,\n\tformatToolOutputLine,\n\tgetTextOutput,\n\trenderBoxedToolCall,\n\trenderBoxedToolResult,\n\treplaceTabs,\n\tshortenPath,\n} from \"../../../shared/box.js\";\nimport { safeTruncateToWidth, truncateAtCodePointBoundary } from \"../../../shared/render-budget.js\";\nimport { parseSimpleBashCommand } from \"./command-shape.js\";\nimport {\n\tclassifyGhCommand,\n\ttype GhParsedSemantic,\n\ttype GhRunJobParsed,\n\ttype GhSemanticClass,\n\tparseGhOutput,\n\trenderGhCardLines,\n\trenderGhRunJobResult,\n} from \"./gh.js\";\nimport {\n\tclassifyGitCommand,\n\ttype GitDiffParsed,\n\ttype GitParsedSemantic,\n\ttype GitSemanticClass,\n\tparseGitOutput,\n\trenderGitCardLines,\n\trenderGitDiffResult,\n} from \"./git.js\";\nimport {\n\ttype GrepMatch,\n\tgroupMatchesByFile,\n\tparseFindOutput,\n\tparseGrepBareOutput,\n\tparseGrepOutput,\n\tparseLsLongOutput,\n\tparseLsOutput,\n\tpluralForm,\n\trenderGrepTree,\n\trenderOutputTree,\n\tSEARCH_ICON,\n\tTREE_INDENT,\n} from \"./output-tree.js\";\nimport {\n\tgetStateElapsedMs,\n\tgetToolsRenderConfig,\n\tisResultSeen,\n\tmarkResultSeen,\n\trecordExecutionEnded,\n\tstartElapsedTicker,\n\tstopElapsedTicker,\n} from \"./session-config.js\";\nimport { type BoxedToolContext, type BoxedToolDefinition, noteBoxedCallState, noteExecutionStart } from \"./shared.js\";\n\nconst MAX_LINE_CHARS = 2000;\nconst ESC = \"\\x1b\";\nconst BASH_TOOL_NOTICE_PATTERN = /^\\[Showing (?:last|lines)\\b.*\\. Full output: .+\\]$/;\nconst BG_ANSI_PATTERN = new RegExp(`${ESC}\\\\[4[0-9;]*m`, \"g\");\nconst SHELL_VAR_PATTERN = /\\$\\{?[A-Za-z_][A-Za-z0-9_]*\\}?/;\nconst SHELL_OP_PATTERN = /^(?:&&|\\|\\||>>|>&|\\|&|[|&;()<>])$/;\n\nfunction highlightBashFallback(line: string): string {\n\ttry {\n\t\tconst highlighted = highlightCode(line, \"bash\")[0] ?? line;\n\t\t// Strip background colors to avoid clashing with badge/parens styling\n\t\treturn highlighted.replace(BG_ANSI_PATTERN, \"\");\n\t} catch {\n\t\treturn line;\n\t}\n}\n\nfunction normalizeShellWord(word: string): string {\n\treturn word.replace(/^(['\"])(.*)\\1$/, \"$2\");\n}\n\nfunction colorShellWord(theme: BoxTheme, word: string, commandExpected: boolean): string {\n\tconst normalized = normalizeShellWord(word);\n\tif (/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(normalized)) return theme.fg(\"syntaxVariable\", word);\n\tif (normalized.startsWith(\"-\")) return theme.fg(\"syntaxKeyword\", word);\n\tif (normalized.includes(\"/\") || /^\\.{1,2}(?:\\/|$)/.test(normalized)) return theme.fg(\"syntaxVariable\", word);\n\tif (SHELL_VAR_PATTERN.test(normalized)) return theme.fg(\"syntaxVariable\", word);\n\treturn commandExpected ? theme.fg(\"syntaxFunction\", word) : theme.fg(\"syntaxString\", word);\n}\n\nfunction tokenizeShellLinePreservingText(line: string): string[] | undefined {\n\tconst tokens: string[] = [];\n\tlet current = \"\";\n\tlet quote: string | null = null;\n\n\tfor (let i = 0; i < line.length; i++) {\n\t\tconst char = line[i] ?? \"\";\n\t\tconst next = line[i + 1] ?? \"\";\n\n\t\tif (quote) {\n\t\t\tcurrent += char;\n\t\t\tif (char === \"\\\\\" && next) current += line[++i] ?? \"\";\n\t\t\telse if (char === quote) quote = null;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === \"'\" || char === '\"') {\n\t\t\tquote = char;\n\t\t\tcurrent += char;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (/\\s/.test(char)) {\n\t\t\tif (current) tokens.push(current);\n\t\t\tcurrent = \"\";\n\t\t\ttokens.push(char);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === \"#\" && !current) {\n\t\t\tif (current) tokens.push(current);\n\t\t\ttokens.push(line.slice(i));\n\t\t\treturn tokens;\n\t\t}\n\n\t\tconst two = `${char}${next}`;\n\t\tif (SHELL_OP_PATTERN.test(two) || SHELL_OP_PATTERN.test(char)) {\n\t\t\tif (current) tokens.push(current);\n\t\t\tcurrent = \"\";\n\t\t\tif (SHELL_OP_PATTERN.test(two)) {\n\t\t\t\ttokens.push(two);\n\t\t\t\ti++;\n\t\t\t} else {\n\t\t\t\ttokens.push(char);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tcurrent += char;\n\t}\n\n\tif (quote) return undefined;\n\tif (current) tokens.push(current);\n\treturn tokens;\n}\n\nfunction highlightBashLine(line: string, theme: BoxTheme): string {\n\tconst tokens = tokenizeShellLinePreservingText(line);\n\tif (!tokens) return highlightBashFallback(line);\n\tlet commandExpected = true;\n\treturn tokens\n\t\t.map((token) => {\n\t\t\tif (/^\\s+$/.test(token)) return token;\n\t\t\tif (token.startsWith(\"#\")) return theme.fg(\"syntaxComment\", token);\n\t\t\tif (SHELL_OP_PATTERN.test(token)) {\n\t\t\t\tcommandExpected = token === \"|\" || token === \"||\" || token === \"&&\" || token === \";\" || token === \"&\";\n\t\t\t\treturn theme.fg(\"syntaxOperator\", token);\n\t\t\t}\n\t\t\tconst styled = colorShellWord(theme, token, commandExpected);\n\t\t\tif (!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(normalizeShellWord(token))) commandExpected = false;\n\t\t\treturn styled;\n\t\t})\n\t\t.join(\"\");\n}\n\nfunction clampLineLength(line: string, max: number = MAX_LINE_CHARS): string {\n\tif (line.length <= max) return line;\n\treturn `${truncateAtCodePointBoundary(line, max)}… (truncated)`;\n}\n\nfunction countNewlines(text: string, from: number, to: number): number {\n\tlet count = 0;\n\tfor (let i = from; i < to; i++) {\n\t\tif (text.charCodeAt(i) === 10) count++;\n\t}\n\treturn count;\n}\n\nfunction stripBashToolNoticeLines(text: string): string {\n\tconst filteredLines = text\n\t\t.replace(/\\r/g, \"\")\n\t\t.split(\"\\n\")\n\t\t.filter((line) => !BASH_TOOL_NOTICE_PATTERN.test(line.trim()));\n\treturn filteredLines\n\t\t.join(\"\\n\")\n\t\t.replace(/\\n{3,}/g, \"\\n\\n\")\n\t\t.trimEnd();\n}\n\nfunction bashWidthKey(rawCommand: string, timeout: unknown): string {\n\treturn boxedToolWidthKey(\"Bash\", `${rawCommand}|${timeout ?? \"\"}`);\n}\n\nfunction renderBoxedBashCall(\n\ttheme: BoxTheme,\n\tcommandLines: string[],\n\tcontext: BoxedToolContext,\n\twidthKey: string,\n): Component {\n\tconst maxCommandLines = 5;\n\tconst shownCount = Math.min(commandLines.length, maxCommandLines + 1);\n\tconst detailLines: string[] = [];\n\tfor (let i = 0; i < shownCount; i++) {\n\t\tconst prefix = i === 0 ? theme.fg(\"dim\", \"$ \") : theme.fg(\"dim\", \"> \");\n\t\tdetailLines.push(`${prefix}${highlightBashLine(commandLines[i] ?? \"\", theme)}`);\n\t}\n\tif (commandLines.length > maxCommandLines + 1) {\n\t\tdetailLines.push(theme.fg(\"muted\", `... ${commandLines.length - maxCommandLines - 1} more lines`));\n\t}\n\tconst running = Boolean(context.executionStarted);\n\tconst resultSeen = isResultSeen(context.state);\n\tconst base = {\n\t\twidthKey,\n\t\tisError: Boolean(context.isError),\n\t\tisPartial: Boolean(context.isPartial),\n\t\tisPending: Boolean(context.isPartial),\n\t\trunning,\n\t};\n\tif (running && context.isPartial && !resultSeen) {\n\t\t// Pre-result running card: the call closes the box with a live running\n\t\t// footer and a `No output received yet` line. The first partial result\n\t\t// renders nothing, so this card is never duplicated below.\n\t\tdetailLines.push(theme.fg(\"dim\", \"No output received yet\"));\n\t\treturn renderBoxedToolCall(theme, \"Bash\", detailLines, {\n\t\t\t...base,\n\t\t\tpendingLabel: formatBoxedRunningStatus(theme, getStateElapsedMs(context.state)),\n\t\t});\n\t}\n\t// Streaming (a result renderer already continues this box) and terminal\n\t// (settled) passes leave the box open so the result closes it.\n\treturn renderBoxedToolCall(theme, \"Bash\", detailLines, { ...base, resultSeen });\n}\n\n// ── Terminal status detection ────────────────────────────────────────────────\n// The bash tool appends a `\\n\\n<status>` suffix to failed results (nonzero exit,\n// timeout, abort). Parse it off the raw text so the footer can carry the real\n// status instead of displaying the suffix as output.\n\ntype BashTerminalStatus =\n\t| { kind: \"exit\"; exitCode: number }\n\t| { kind: \"timeout\"; seconds: number }\n\t| { kind: \"cancelled\" };\n\nconst BASH_STATUS_PATTERNS: ReadonlyArray<{\n\tre: RegExp;\n\tbuild: (match: RegExpMatchArray) => BashTerminalStatus;\n}> = [\n\t{\n\t\tre: /(?:^|\\n\\n)Command timed out after ([\\d.]+) seconds$/i,\n\t\tbuild: (match) => ({ kind: \"timeout\", seconds: Number(match[1]) }),\n\t},\n\t{ re: /(?:^|\\n\\n)[^\\n]*aborted$/i, build: () => ({ kind: \"cancelled\" }) },\n\t{\n\t\tre: /(?:^|\\n\\n)Command exited with code (\\d+)$/i,\n\t\tbuild: (match) => ({ kind: \"exit\", exitCode: Number(match[1]) }),\n\t},\n];\n\nfunction parseBashTerminalStatus(text: string): { status: BashTerminalStatus | undefined; body: string } {\n\tconst clean = String(text ?? \"\").replace(/\\r/g, \"\");\n\tfor (const { re, build } of BASH_STATUS_PATTERNS) {\n\t\tconst match = clean.match(re);\n\t\tif (match && match.index !== undefined) {\n\t\t\treturn { status: build(match), body: clean.slice(0, match.index).trimEnd() };\n\t\t}\n\t}\n\t// Pi's message_end error path (agent aborted) sends a bare status text with\n\t// no bash output shape; recognize it as a cancelled state.\n\tif (/^(?:operation )?aborted(?: after \\d+ retry attempts?)?$/i.test(clean.trim())) {\n\t\treturn { status: { kind: \"cancelled\" }, body: \"\" };\n\t}\n\treturn { status: undefined, body: clean };\n}\n\nfunction bashErrorLabel(status: BashTerminalStatus | undefined): string | undefined {\n\tif (status?.kind === \"timeout\") return \"✗ Timed out\";\n\tif (status?.kind === \"cancelled\") return \"✗ Cancelled\";\n\treturn undefined;\n}\n\n/** Body text shown when a terminal bash result produced no output. */\nfunction bashEmptyBodyText(status: BashTerminalStatus | undefined, isError: boolean): string {\n\tif (status?.kind === \"timeout\") return \"No output was received before the timeout\";\n\tif (status?.kind === \"cancelled\") return \"Command was cancelled without producing output\";\n\tif (isError) return \"Command failed without producing output\";\n\treturn \"Command completed without producing output\";\n}\n\nfunction bashFooter(\n\ttheme: BoxTheme,\n\tstatus: BashTerminalStatus | undefined,\n\telapsedMs: number | undefined,\n\tbodyText: string,\n\tisError: boolean,\n): string {\n\tconst elapsed = elapsedMs === undefined ? \"--\" : `${(elapsedMs / 1000).toFixed(2)}s`;\n\tconst words = bodyText.trim() ? formatBoxedWords(bodyText) : \"\";\n\n\tif (status?.kind === \"timeout\") {\n\t\tconst seconds = Number.isFinite(status.seconds) && status.seconds > 0 ? status.seconds : Number.NaN;\n\t\treturn theme.fg(\n\t\t\t\"warning\",\n\t\t\tNumber.isFinite(seconds) ? `Terminated after ${seconds.toFixed(1)}s` : \"Terminated by timeout\",\n\t\t);\n\t}\n\tif (status?.kind === \"cancelled\") {\n\t\treturn [theme.fg(\"warning\", \"Cancelled\"), theme.fg(\"text\", elapsed)].join(theme.fg(\"dim\", \" · \"));\n\t}\n\n\tconst exitLabel = status?.kind === \"exit\" ? `Exit ${status.exitCode}` : isError ? \"Failed\" : \"Exit 0\";\n\tconst exitColor = status?.kind === \"exit\" && status.exitCode !== 0 ? \"error\" : \"text\";\n\tconst parts = [theme.fg(exitColor, exitLabel), theme.fg(\"text\", elapsed)];\n\tif (words) parts.push(theme.fg(\"dim\", words));\n\treturn parts.join(theme.fg(\"dim\", \" · \"));\n}\n\n// ── Interactive command heuristics ───────────────────────────────────────────\n// Terminal programs that read stdin or own the screen produce no pipe output;\n// when one runs silently we hint that it may be waiting for terminal input.\n\nconst INTERACTIVE_COMMANDS = new Set([\n\t\"pi\",\n\t\"vim\",\n\t\"vi\",\n\t\"nvim\",\n\t\"nano\",\n\t\"less\",\n\t\"more\",\n\t\"man\",\n\t\"top\",\n\t\"htop\",\n\t\"btop\",\n\t\"ssh\",\n\t\"telnet\",\n\t\"python\",\n\t\"python3\",\n\t\"node\",\n\t\"sqlite3\",\n\t\"mysql\",\n\t\"psql\",\n\t\"redis-cli\",\n\t\"mongosh\",\n\t\"bc\",\n\t\"irssi\",\n]);\n\nfunction isInteractiveCommand(command: unknown): boolean {\n\tconst base =\n\t\t(\n\t\t\tString(command ?? \"\")\n\t\t\t\t.trim()\n\t\t\t\t.split(/\\s+/)[0] ?? \"\"\n\t\t)\n\t\t\t.split(\"/\")\n\t\t\t.pop() ?? \"\";\n\treturn INTERACTIVE_COMMANDS.has(base);\n}\n\n/** Wrap an output preview so an empty result renders state text instead of `∅`. */\nfunction bashBodyComponent(preview: Component, emptyLines: string[] | undefined): Component {\n\tif (!emptyLines) return preview;\n\treturn {\n\t\tinvalidate: () => preview.invalidate(),\n\t\trender(width: number): string[] {\n\t\t\tconst lines = preview.render(width);\n\t\t\treturn lines.length > 0 ? lines : emptyLines;\n\t\t},\n\t};\n}\n\n/** Streaming continuation: streamed output (or `No output received yet`), a\n * live running footer, and no `Response` divider until the tool settles. */\nfunction renderBashStreamingResult(\n\ttheme: BoxTheme,\n\traw: string,\n\toptions: { expanded: boolean },\n\tcontext: BoxedToolContext,\n): Component {\n\tconst body = stripBashToolNoticeLines(stripAnsi(raw));\n\tconst hasOutput = body.trim().length > 0;\n\tconst elapsed = getStateElapsedMs(context.state);\n\tconst emptyLines: string[] = [theme.fg(\"dim\", \"No output received yet\")];\n\tif (!hasOutput && isInteractiveCommand(context?.args?.command) && (elapsed ?? 0) >= 1000) {\n\t\temptyLines.push(theme.fg(\"dim\", \"The process may be waiting for terminal input\"));\n\t}\n\tconst preview = createBashResultPreview(theme, body, options, \"toolOutput\");\n\tconst rawCommand = String(context?.args?.command ?? \"...\");\n\treturn renderBoxedToolResult(theme, bashBodyComponent(preview, hasOutput ? undefined : emptyLines), {\n\t\twidthKey: bashWidthKey(rawCommand, context?.args?.timeout),\n\t\treferenceLines: rawCommand.split(\"\\n\").map((line, index) => `${index === 0 ? \"$ \" : \"> \"}${line}`),\n\t\tdividerLabel: \"Output\",\n\t\tshowDivider: hasOutput,\n\t\tfooterLines: [formatBoxedRunningStatus(theme, elapsed)],\n\t\tisPartial: true,\n\t});\n}\n\nfunction renderBashFinalResult(\n\ttheme: BoxTheme,\n\traw: string,\n\toptions: { expanded: boolean },\n\tcontext: BoxedToolContext,\n): Component {\n\tconst isError = Boolean(context.isError);\n\tconst clean = stripAnsi(raw);\n\tconst { status, body: statusStripped } = parseBashTerminalStatus(clean);\n\tconst output = stripBashToolNoticeLines(statusStripped);\n\tconst elapsed = getStateElapsedMs(context.state);\n\tconst outputColor = isError ? \"error\" : \"toolOutput\";\n\tconst footer = bashFooter(theme, status, elapsed, output, isError);\n\tconst errorLabel = isError ? (bashErrorLabel(status) ?? \"✗ Error\") : undefined;\n\n\tconst rawCommand = String(context?.args?.command ?? \"...\");\n\tconst widthKey = bashWidthKey(rawCommand, context?.args?.timeout);\n\tconst referenceLines = rawCommand.split(\"\\n\").map((line, index) => `${index === 0 ? \"$ \" : \"> \"}${line}`);\n\n\tif (!options.expanded) {\n\t\t// Collapsed: only process the tail of the output (notices stripped per line).\n\t\tconst scanLines = getToolsRenderConfig().maxCollapsedLines + 10;\n\t\tlet nlCount = 0;\n\t\tlet tailStart = 0;\n\t\tfor (let i = statusStripped.length - 1; i >= 0; i--) {\n\t\t\tif (statusStripped.charCodeAt(i) === 10) {\n\t\t\t\tnlCount++;\n\t\t\t\tif (nlCount >= scanLines) {\n\t\t\t\t\ttailStart = i + 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst tail = stripBashToolNoticeLines(stripAnsi(statusStripped.slice(tailStart)));\n\t\tconst totalLinesBefore = tailStart > 0 ? countNewlines(statusStripped, 0, tailStart) : 0;\n\t\tconst preview = createBashResultPreview(theme, tail, options, outputColor);\n\t\treturn renderBoxedToolResult(\n\t\t\ttheme,\n\t\t\tbashBodyComponent(\n\t\t\t\tpreview,\n\t\t\t\tstatusStripped.trim() ? undefined : [theme.fg(\"muted\", bashEmptyBodyText(status, isError))],\n\t\t\t),\n\t\t\t{\n\t\t\t\twidthKey,\n\t\t\t\treferenceLines,\n\t\t\t\tfooterLines: [footer],\n\t\t\t\t...(totalLinesBefore > 0 ? { expandHint: \"Ctrl+O for more\" } : {}),\n\t\t\t\tisError,\n\t\t\t\tisPartial: false,\n\t\t\t\t...(errorLabel ? { errorLabel } : {}),\n\t\t\t},\n\t\t);\n\t}\n\n\tconst preview = createBashResultPreview(theme, output, options, outputColor);\n\treturn renderBoxedToolResult(\n\t\ttheme,\n\t\tbashBodyComponent(preview, output.trim() ? undefined : [theme.fg(\"muted\", bashEmptyBodyText(status, isError))]),\n\t\t{\n\t\t\twidthKey,\n\t\t\treferenceLines,\n\t\t\tfooterLines: [footer],\n\t\t\tisError,\n\t\t\tisPartial: false,\n\t\t\t...(errorLabel ? { errorLabel } : {}),\n\t\t},\n\t);\n}\n\n/** First-partial-pass result: the pending/running call card stands alone. */\nconst EMPTY_BASH_RESULT: Component = Object.freeze({\n\tinvalidate() {},\n\trender() {\n\t\treturn [];\n\t},\n});\n\nfunction createBashResultPreview(\n\ttheme: BoxTheme,\n\ttext: string,\n\toptions: { expanded: boolean },\n\tcolor: \"toolOutput\" | \"error\",\n): Component {\n\tlet cacheKey = \"\";\n\tlet cacheLines: string[] | null = null;\n\n\treturn {\n\t\tinvalidate() {\n\t\t\tcacheKey = \"\";\n\t\t\tcacheLines = null;\n\t\t},\n\t\trender(width: number): string[] {\n\t\t\tconst bodyWidth = Math.max(1, width);\n\t\t\tconst cfg = getToolsRenderConfig();\n\t\t\tconst expanded = Boolean(options.expanded);\n\t\t\tconst cacheId = `${bodyWidth}|${expanded ? 1 : 0}|${cfg.maxExpandedLines}|${cfg.dimOutput ? 1 : 0}`;\n\t\t\tif (cacheLines && cacheKey === cacheId) return cacheLines;\n\n\t\t\tif (!expanded) {\n\t\t\t\t// Collapsed: only process the tail of the output\n\t\t\t\tconst needed = cfg.maxCollapsedLines;\n\t\t\t\tlet totalNewlines = 0;\n\t\t\t\tlet scanFrom = 0; // default: take full text if fewer than needed newlines\n\t\t\t\tfor (let i = text.length - 1; i >= 0; i--) {\n\t\t\t\t\tif (text.charCodeAt(i) === 10) {\n\t\t\t\t\t\ttotalNewlines++;\n\t\t\t\t\t\tif (totalNewlines === needed) {\n\t\t\t\t\t\t\tscanFrom = i + 1;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (text.length === 0) {\n\t\t\t\t\tcacheKey = cacheId;\n\t\t\t\t\tcacheLines = [];\n\t\t\t\t\treturn cacheLines;\n\t\t\t\t}\n\n\t\t\t\tconst tail = replaceTabs(text.slice(scanFrom)).replace(/\\r/g, \"\");\n\t\t\t\tconst shownLines = tail ? tail.split(\"\\n\").map((l) => clampLineLength(l)) : [];\n\n\t\t\t\tif (shownLines.length === 0) {\n\t\t\t\t\tcacheKey = cacheId;\n\t\t\t\t\tcacheLines = [];\n\t\t\t\t\treturn cacheLines;\n\t\t\t\t}\n\n\t\t\t\tconst truncatedShown = shownLines.map((line) => {\n\t\t\t\t\tconst truncated = safeTruncateToWidth(line, bodyWidth, \"…\");\n\t\t\t\t\tif (color === \"error\") return formatToolOutputLine(theme, truncated, \"error\");\n\t\t\t\t\treturn cfg.dimOutput\n\t\t\t\t\t\t? formatToolOutputLine(theme, truncated)\n\t\t\t\t\t\t: formatToolOutputLine(theme, truncated, \"text\");\n\t\t\t\t});\n\n\t\t\t\tcacheKey = cacheId;\n\t\t\t\tcacheLines = truncatedShown;\n\t\t\t\treturn cacheLines;\n\t\t\t}\n\n\t\t\t// Expanded: process all lines\n\t\t\tconst normalized = replaceTabs(text);\n\t\t\tconst logicalLines = normalized.split(\"\\n\").map((l) => clampLineLength(l));\n\t\t\tconst hasOutput = !(logicalLines.length === 1 && logicalLines[0] === \"\");\n\n\t\t\tif (!hasOutput) {\n\t\t\t\tcacheKey = cacheId;\n\t\t\t\tcacheLines = [];\n\t\t\t\treturn cacheLines;\n\t\t\t}\n\n\t\t\tconst truncatedLines = logicalLines.map((line) => safeTruncateToWidth(line, bodyWidth, \"…\"));\n\t\t\tconst expandedLines = truncatedLines.length === 1 && truncatedLines[0] === \"\" ? [] : truncatedLines;\n\t\t\tconst applyColor = (l: string) =>\n\t\t\t\tcolor === \"error\"\n\t\t\t\t\t? formatToolOutputLine(theme, l, \"error\")\n\t\t\t\t\t: cfg.dimOutput\n\t\t\t\t\t\t? formatToolOutputLine(theme, l)\n\t\t\t\t\t\t: formatToolOutputLine(theme, l, \"text\");\n\t\t\tif (cfg.maxExpandedLines > 0 && expandedLines.length > cfg.maxExpandedLines) {\n\t\t\t\tconst truncated = expandedLines.slice(-cfg.maxExpandedLines).map(applyColor);\n\t\t\t\tconst remaining = expandedLines.length - cfg.maxExpandedLines;\n\t\t\t\ttruncated.unshift(theme.fg(\"dim\", `… ${remaining} earlier lines`));\n\t\t\t\tcacheKey = cacheId;\n\t\t\t\tcacheLines = truncated;\n\t\t\t\treturn cacheLines;\n\t\t\t}\n\n\t\t\tcacheKey = cacheId;\n\t\t\tcacheLines = expandedLines.map(applyColor);\n\t\t\treturn cacheLines;\n\t\t},\n\t};\n}\n\n// ── ls/find/grep/rg command detection ───────────────────────────────────────\n// A bash command whose real command is ls/find/grep/rg (after env assignments,\n// sudo/env/time prefixes, and path stripping), with no shell metacharacters\n// (pipes, redirects, `;`, `&&`, command substitution, subshells, newlines), is\n// rendered as the same boxless output tree as the corresponding native tool.\n// Everything else keeps the boxed command/response shell.\n\ntype BashTreeKind = \"ls\" | \"find\" | \"grep\";\n\ninterface BashTreeClass {\n\treadonly kind: BashTreeKind;\n\treadonly pattern?: string;\n\treadonly pathLabel?: string;\n\t/** grep: exactly one path positional — single-file output (`line: content`)\n\t * is attributed to it. */\n\treadonly singlePath?: string;\n}\n\nconst BASH_GREP_COMMANDS = new Set([\"grep\", \"egrep\", \"fgrep\", \"rg\"]);\n\n/** grep/rg flags that consume a separate value token (`--type ts`). */\nconst GREP_VALUE_FLAGS = new Set([\n\t\"-e\",\n\t\"--regexp\",\n\t\"-g\",\n\t\"--glob\",\n\t\"--type\",\n\t\"-t\",\n\t\"--include\",\n\t\"--exclude\",\n\t\"-C\",\n\t\"-A\",\n\t\"-B\",\n\t\"--context\",\n\t\"--after-context\",\n\t\"--before-context\",\n\t\"-m\",\n\t\"--max-count\",\n\t\"-M\",\n\t\"--max-columns\",\n\t\"--ignore-file\",\n]);\n\n/** find flags that consume a separate value token (`-type f`). */\nconst FIND_VALUE_FLAGS = new Set([\n\t\"-type\",\n\t\"-mtime\",\n\t\"-atime\",\n\t\"-ctime\",\n\t\"-size\",\n\t\"-maxdepth\",\n\t\"-mindepth\",\n\t\"-perm\",\n\t\"-group\",\n\t\"-user\",\n\t\"-newer\",\n]);\n\nfunction classifyByArgs(kind: BashTreeKind, args: string[]): BashTreeClass {\n\tconst positionals: string[] = [];\n\tlet pattern: string | undefined;\n\tfor (let i = 0; i < args.length; i++) {\n\t\tconst token = args[i] ?? \"\";\n\t\tif (\n\t\t\t(kind === \"grep\" && (token === \"-e\" || token === \"--regexp\")) ||\n\t\t\t(kind === \"find\" && (token === \"-name\" || token === \"-iname\" || token === \"-path\" || token === \"-ipath\"))\n\t\t) {\n\t\t\tpattern = args[++i];\n\t\t\tcontinue;\n\t\t}\n\t\tif (kind === \"grep\" && GREP_VALUE_FLAGS.has(token)) {\n\t\t\ti++; // skip the flag and its value\n\t\t\tcontinue;\n\t\t}\n\t\tif (kind === \"find\" && FIND_VALUE_FLAGS.has(token)) {\n\t\t\ti++; // skip the flag and its value\n\t\t\tcontinue;\n\t\t}\n\t\tif (token.startsWith(\"-\")) continue;\n\t\tpositionals.push(token);\n\t}\n\tconst rawPath = positionals[0] ?? \".\";\n\tconst pathLabel = rawPath === \".\" ? \"current directory\" : shortenPath(rawPath);\n\tif (kind === \"ls\") return { kind, pathLabel };\n\tif (kind === \"find\") return { kind, ...(pattern !== undefined ? { pattern } : {}), pathLabel };\n\tconst grepPattern = pattern ?? positionals[0];\n\tconst pathArgs = pattern !== undefined ? positionals : positionals.slice(1);\n\tconst grepPath = pathArgs.join(\" \");\n\tconst grepPathLabel = !grepPath || grepPath === \".\" ? \"current directory\" : shortenPath(grepPath);\n\treturn {\n\t\tkind,\n\t\t...(grepPattern !== undefined ? { pattern: grepPattern } : {}),\n\t\tpathLabel: grepPathLabel,\n\t\t...(pathArgs.length === 1 ? { singlePath: pathArgs[0] ?? \"\" } : {}),\n\t};\n}\n\n/** Classify a bash command for tree rendering, or null to keep the boxed shell. */\nexport function classifyBashCommand(command: string): BashTreeClass | null {\n\tconst shape = parseSimpleBashCommand(command, { allowTrailingTruncationPipe: true });\n\tif (!shape) return null;\n\tconst rest = shape.tokens;\n\tconst base = (rest[0] ?? \"\").split(\"/\").pop() ?? \"\";\n\tlet kind: BashTreeKind | null = null;\n\tif (base === \"ls\") kind = \"ls\";\n\telse if (base === \"find\") kind = \"find\";\n\telse if (BASH_GREP_COMMANDS.has(base)) kind = \"grep\";\n\tif (!kind) return null;\n\n\tconst cls = classifyByArgs(kind, rest.slice(1));\n\tif (shape.cdDir && cls.pathLabel === \"current directory\") {\n\t\treturn {\n\t\t\tkind,\n\t\t\t...(cls.pattern !== undefined ? { pattern: cls.pattern } : {}),\n\t\t\tpathLabel: shortenPath(shape.cdDir),\n\t\t\t...(cls.singlePath !== undefined ? { singlePath: cls.singlePath } : {}),\n\t\t};\n\t}\n\treturn cls;\n}\n\nfunction bashTreeHeader(theme: BoxTheme, cls: BashTreeClass, counts?: { files?: number; matches?: number }): string {\n\tconst label = cls.kind === \"find\" ? \"Find\" : cls.kind === \"ls\" ? \"List\" : \"Grep\";\n\tconst hasDetail = Boolean(cls.pattern) || Boolean(counts);\n\t// ls/find/grep headers carry the magnifying-glass icon in Nerd Font mode.\n\tconst icon = getToolsRenderConfig().nerdFonts ? `${SEARCH_ICON} ` : \"\";\n\tconst prefix = icon + (hasDetail ? `${label}:` : label);\n\tconst patternPart = cls.pattern ? ` ${theme.fg(\"text\", cls.pattern)}` : \"\";\n\tlet middle = \"\";\n\tif (counts) {\n\t\tif (cls.kind === \"grep\") {\n\t\t\tconst matches = counts.matches ?? 0;\n\t\t\tconst files = counts.files ?? 0;\n\t\t\tmiddle = ` ${theme.fg(\"accent\", `${matches} ${pluralForm(\"match\", matches)}`)}${theme.fg(\"dim\", ` · ${files} ${pluralForm(\"file\", files)}`)}`;\n\t\t} else {\n\t\t\tconst files = counts.files ?? 0;\n\t\t\tmiddle = ` ${theme.fg(\"accent\", `${files} ${pluralForm(\"file\", files)}`)}`;\n\t\t}\n\t}\n\tconst pathPart =\n\t\tcls.pathLabel && cls.pathLabel !== \"current directory\" ? theme.fg(\"dim\", ` · in ${cls.pathLabel}`) : \"\";\n\treturn `${typeof theme?.bold === \"function\" ? theme.bold(prefix) : prefix}${patternPart}${middle}${pathPart}`;\n}\n\n/** `ls -l` long-format lines (permissions block) can't be parsed into names\n * reliably; fall back to the boxed shell for those. A leading `total N`\n * summary line is skipped before the check. */\nfunction isLongFormatLs(text: string): boolean {\n\tconst first = text\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trim())\n\t\t.find((line) => line.length > 0 && !/^total\\s+\\d+$/i.test(line));\n\treturn Boolean(first) && /^[bcdlsp-][rwxtsST-]{9}[\\s@]/.test(first as string);\n}\n\n/** Parsed bash tree output, or null to fall back to the boxed shell\n * (long-format ls, unparseable grep). */\ntype ParsedBashTree = { entries: string[] } | { matches: GrepMatch[] };\n\nfunction parseBashTreeOutput(cls: BashTreeClass, output: string): ParsedBashTree | null {\n\tif (cls.kind === \"ls\") {\n\t\t// `ls -l`/`ls -la` long format is parsed into names (with `/` for dirs)\n\t\t// so bash listings render like the List tool tree.\n\t\tif (isLongFormatLs(output)) return { entries: parseLsLongOutput(output) };\n\t\treturn { entries: parseLsOutput(output) };\n\t}\n\tif (cls.kind === \"find\") return { entries: parseFindOutput(output) };\n\tconst matches = parseGrepOutput(output);\n\tif (matches.length === 0 && output.trim().length > 0) {\n\t\t// Single-file `rg`/`grep` output is `line: content` with no filename:\n\t\t// attribute matches to the command's single path argument.\n\t\tif (cls.singlePath) {\n\t\t\tconst bare = parseGrepBareOutput(output, cls.singlePath);\n\t\t\tif (bare.length > 0) return { matches: bare };\n\t\t}\n\t\treturn null;\n\t}\n\treturn { matches };\n}\n\ninterface BashTreeState {\n\treadonly cls: BashSemanticClass;\n\t/** Raw command, so the call panel can render the boxed bash call on fallback. */\n\treadonly command: string;\n\t/** `parsed` once the result arrives; `fallback` when the boxed shell takes over. */\n\tparsed?: ParsedSemantic;\n\tfallback?: boolean;\n}\n\n/** Classified semantic command: a bash tree (ls/find/grep), a git card, or a\n * gh card (pr/issue/run). */\nexport type BashSemanticClass = BashTreeClass | GitSemanticClass | GhSemanticClass;\ntype ParsedSemantic = ParsedBashTree | GitParsedSemantic | GhParsedSemantic;\n\n/** Classify a bash command for semantic rendering (tree, git card, or gh\n * card), or null to keep the boxed command/response shell. */\nexport function classifyBashSemantic(command: string): BashSemanticClass | null {\n\treturn classifyBashCommand(command) ?? classifyGitCommand(command) ?? classifyGhCommand(command);\n}\n\nfunction isBashTreeClass(cls: BashSemanticClass): cls is BashTreeClass {\n\treturn cls.kind === \"ls\" || cls.kind === \"find\" || cls.kind === \"grep\";\n}\n\n/** Type guard for the gh semantic classes (pr/issue/run list/view/checks/\n * create/job). */\nfunction isGhClass(cls: BashSemanticClass): cls is GhSemanticClass {\n\tswitch (cls.kind) {\n\t\tcase \"pr-list\":\n\t\tcase \"pr-view\":\n\t\tcase \"pr-checks\":\n\t\tcase \"pr-create\":\n\t\tcase \"issue-list\":\n\t\tcase \"issue-view\":\n\t\tcase \"run-list\":\n\t\tcase \"run-view\":\n\t\tcase \"run-job\":\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\n/** `gh run view --job=<id>` renders a boxed log result (Phase 8D); the other gh\n * classes render their whole panel in the call card. */\nfunction isGhRunJobClass(cls: BashSemanticClass): boolean {\n\treturn cls.kind === \"run-job\";\n}\n\n/** `git diff` / `git show` render a boxed adaptive-diff result (Phase 8B); the\n * other semantic classes render their whole panel in the call card. */\nfunction isGitDiffClass(cls: BashSemanticClass): boolean {\n\treturn !isBashTreeClass(cls) && (cls as GitSemanticClass).kind === \"diff\";\n}\n\n/** `git commit`/`push`/`pull`/`fetch` may produce informational exit-1 output\n * (e.g. `git commit` with nothing staged) that still parses to a card. Their\n * parsers are fail-closed, so genuine errors (push rejected, hook failure)\n * return null and fall back to the raw boxed shell (ADR 0005). */\nfunction isGitActionClass(cls: BashSemanticClass): boolean {\n\treturn !isBashTreeClass(cls) && (cls as GitSemanticClass).kind === \"action\";\n}\n\nfunction parseSemanticOutput(cls: BashSemanticClass, output: string): ParsedSemantic | null {\n\tif (isBashTreeClass(cls)) return parseBashTreeOutput(cls, output);\n\tif (isGhClass(cls)) return parseGhOutput(cls, output);\n\treturn parseGitOutput(cls, output);\n}\n\nconst semanticStates = new Map<string, BashTreeState>();\n\n/** Reset all semantic bash state (session start/shutdown, new message). */\nexport function resetBashTreeRegistry(): void {\n\tsemanticStates.clear();\n}\n\nfunction renderBashTreeLines(\n\ttheme: BoxTheme,\n\tstate: { cls: BashTreeClass; parsed?: ParsedBashTree },\n\twidth: number,\n): string[] {\n\tconst safeWidth = Math.max(1, width);\n\tconst cls = state.cls;\n\tif (state.parsed && \"entries\" in state.parsed) {\n\t\tconst entries = state.parsed.entries;\n\t\treturn renderOutputTree(theme, bashTreeHeader(theme, cls, { files: entries.length }), entries, safeWidth, {\n\t\t\tmoreUnit: \"file\",\n\t\t\tindent: TREE_INDENT,\n\t\t\twithIcons: getToolsRenderConfig().nerdFonts,\n\t\t});\n\t}\n\tif (state.parsed && \"matches\" in state.parsed) {\n\t\tconst matches = state.parsed.matches;\n\t\treturn renderGrepTree(\n\t\t\ttheme,\n\t\t\tbashTreeHeader(theme, cls, { matches: matches.length, files: groupMatchesByFile(matches).length }),\n\t\t\tmatches,\n\t\t\tsafeWidth,\n\t\t\t{ indent: TREE_INDENT, withIcons: getToolsRenderConfig().nerdFonts },\n\t\t);\n\t}\n\treturn [safeTruncateToWidth(bashTreeHeader(theme, cls), safeWidth, \"…\")];\n}\n\n/** Empty result component — the tree lives in the call panel, which re-renders\n * with the parsed output once the result arrives. */\nconst EMPTY_BASH_TREE_RESULT: Component = {\n\tinvalidate() {},\n\trender() {\n\t\treturn [];\n\t},\n};\n\n/** Live panel component for a classified bash command: pending header until the\n * result arrives, then the parsed output tree/card. When the result falls back\n * to the boxed shell, the call renders the boxed bash call instead, so call and\n * result form one complete box and never duplicate. The state reference is\n * captured at creation so a registry clear on session reset/resume does not\n * blank already-rendered panels. */\nfunction renderSemanticPanel(theme: BoxTheme, toolCallId: string, context: BoxedToolContext): Component {\n\tconst state = semanticStates.get(toolCallId);\n\treturn {\n\t\tinvalidate() {},\n\t\trender(width: number): string[] {\n\t\t\tif (!state) return [];\n\t\t\tif (state.fallback) {\n\t\t\t\treturn renderBoxedBashCall(\n\t\t\t\t\ttheme,\n\t\t\t\t\tstate.command.split(\"\\n\"),\n\t\t\t\t\tcontext,\n\t\t\t\t\tbashWidthKey(state.command, context?.args?.timeout),\n\t\t\t\t).render(width);\n\t\t\t}\n\t\t\tif (isBashTreeClass(state.cls)) {\n\t\t\t\tconst treeState: { cls: BashTreeClass; parsed?: ParsedBashTree } = { cls: state.cls };\n\t\t\t\tif (state.parsed !== undefined) treeState.parsed = state.parsed as ParsedBashTree;\n\t\t\t\treturn renderBashTreeLines(theme, treeState, width);\n\t\t\t}\n\t\t\t// Git classes only ever carry git parsed values (parseSemanticOutput\n\t\t\t// dispatches on the class), so the narrowed cast is exact.\n\t\t\tif (isGhClass(state.cls)) {\n\t\t\t\tconst ghState: { cls: GhSemanticClass; parsed?: GhParsedSemantic } = { cls: state.cls };\n\t\t\t\tif (state.parsed !== undefined) ghState.parsed = state.parsed as GhParsedSemantic;\n\t\t\t\treturn renderGhCardLines(theme, ghState, width);\n\t\t\t}\n\t\t\tconst gitState: { cls: GitSemanticClass; parsed?: GitParsedSemantic } = { cls: state.cls };\n\t\t\tif (state.parsed !== undefined) gitState.parsed = state.parsed as GitParsedSemantic;\n\t\t\treturn renderGitCardLines(theme, gitState, width);\n\t\t},\n\t};\n}\n\nexport const bashTool: BoxedToolDefinition = {\n\tcall(args, theme, context) {\n\t\tnoteExecutionStart(context);\n\t\tconst cls = classifyBashSemantic(String(args?.command ?? \"\"));\n\t\tif (cls) {\n\t\t\tsemanticStates.set(context.toolCallId, { cls, command: String(args?.command ?? \"\") });\n\t\t\treturn renderSemanticPanel(theme, context.toolCallId, context);\n\t\t}\n\t\tnoteBoxedCallState(context);\n\t\tconst rawCommand = String(args?.command ?? \"...\");\n\t\treturn renderBoxedBashCall(theme, rawCommand.split(\"\\n\"), context, bashWidthKey(rawCommand, args?.timeout));\n\t},\n\tresult(result, options, theme, context) {\n\t\tconst firstResultPass = !isResultSeen(context.state);\n\t\tmarkResultSeen(context.state);\n\t\tconst cls = classifyBashSemantic(String(context?.args?.command ?? \"\"));\n\t\t// Action classes (commit/push/pull/fetch) also attempt parsing on exit-1\n\t\t// results so informational states like `git commit` with nothing staged\n\t\t// render as a card; the fail-closed parser keeps genuine errors raw.\n\t\tif (cls && (!context.isError || isGitActionClass(cls))) {\n\t\t\t// Semantic-classified commands render in the call panel; the result adds\n\t\t\t// nothing. Keep terminal state in sync without an elapsed ticker. Git\n\t\t\t// parsers only run on the terminal result: streaming partial output may\n\t\t\t// hold a truncated line that would fail parsing and wrongly fall back.\n\t\t\tif (!options.isPartial) {\n\t\t\t\trecordExecutionEnded(context.state);\n\t\t\t\tstopElapsedTicker(context.state);\n\t\t\t}\n\t\t\tif (!options.isPartial || isBashTreeClass(cls)) {\n\t\t\t\tconst output = stripBashToolNoticeLines(stripAnsi(getTextOutput(result)));\n\t\t\t\tconst parsed = parseSemanticOutput(cls, output);\n\t\t\t\tconst state = semanticStates.get(context.toolCallId);\n\t\t\t\tif (parsed) {\n\t\t\t\t\tif (state) state.parsed = parsed;\n\t\t\t\t\telse\n\t\t\t\t\t\tsemanticStates.set(context.toolCallId, {\n\t\t\t\t\t\t\tcls,\n\t\t\t\t\t\t\tcommand: String(context?.args?.command ?? \"\"),\n\t\t\t\t\t\t\tparsed,\n\t\t\t\t\t\t});\n\t\t\t\t\t// `git diff` / `git show` render a boxed adaptive-diff result (one frame\n\t\t\t\t\t// per file); `gh run view --job=<id>` renders a boxed log result. Every\n\t\t\t\t\t// other semantic class renders its whole panel in the call card, so the\n\t\t\t\t\t// result adds nothing.\n\t\t\t\t\tif (isGitDiffClass(cls)) {\n\t\t\t\t\t\treturn renderGitDiffResult(theme, parsed as GitDiffParsed, options, context);\n\t\t\t\t\t}\n\t\t\t\t\tif (isGhRunJobClass(cls)) {\n\t\t\t\t\t\treturn renderGhRunJobResult(theme, parsed as GhRunJobParsed, options, context);\n\t\t\t\t\t}\n\t\t\t\t\treturn EMPTY_BASH_TREE_RESULT;\n\t\t\t\t}\n\t\t\t\t// Unparseable output (ls -l, raw rg summary, non-git output): the boxed\n\t\t\t\t// shell owns the result; flag the call panel to render nothing so the\n\t\t\t\t// two don't duplicate.\n\t\t\t\tif (state) state.fallback = true;\n\t\t\t}\n\t\t} else if (options.isPartial) {\n\t\t\tstartElapsedTicker(context.state, context.invalidate);\n\t\t} else {\n\t\t\trecordExecutionEnded(context.state);\n\t\t\tstopElapsedTicker(context.state);\n\t\t}\n\t\tconst raw = getTextOutput(result);\n\t\tif (options.isPartial) {\n\t\t\t// First partial pass: the running call card stands alone. Later passes\n\t\t\t// stream output into the open continuation without a Response divider.\n\t\t\tif (firstResultPass) return EMPTY_BASH_RESULT;\n\t\t\treturn renderBashStreamingResult(theme, raw, options, context);\n\t\t}\n\t\treturn renderBashFinalResult(theme, raw, options, context);\n\t},\n};\n","// Simple bash command shape detection, shared by the bash tool renderer and\n// the git/gh semantic classifiers.\n//\n// A command is \"simple\" when pi-style can reason about it purely from its\n// token list: single line, no shell metacharacters (pipes, redirects,\n// substitutions), and no `&&`/`;`/`&` outside a leading `cd X &&` chain.\n// Anything ambiguous returns null so the boxed command/response shell stays\n// the fallback (ADR 0005 — no approximate rendering).\n\n/** Tokens of a classifiable command after env/prefix/cd-chain stripping. */\nexport interface SimpleBashCommandShape {\n\t/** Tokens after leading env assignments, prefix commands, and `cd X &&` chains. */\n\treadonly tokens: string[];\n\t/** Last directory from a leading `cd <dir> &&` / `cd <dir>;` chain. */\n\treadonly cdDir?: string;\n}\n\nconst BASH_PREFIX_COMMANDS = new Set([\"sudo\", \"env\", \"time\", \"nice\", \"nohup\", \"command\", \"stdbuf\", \"ionice\", \"watch\"]);\n// Pipes (`|`), `;`, and `&` are excluded here: the classifier validates them\n// explicitly (allowing `cd X && cmd` chains and a trailing `| head/tail`).\nconst BASH_SHELL_META_CHARS = new Set([\"<\", \">\", \"(\", \")\", \"`\"]);\n\n/** Tokenize a single command line, stripping quotes. Returns null on an\n * unterminated quote. `hasMeta` is true if any shell metacharacter appears\n * *outside* quotes (so `grep 'a|b' f` stays classifiable). */\nfunction tokenizeCommandLine(line: string): { tokens: string[]; hasMeta: boolean } | null {\n\tconst tokens: string[] = [];\n\tlet current = \"\";\n\tlet inToken = false;\n\tlet quote: string | null = null;\n\tlet hasMeta = false;\n\tfor (let i = 0; i < line.length; i++) {\n\t\tconst char = line[i] ?? \"\";\n\t\tif (quote) {\n\t\t\tif (char === \"\\\\\" && quote === '\"') {\n\t\t\t\tcurrent += line[++i] ?? \"\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (char === quote) {\n\t\t\t\tquote = null;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcurrent += char;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === '\"' || char === \"'\") {\n\t\t\tquote = char;\n\t\t\tinToken = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === \" \" || char === \"\\t\") {\n\t\t\tif (inToken) {\n\t\t\t\ttokens.push(current);\n\t\t\t\tcurrent = \"\";\n\t\t\t\tinToken = false;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (BASH_SHELL_META_CHARS.has(char) || (char === \"$\" && (line[i + 1] ?? \"\") === \"(\")) {\n\t\t\thasMeta = true;\n\t\t\tcontinue;\n\t\t}\n\t\tcurrent += char;\n\t\tinToken = true;\n\t}\n\tif (quote) return null;\n\tif (inToken) tokens.push(current);\n\treturn { tokens, hasMeta };\n}\n\n/** `head [-n N]` / `tail [-n N]` truncation pipe tail (allowed at the end). */\nfunction isHeadOrTailTail(tokens: readonly string[]): boolean {\n\tif (tokens.length === 0 || (tokens[0] !== \"head\" && tokens[0] !== \"tail\")) return false;\n\tfor (let i = 1; i < tokens.length; i++) {\n\t\tconst token = tokens[i] ?? \"\";\n\t\tif (token === \"-n\") continue;\n\t\tif (/^\\d+$/.test(token)) continue;\n\t\tif (/^-\\d+$/.test(token)) continue;\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n/**\n * Tokenize a single-line bash command and verify it is simple enough to\n * classify: no shell metacharacters (`<`, `>`, `(`, `)`, backtick, `$(`), no\n * `&&`/`;`/`&` outside a leading `cd X &&` chain, and — unless\n * `allowTrailingTruncationPipe` — no pipes at all. Returns null for anything\n * ambiguous so callers fall back to the boxed shell. Newlines and unterminated\n * quotes are rejected.\n */\nexport function parseSimpleBashCommand(\n\tcommand: string,\n\toptions: { allowTrailingTruncationPipe?: boolean } = {},\n): SimpleBashCommandShape | null {\n\tconst commandText = String(command ?? \"\").trim();\n\tif (!commandText || commandText.includes(\"\\n\")) return null;\n\tconst tokenized = tokenizeCommandLine(commandText);\n\tif (!tokenized || tokenized.hasMeta || tokenized.tokens.length === 0) return null;\n\tlet tokens = tokenized.tokens;\n\n\tif (options.allowTrailingTruncationPipe) {\n\t\t// Allow a single trailing truncation pipe: `cmd | head [-n] N` / `| tail …`.\n\t\tconst pipes = tokens.flatMap((token, i) => (token === \"|\" ? [i] : []));\n\t\tif (pipes.length > 0) {\n\t\t\tif (pipes.length > 1) return null;\n\t\t\tconst last = pipes[0] ?? -1;\n\t\t\tif (!isHeadOrTailTail(tokens.slice(last + 1))) return null;\n\t\t\ttokens = tokens.slice(0, last);\n\t\t}\n\t} else if (tokens.includes(\"|\")) {\n\t\t// git/gh classification keeps the pipe rule strict (ADR 0005): any pipe\n\t\t// falls back to the raw boxed shell.\n\t\treturn null;\n\t}\n\n\tlet index = 0;\n\t// Skip leading environment assignments (FOO=bar ...) and prefix commands.\n\twhile (index < tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[index] ?? \"\")) index++;\n\twhile (index < tokens.length && BASH_PREFIX_COMMANDS.has(tokens[index] ?? \"\")) index++;\n\t// `cd <dir> &&` / `cd <dir>;` chains: the last directory becomes the default\n\t// path when the command itself carries none.\n\tlet cdDir: string | undefined;\n\twhile (\n\t\ttokens[index] === \"cd\" &&\n\t\tindex + 2 < tokens.length &&\n\t\ttokens[index + 1] !== undefined &&\n\t\t(tokens[index + 2] === \"&&\" || tokens[index + 2] === \";\")\n\t) {\n\t\tcdDir = tokens[index + 1];\n\t\tindex += 3;\n\t}\n\tconst rest = tokens.slice(index);\n\tif (rest.length === 0 || rest.some((token) => token === \"&&\" || token === \";\" || token === \"&\")) return null;\n\treturn { tokens: rest, ...(cdDir !== undefined ? { cdDir } : {}) };\n}\n","// GitHub (`gh`) semantic view renderer (Phase 8D).\n//\n// Bash `gh pr`/`issue`/`run` results render as a boxless compact card in the\n// call panel, mirroring the git semantic path (see git.ts). `gh run view\n// --job=<id>` renders the job log in a boxed result (the same\n// `renderBoxedToolResult` shape git diff uses), while `gh run watch`, `gh api`,\n// and any command with pipes/redirects/`&&` stay raw (ADR 0005). bash.ts owns\n// the registry and dispatch; this module is registry-free pure functions.\n//\n// Every parser is fail-closed: on any ambiguity it returns null and the boxed\n// command/response shell renders the raw output unchanged. `--json` output is\n// detected by the first non-whitespace character (`{`/`[`); otherwise the\n// table/rich text format is parsed.\n\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport { type BoxTheme, dimLine, renderBoxedToolResult } from \"../../../shared/box.js\";\nimport { formatElapsedMs } from \"../../../shared/elapsed.js\";\nimport { safeTruncateToWidth } from \"../../../shared/render-budget.js\";\nimport { parseSimpleBashCommand } from \"./command-shape.js\";\nimport { pluralForm, TREE_INDENT } from \"./output-tree.js\";\nimport { getStateElapsedMs, getToolsRenderConfig } from \"./session-config.js\";\nimport type { BoxedToolContext } from \"./shared.js\";\n\n// ── Classification ──────────────────────────────────────────────────────────\n\nexport type GhSemanticClass =\n\t| { readonly kind: \"pr-list\" }\n\t| { readonly kind: \"pr-view\" }\n\t| { readonly kind: \"pr-checks\" }\n\t| { readonly kind: \"pr-create\" }\n\t| { readonly kind: \"issue-list\" }\n\t| { readonly kind: \"issue-view\" }\n\t| { readonly kind: \"run-list\" }\n\t| { readonly kind: \"run-view\" }\n\t| { readonly kind: \"run-job\"; readonly jobId: string };\n\n/** Global `gh` flags that consume a separate value token (`-R owner/repo`). */\nconst GH_REPO_VALUE_FLAGS = new Set([\"-R\", \"--repo\"]);\n\n/** Strip `-R <value>` / `--repo <value>` (and attached `--repo=value`) pairs so\n * the command/subcommand words can be located anywhere in the arg list. */\nfunction stripRepoFlags(args: readonly string[]): string[] {\n\tconst out: string[] = [];\n\tfor (let i = 0; i < args.length; ) {\n\t\tconst token = args[i] ?? \"\";\n\t\tif (GH_REPO_VALUE_FLAGS.has(token)) {\n\t\t\ti += 2; // flag + its value\n\t\t\tcontinue;\n\t\t}\n\t\tif (token.startsWith(\"--repo=\")) {\n\t\t\ti += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tout.push(token);\n\t\ti += 1;\n\t}\n\treturn out;\n}\n\n/** Locate the `--job` value (`--job <id>` or `--job=<id>`) on a `run view`. */\nfunction findJobId(args: readonly string[]): string | undefined {\n\tfor (let i = 0; i < args.length; i++) {\n\t\tconst token = args[i] ?? \"\";\n\t\tif (token === \"--job\") return args[i + 1];\n\t\tconst attached = /^--job=(.+)$/.exec(token);\n\t\tif (attached) return attached[1];\n\t}\n\treturn undefined;\n}\n\n/**\n * Classify a bash command for `gh` semantic rendering, or null to keep the\n * boxed shell. Only `gh pr {list,view,checks,create}`, `gh issue {list,view}`,\n * and `gh run {list,view}` are eligible; `gh run view --job=<id>` becomes a\n * `run-job` (boxed log). `gh run watch`, `gh api`, and any other subcommand or\n * pipe/redirect fall back raw (ADR 0005).\n */\nexport function classifyGhCommand(command: string): GhSemanticClass | null {\n\tconst shape = parseSimpleBashCommand(command);\n\tif (!shape) return null;\n\tconst rest = shape.tokens;\n\tif ((rest[0] ?? \"\").split(\"/\").pop() !== \"gh\") return null;\n\tconst args = rest.slice(1);\n\tif (args.length === 0) return null;\n\n\tconst tokens = stripRepoFlags(args);\n\tconst commandWord = tokens[0];\n\tconst subcommand = tokens[1];\n\n\tif (commandWord === \"pr\") {\n\t\tif (subcommand === \"list\") return { kind: \"pr-list\" };\n\t\tif (subcommand === \"view\") return { kind: \"pr-view\" };\n\t\tif (subcommand === \"checks\") return { kind: \"pr-checks\" };\n\t\tif (subcommand === \"create\") return { kind: \"pr-create\" };\n\t\treturn null;\n\t}\n\tif (commandWord === \"issue\") {\n\t\tif (subcommand === \"list\") return { kind: \"issue-list\" };\n\t\tif (subcommand === \"view\") return { kind: \"issue-view\" };\n\t\treturn null;\n\t}\n\tif (commandWord === \"run\") {\n\t\tif (subcommand === \"list\") return { kind: \"run-list\" };\n\t\tif (subcommand === \"view\") {\n\t\t\tconst jobId = findJobId(args);\n\t\t\tif (jobId !== undefined) return { kind: \"run-job\", jobId };\n\t\t\treturn { kind: \"run-view\" };\n\t\t}\n\t\t// `gh run watch` and all other run subcommands stay raw (ADR 0005).\n\t\treturn null;\n\t}\n\treturn null; // `gh api`, extensions, and other subcommands\n}\n\n// ── Parsed shapes ───────────────────────────────────────────────────────────\n\nconst GH_STATES = new Set([\"OPEN\", \"CLOSED\", \"MERGED\"]);\nconst GH_CHECK_STATES = new Set([\n\t\"pass\",\n\t\"fail\",\n\t\"pending\",\n\t\"skipping\",\n\t\"neutral\",\n\t\"cancelled\",\n\t\"timed_out\",\n\t\"startup_failure\",\n\t\"stale\",\n\t\"action_required\",\n]);\n\nexport interface GhListItem {\n\treadonly number: number;\n\treadonly title: string;\n\treadonly branch?: string;\n\treadonly state: string;\n}\n\nexport interface GhListParsed {\n\treadonly kind: \"pr-list\" | \"issue-list\";\n\treadonly rows: readonly GhListItem[];\n}\n\nexport interface GhViewParsed {\n\treadonly kind: \"pr-view\" | \"issue-view\";\n\treadonly title: string;\n\treadonly state: string;\n\treadonly author?: string;\n\treadonly number?: number;\n\treadonly url?: string;\n\treadonly additions?: number;\n\treadonly deletions?: number;\n\treadonly changedFiles?: number;\n\treadonly baseRefName?: string;\n\treadonly headRefName?: string;\n\treadonly reviewers?: string;\n\treadonly reviewDecision?: string;\n\treadonly mergeable?: string;\n\treadonly labels?: string;\n\treadonly body?: string;\n}\n\nexport interface GhCheckRow {\n\treadonly name: string;\n\treadonly state: string;\n\treadonly duration?: string;\n\treadonly url?: string;\n}\n\nexport interface GhChecksParsed {\n\treadonly kind: \"pr-checks\";\n\treadonly rows: readonly GhCheckRow[];\n}\n\nexport interface GhCreateParsed {\n\treadonly kind: \"pr-create\";\n\treadonly url: string;\n\treadonly number?: number;\n}\n\nexport interface GhRunListRow {\n\treadonly status: string;\n\treadonly conclusion?: string;\n\treadonly title: string;\n\treadonly workflow: string;\n\treadonly branch: string;\n\treadonly event: string;\n\treadonly id: string;\n\treadonly elapsed?: string;\n}\n\nexport interface GhRunListParsed {\n\treadonly kind: \"run-list\";\n\treadonly rows: readonly GhRunListRow[];\n}\n\nexport interface GhRunJob {\n\treadonly state: string;\n\treadonly name: string;\n\treadonly count?: number;\n\treadonly duration?: string;\n\treadonly id?: string;\n}\n\nexport interface GhRunAnnotation {\n\treadonly text: string;\n}\n\nexport interface GhRunViewParsed {\n\treadonly kind: \"run-view\";\n\treadonly state?: string;\n\treadonly branch?: string;\n\treadonly workflow?: string;\n\treadonly id?: string;\n\treadonly trigger?: string;\n\treadonly jobs: readonly GhRunJob[];\n\treadonly annotations: readonly GhRunAnnotation[];\n}\n\nexport interface GhRunJobParsed {\n\treadonly kind: \"run-job\";\n\treadonly jobId: string;\n\treadonly lines: readonly string[];\n}\n\nexport type GhParsedSemantic =\n\t| GhListParsed\n\t| GhViewParsed\n\t| GhChecksParsed\n\t| GhCreateParsed\n\t| GhRunListParsed\n\t| GhRunViewParsed\n\t| GhRunJobParsed;\n\n// ── JSON detection ──────────────────────────────────────────────────────────\n\ntype JsonProbe = { readonly json: unknown } | { readonly notJson: true } | null;\n\n/** Probe whether the text is `gh --json` output (starts with `{`/`[`). Returns\n * `{json}` on a successful parse, `{notJson}` for table/rich text, or `null`\n * when the text looks like JSON but fails to parse (hostile). */\nfunction probeJson(text: string): JsonProbe {\n\tconst trimmed = text.trimStart();\n\tconst first = trimmed[0];\n\tif (first !== \"{\" && first !== \"[\") return { notJson: true };\n\ttry {\n\t\treturn { json: JSON.parse(trimmed) };\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction asString(value: unknown): string | undefined {\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction asNumber(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\n/** `author` may be a bare login string or `{ login }` (the `gh --json` shape). */\nfunction authorOf(value: unknown): string | undefined {\n\tif (typeof value === \"string\") return value;\n\tif (value && typeof value === \"object\") return asString((value as Record<string, unknown>).login);\n\treturn undefined;\n}\n\n/** Join an array of `{ login }` / `{ name }` objects into a comma list. */\nfunction nameList(value: unknown, field: \"login\" | \"name\" = \"login\"): string | undefined {\n\tif (!Array.isArray(value) || value.length === 0) return undefined;\n\tconst names = value\n\t\t.map((item) => (item && typeof item === \"object\" ? asString((item as Record<string, unknown>)[field]) : undefined))\n\t\t.filter((name): name is string => typeof name === \"string\");\n\treturn names.length > 0 ? names.join(\", \") : undefined;\n}\n\n// ── list parsers (pr list / issue list) ─────────────────────────────────────\n// Tab-separated default output. `gh pr list` columns are\n// NUMBER<TAB>TITLE<TAB>BRANCH<TAB>STATE<TAB>UPDATED (5); `gh issue list` is\n// NUMBER<TAB>TITLE<TAB>STATE<TAB>UPDATED (4) and may carry labels before STATE.\n// The state token (OPEN/CLOSED/MERGED) is located by content so both shapes\n// parse without a fixed column count.\n\nfunction parseListTable(text: string, kind: \"pr-list\" | \"issue-list\"): GhListParsed | null {\n\tconst rows: GhListItem[] = [];\n\tfor (const rawLine of text.replace(/\\r/g, \"\").split(\"\\n\")) {\n\t\tconst line = rawLine.trimEnd();\n\t\tif (line === \"\") continue;\n\t\tconst fields = line.split(\"\\t\");\n\t\tif (fields.length < 4) return null;\n\t\tconst numberField = fields[0] ?? \"\";\n\t\tif (!/^\\d+$/.test(numberField)) return null;\n\t\tconst title = fields[1] ?? \"\";\n\t\tlet stateIndex = -1;\n\t\tfor (let i = 2; i < fields.length - 1; i++) {\n\t\t\tif (GH_STATES.has((fields[i] ?? \"\").toUpperCase())) {\n\t\t\t\tstateIndex = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (stateIndex < 0) return null;\n\t\tconst state = (fields[stateIndex] ?? \"\").toUpperCase();\n\t\tconst branch = kind === \"pr-list\" ? (fields[2] ?? \"\") : \"\";\n\t\trows.push({\n\t\t\tnumber: Number(numberField),\n\t\t\ttitle,\n\t\t\t...(branch ? { branch } : {}),\n\t\t\tstate,\n\t\t});\n\t}\n\treturn { kind, rows };\n}\n\nfunction parseListJson(json: unknown, kind: \"pr-list\" | \"issue-list\"): GhListParsed | null {\n\tif (!Array.isArray(json)) return null;\n\tconst rows: GhListItem[] = [];\n\tfor (const item of json) {\n\t\tif (!item || typeof item !== \"object\") return null;\n\t\tconst obj = item as Record<string, unknown>;\n\t\tconst number = asNumber(obj.number);\n\t\tif (number === undefined) return null;\n\t\tconst title = asString(obj.title);\n\t\tif (title === undefined) return null;\n\t\tconst stateRaw = asString(obj.state);\n\t\tif (stateRaw === undefined || !GH_STATES.has(stateRaw.toUpperCase())) return null;\n\t\tconst branch = asString(obj.headRefName);\n\t\trows.push({ number, title, state: stateRaw.toUpperCase(), ...(branch ? { branch } : {}) });\n\t}\n\treturn { kind, rows };\n}\n\nfunction parseGhList(text: string, kind: \"pr-list\" | \"issue-list\"): GhListParsed | null {\n\tconst probe = probeJson(text);\n\tif (probe === null) return null;\n\tif (\"notJson\" in probe) return parseListTable(text, kind);\n\treturn parseListJson(probe.json, kind);\n}\n\n// ── view parsers (pr view / issue view) ─────────────────────────────────────\n// Rich output is a block of `key:\\tvalue` pairs, a `--` separator, then the\n// markdown body. `--json` is a single object (base/head/mergeable/changedFiles\n// only appear in JSON; the rich block carries title/state/author/labels/\n// reviewers/number/url/additions/deletions).\n\nconst VIEW_FIELD_LINE = /^([a-zA-Z][a-zA-Z0-9-]*?):\\t(.*)$/;\n\nfunction parseViewRich(text: string, kind: \"pr-view\" | \"issue-view\"): GhViewParsed | null {\n\tconst lines = text.replace(/\\r/g, \"\").split(\"\\n\");\n\tconst fields: Record<string, string> = {};\n\tlet bodyStart = -1;\n\tfor (let i = 0; i < lines.length; i++) {\n\t\tconst line = lines[i] ?? \"\";\n\t\tif (line === \"--\") {\n\t\t\tbodyStart = i + 1;\n\t\t\tbreak;\n\t\t}\n\t\tconst match = VIEW_FIELD_LINE.exec(line);\n\t\tif (!match) {\n\t\t\tif (line.trim() === \"\") continue; // tolerate a stray blank line\n\t\t\treturn null; // unrecognized line → fail closed\n\t\t}\n\t\tconst key = match[1] ?? \"\";\n\t\tconst value = match[2] ?? \"\";\n\t\tif (fields[key] === undefined) fields[key] = value;\n\t}\n\tconst title = fields.title;\n\tconst stateRaw = fields.state;\n\tif (!title || !stateRaw) return null;\n\tconst state = stateRaw.toUpperCase();\n\tconst body = bodyStart >= 0 ? lines.slice(bodyStart).join(\"\\n\").replace(/\\s+$/u, \"\") : undefined;\n\n\tconst number = /^\\d+$/.test(fields.number ?? \"\") ? Number(fields.number) : undefined;\n\tconst additions = /^\\d+$/.test(fields.additions ?? \"\") ? Number(fields.additions) : undefined;\n\tconst deletions = /^\\d+$/.test(fields.deletions ?? \"\") ? Number(fields.deletions) : undefined;\n\n\treturn {\n\t\tkind,\n\t\ttitle,\n\t\tstate,\n\t\t...(fields.author ? { author: fields.author } : {}),\n\t\t...(number !== undefined ? { number } : {}),\n\t\t...(fields.url ? { url: fields.url } : {}),\n\t\t...(additions !== undefined ? { additions } : {}),\n\t\t...(deletions !== undefined ? { deletions } : {}),\n\t\t...(fields.labels ? { labels: fields.labels } : {}),\n\t\t...(fields.reviewers ? { reviewers: fields.reviewers } : {}),\n\t\t...(body?.trim() ? { body } : {}),\n\t};\n}\n\nfunction parseViewJson(json: unknown, kind: \"pr-view\" | \"issue-view\"): GhViewParsed | null {\n\tif (!json || typeof json !== \"object\" || Array.isArray(json)) return null;\n\tconst o = json as Record<string, unknown>;\n\tconst title = asString(o.title);\n\tconst stateRaw = asString(o.state);\n\tif (!title || !stateRaw || !GH_STATES.has(stateRaw.toUpperCase())) return null;\n\tconst state = stateRaw.toUpperCase();\n\tconst author = authorOf(o.author);\n\tconst number = asNumber(o.number);\n\tconst url = asString(o.url);\n\tconst additions = asNumber(o.additions);\n\tconst deletions = asNumber(o.deletions);\n\tconst changedFiles = asNumber(o.changedFiles);\n\tconst baseRefName = asString(o.baseRefName);\n\tconst headRefName = asString(o.headRefName);\n\tconst mergeable = asString(o.mergeable);\n\tconst reviewDecision = asString(o.reviewDecision);\n\tconst reviewers = nameList(o.reviewRequests) ?? nameList(o.reviews);\n\tconst body = asString(o.body);\n\treturn {\n\t\tkind,\n\t\ttitle,\n\t\tstate,\n\t\t...(author ? { author } : {}),\n\t\t...(number !== undefined ? { number } : {}),\n\t\t...(url ? { url } : {}),\n\t\t...(additions !== undefined ? { additions } : {}),\n\t\t...(deletions !== undefined ? { deletions } : {}),\n\t\t...(changedFiles !== undefined ? { changedFiles } : {}),\n\t\t...(baseRefName ? { baseRefName } : {}),\n\t\t...(headRefName ? { headRefName } : {}),\n\t\t...(mergeable ? { mergeable } : {}),\n\t\t...(reviewDecision ? { reviewDecision } : {}),\n\t\t...(reviewers ? { reviewers } : {}),\n\t\t...(body?.trim() ? { body } : {}),\n\t};\n}\n\nfunction parseGhView(text: string, kind: \"pr-view\" | \"issue-view\"): GhViewParsed | null {\n\tconst probe = probeJson(text);\n\tif (probe === null) return null;\n\tif (\"notJson\" in probe) return parseViewRich(text, kind);\n\treturn parseViewJson(probe.json, kind);\n}\n\n// ── pr checks parser ────────────────────────────────────────────────────────\n// `NAME<TAB>STATE<TAB>DURATION<TAB>URL` (states: pass/fail/pending/skipping).\n\nfunction parseChecksTable(text: string): GhChecksParsed | null {\n\tconst rows: GhCheckRow[] = [];\n\tfor (const rawLine of text.replace(/\\r/g, \"\").split(\"\\n\")) {\n\t\tconst line = rawLine.trimEnd();\n\t\tif (line === \"\") continue;\n\t\tconst fields = line.split(\"\\t\");\n\t\tif (fields.length < 2) return null;\n\t\tconst name = fields[0] ?? \"\";\n\t\tconst state = (fields[1] ?? \"\").toLowerCase();\n\t\tif (!GH_CHECK_STATES.has(state)) return null;\n\t\tconst duration = fields[2] !== undefined && fields[2] !== \"\" ? fields[2] : undefined;\n\t\tconst url = fields[3];\n\t\trows.push({\n\t\t\tname,\n\t\t\tstate,\n\t\t\t...(duration ? { duration } : {}),\n\t\t\t...(url ? { url } : {}),\n\t\t});\n\t}\n\treturn { kind: \"pr-checks\", rows };\n}\n\n// ── pr create parser ────────────────────────────────────────────────────────\n// Success prints `https://github.com/<owner>/<repo>/pull/<N>`.\n\nconst PR_CREATE_URL = /^(https:\\/\\/github\\.com\\/[^/\\s]+\\/[^/\\s]+\\/pull\\/(\\d+))/;\n\nfunction parseGhCreate(text: string): GhCreateParsed | null {\n\tconst trimmed = text.replace(/\\r/g, \"\").trim();\n\tconst match = PR_CREATE_URL.exec(trimmed);\n\tif (!match) return null;\n\tconst url = match[1] ?? \"\";\n\tconst number = match[2] !== undefined ? Number(match[2]) : undefined;\n\treturn { kind: \"pr-create\", url, ...(number !== undefined ? { number } : {}) };\n}\n\n// ── run list parser ─────────────────────────────────────────────────────────\n// STATUS<TAB>CONCLUSION<TAB>TITLE<TAB>WORKFLOW<TAB>BRANCH<TAB>EVENT<TAB>ID<TAB>\n// ELAPSED<TAB>AGE. JSON carries databaseId/headBranch/name/workflowName/event.\n\nfunction parseRunListTable(text: string): GhRunListParsed | null {\n\tconst rows: GhRunListRow[] = [];\n\tfor (const rawLine of text.replace(/\\r/g, \"\").split(\"\\n\")) {\n\t\tconst line = rawLine.trimEnd();\n\t\tif (line === \"\") continue;\n\t\tconst fields = line.split(\"\\t\");\n\t\t// Need at least STATUS..CONCLUSION..TITLE..WORKFLOW..BRANCH..EVENT..ID.\n\t\tif (fields.length < 7) return null;\n\t\tconst id = fields[6] ?? \"\";\n\t\tif (!/^\\d+$/.test(id)) return null;\n\t\tconst status = fields[0] ?? \"\";\n\t\tconst conclusionField = fields[1] ?? \"\";\n\t\tconst conclusion = conclusionField !== \"\" ? conclusionField : undefined;\n\t\tconst title = fields[2] ?? \"\";\n\t\tconst workflow = fields[3] ?? \"\";\n\t\tconst branch = fields[4] ?? \"\";\n\t\tconst event = fields[5] ?? \"\";\n\t\tconst elapsed = fields[7] !== undefined && fields[7] !== \"\" ? fields[7] : undefined;\n\t\trows.push({\n\t\t\tstatus,\n\t\t\t...(conclusion ? { conclusion } : {}),\n\t\t\ttitle,\n\t\t\tworkflow,\n\t\t\tbranch,\n\t\t\tevent,\n\t\t\tid,\n\t\t\t...(elapsed ? { elapsed } : {}),\n\t\t});\n\t}\n\treturn { kind: \"run-list\", rows };\n}\n\nfunction parseRunListJson(json: unknown): GhRunListParsed | null {\n\tif (!Array.isArray(json)) return null;\n\tconst rows: GhRunListRow[] = [];\n\tfor (const item of json) {\n\t\tif (!item || typeof item !== \"object\") return null;\n\t\tconst o = item as Record<string, unknown>;\n\t\tconst status = asString(o.status);\n\t\tconst id = asNumber(o.databaseId ?? o.id);\n\t\tif (status === undefined || id === undefined) return null;\n\t\tconst workflow = asString(o.workflowName) ?? asString(o.name) ?? \"\";\n\t\tconst title = asString(o.displayTitle) ?? workflow;\n\t\trows.push({\n\t\t\tstatus,\n\t\t\t...(asString(o.conclusion) ? { conclusion: asString(o.conclusion) as string } : {}),\n\t\t\ttitle,\n\t\t\tworkflow,\n\t\t\tbranch: asString(o.headBranch) ?? \"\",\n\t\t\tevent: asString(o.event) ?? \"\",\n\t\t\tid: String(id),\n\t\t\t...(asString(o.elapsed) ? { elapsed: o.elapsed as string } : {}),\n\t\t});\n\t}\n\treturn { kind: \"run-list\", rows };\n}\n\nfunction parseGhRunList(text: string): GhRunListParsed | null {\n\tconst probe = probeJson(text);\n\tif (probe === null) return null;\n\tif (\"notJson\" in probe) return parseRunListTable(text);\n\treturn parseRunListJson(probe.json);\n}\n\n// ── run view parser ─────────────────────────────────────────────────────────\n// Rich output: a status line `✓|✗|◌ <branch> <workflow> · <id>`, an optional\n// `Triggered via …` line, a `JOBS` block of `✓|✗|◌ <name> (N) in <dur> (ID id)`\n// rows, an optional `ANNOTATIONS` block of `! …` rows, then trailing hint\n// lines (`For more information…`, `View this run on GitHub:…`) which are skipped.\n\nconst RUN_VIEW_STATUS_LINE = /^([✓✗◌*])\\s+(\\S+)\\s+(.+?)\\s+·\\s+(\\d+)\\s*$/u;\nconst RUN_VIEW_JOB_LINE = /^([✓✗◌*])\\s+(.+?)\\s+\\((\\d+)\\)\\s+in\\s+(\\S+)\\s+\\(ID\\s+(\\d+)\\)\\s*$/u;\n\nfunction isRunViewHint(line: string): boolean {\n\treturn line.startsWith(\"For more information about the job, try:\") || line.startsWith(\"View this run on GitHub:\");\n}\n\nfunction parseGhRunView(text: string): GhRunViewParsed | null {\n\tconst lines = text.replace(/\\r/g, \"\").split(\"\\n\");\n\tlet idx = 0;\n\twhile (idx < lines.length && (lines[idx] ?? \"\").trim() === \"\") idx++;\n\tif (idx >= lines.length) return null;\n\n\tconst statusMatch = RUN_VIEW_STATUS_LINE.exec(lines[idx] ?? \"\");\n\tif (!statusMatch) return null;\n\tconst state = statusMatch[1] ?? \"\";\n\tconst branch = statusMatch[2] ?? \"\";\n\tconst workflow = statusMatch[3] ?? \"\";\n\tconst id = statusMatch[4] ?? \"\";\n\tidx++;\n\n\t// Optional `Triggered via …` line.\n\tlet trigger: string | undefined;\n\twhile (idx < lines.length && (lines[idx] ?? \"\").trim() === \"\") idx++;\n\tif (idx < lines.length && /^Triggered via .+/.test(lines[idx] ?? \"\")) {\n\t\ttrigger = lines[idx];\n\t\tidx++;\n\t}\n\n\tconst jobs: GhRunJob[] = [];\n\tconst annotations: GhRunAnnotation[] = [];\n\n\tconst skipBlanks = () => {\n\t\twhile (idx < lines.length && (lines[idx] ?? \"\").trim() === \"\") idx++;\n\t};\n\n\tskipBlanks();\n\tif ((lines[idx] ?? \"\") === \"JOBS\") {\n\t\tidx++;\n\t\twhile (idx < lines.length) {\n\t\t\tconst line = lines[idx] ?? \"\";\n\t\t\tif (line === \"\") {\n\t\t\t\tidx++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (line === \"ANNOTATIONS\" || isRunViewHint(line)) break;\n\t\t\tconst jobMatch = RUN_VIEW_JOB_LINE.exec(line);\n\t\t\tif (!jobMatch) return null;\n\t\t\tjobs.push({\n\t\t\t\tstate: jobMatch[1] ?? \"\",\n\t\t\t\tname: jobMatch[2] ?? \"\",\n\t\t\t\tcount: Number(jobMatch[3] ?? 0),\n\t\t\t\tduration: jobMatch[4] ?? \"\",\n\t\t\t\tid: jobMatch[5] ?? \"\",\n\t\t\t});\n\t\t\tidx++;\n\t\t}\n\t}\n\n\tskipBlanks();\n\tif ((lines[idx] ?? \"\") === \"ANNOTATIONS\") {\n\t\tidx++;\n\t\twhile (idx < lines.length) {\n\t\t\tconst line = lines[idx] ?? \"\";\n\t\t\tif (line === \"\") {\n\t\t\t\tidx++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (isRunViewHint(line)) break;\n\t\t\tconst annotationMatch = /^!\\s+(.+)$/.exec(line);\n\t\t\tif (annotationMatch) {\n\t\t\t\tannotations.push({ text: annotationMatch[1] ?? \"\" });\n\t\t\t\tidx++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Location-reference row following a `! …` message (`check (22):\n\t\t\t// .github#2`) — a dim source pointer, not a new annotation.\n\t\t\tconst sourceMatch = /^[A-Za-z0-9_ ./()-]+\\(\\d+\\): \\S+#\\d+$/.exec(line);\n\t\t\tif (sourceMatch) {\n\t\t\t\tannotations.push({ text: line });\n\t\t\t\tidx++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t// Only hint/blank lines may follow; anything else fails closed.\n\tfor (let i = idx; i < lines.length; i++) {\n\t\tconst line = lines[i] ?? \"\";\n\t\tif (line.trim() === \"\") continue;\n\t\tif (isRunViewHint(line)) continue;\n\t\treturn null;\n\t}\n\n\treturn {\n\t\tkind: \"run-view\",\n\t\t...(state ? { state } : {}),\n\t\t...(branch ? { branch } : {}),\n\t\t...(workflow ? { workflow } : {}),\n\t\t...(id ? { id } : {}),\n\t\t...(trigger ? { trigger } : {}),\n\t\tjobs,\n\t\tannotations,\n\t};\n}\n\n// ── run job parser ──────────────────────────────────────────────────────────\n// The job log is raw text; any output is a valid log body (the boxed result\n// owns width-truncation and a render budget). It never fails closed.\n\nfunction parseGhRunJob(text: string, jobId: string): GhRunJobParsed {\n\tconst body = String(text ?? \"\").replace(/\\r/g, \"\");\n\tconst lines = body.split(\"\\n\");\n\tif (lines.length > 0 && lines[lines.length - 1] === \"\") lines.pop();\n\treturn { kind: \"run-job\", jobId, lines };\n}\n\n// ── Dispatch helpers (used by bash.ts) ──────────────────────────────────────\n\nexport function parseGhOutput(cls: GhSemanticClass, output: string): GhParsedSemantic | null {\n\tconst text = String(output ?? \"\");\n\tswitch (cls.kind) {\n\t\tcase \"pr-list\":\n\t\t\treturn parseGhList(text, \"pr-list\");\n\t\tcase \"issue-list\":\n\t\t\treturn parseGhList(text, \"issue-list\");\n\t\tcase \"pr-view\":\n\t\t\treturn parseGhView(text, \"pr-view\");\n\t\tcase \"issue-view\":\n\t\t\treturn parseGhView(text, \"issue-view\");\n\t\tcase \"pr-checks\":\n\t\t\treturn parseChecksTable(text);\n\t\tcase \"pr-create\":\n\t\t\treturn parseGhCreate(text);\n\t\tcase \"run-list\":\n\t\t\treturn parseGhRunList(text);\n\t\tcase \"run-view\":\n\t\t\treturn parseGhRunView(text);\n\t\tcase \"run-job\":\n\t\t\treturn parseGhRunJob(text, cls.jobId);\n\t}\n}\n\n// ── Rendering ───────────────────────────────────────────────────────────────\n\n/** Nerd Font GitHub mark glyph used on gh card headers in Nerd Font mode. */\nexport const GH_ICON = \"\\u{F408}\";\n\nconst GH_CARD_HEAD_LIMIT = 6;\nconst GH_BODY_PREVIEW_LINES = 8;\n\nfunction ghCardHeader(theme: BoxTheme, cls: GhSemanticClass, parsed?: GhParsedSemantic): string {\n\tconst icon = getToolsRenderConfig().nerdFonts ? `${GH_ICON} ` : \"\";\n\tlet prefix: string;\n\tswitch (cls.kind) {\n\t\tcase \"pr-list\":\n\t\t\tprefix = `${icon}PRs`;\n\t\t\tbreak;\n\t\tcase \"pr-view\":\n\t\t\tprefix = `${icon}PR`;\n\t\t\tbreak;\n\t\tcase \"pr-checks\":\n\t\t\tprefix = `${icon}PR checks`;\n\t\t\tbreak;\n\t\tcase \"pr-create\":\n\t\t\tprefix = `${icon}PR created`;\n\t\t\tbreak;\n\t\tcase \"issue-list\":\n\t\t\tprefix = `${icon}Issues`;\n\t\t\tbreak;\n\t\tcase \"issue-view\":\n\t\t\tprefix = `${icon}Issue`;\n\t\t\tbreak;\n\t\tcase \"run-list\":\n\t\t\tprefix = `${icon}Runs`;\n\t\t\tbreak;\n\t\tcase \"run-view\":\n\t\t\tprefix = `${icon}Run`;\n\t\t\tbreak;\n\t\tcase \"run-job\":\n\t\t\tprefix = `${icon}Run job`;\n\t\t\tbreak;\n\t}\n\tif (parsed) {\n\t\tif (parsed.kind === \"pr-view\" || parsed.kind === \"issue-view\") {\n\t\t\tif (parsed.number !== undefined) prefix += ` #${parsed.number}`;\n\t\t\tprefix += ` · ${parsed.title}`;\n\t\t} else if (parsed.kind === \"pr-create\") {\n\t\t\tif (parsed.number !== undefined) prefix += ` #${parsed.number}`;\n\t\t} else if (parsed.kind === \"run-view\") {\n\t\t\tif (parsed.workflow) prefix += ` · ${parsed.workflow}`;\n\t\t\tif (parsed.id) prefix += ` · ${parsed.id}`;\n\t\t} else if (parsed.kind === \"run-job\") {\n\t\t\tprefix += ` · ${parsed.jobId}`;\n\t\t}\n\t}\n\treturn typeof theme?.bold === \"function\" ? theme.bold(prefix) : prefix;\n}\n\n/** State color for an OPEN/CLOSED/MERGED value. */\nfunction ghStateColor(state: string): string {\n\tif (state === \"OPEN\") return \"accent\";\n\tif (state === \"MERGED\") return \"toolDiffAdded\";\n\treturn \"dim\"; // CLOSED\n}\n\n/** Colored run glyph from a status/conclusion pair (✓ success, ✗ failure,\n * ◌ in-progress/queued, dim for skipped/cancelled). */\nfunction runGlyph(theme: BoxTheme, status: string, conclusion?: string): string {\n\tif (status === \"completed\") {\n\t\tif (conclusion === \"success\") return theme.fg(\"toolDiffAdded\", \"✓\");\n\t\tif (conclusion === \"failure\") return theme.fg(\"error\", \"✗\");\n\t\treturn theme.fg(\"dim\", \"◌\"); // cancelled / skipped / neutral\n\t}\n\treturn theme.fg(\"warning\", \"◌\"); // in_progress / queued / waiting\n}\n\n/** Colored run glyph from a raw ✓/✗/◌ token (run-view jobs). */\nfunction runStateGlyph(theme: BoxTheme, glyph: string): string {\n\tif (glyph === \"✓\") return theme.fg(\"toolDiffAdded\", \"✓\");\n\tif (glyph === \"✗\") return theme.fg(\"error\", \"✗\");\n\treturn theme.fg(\"warning\", \"◌\");\n}\n\n/** Check-state color (pass/fail/pending/skipping/…). */\nfunction checkStateColor(state: string): string {\n\tif (state === \"pass\") return \"toolDiffAdded\";\n\tif (state === \"fail\") return \"error\";\n\tif (state === \"pending\") return \"warning\";\n\treturn \"dim\"; // skipping / neutral / cancelled / …\n}\n\nfunction renderMoreRow(theme: BoxTheme, unit: string, more: number, width: number): string {\n\treturn safeTruncateToWidth(\n\t\t`${TREE_INDENT}${dimLine(\"└─\")} ${theme.fg(\"dim\", `… ${more} more ${pluralForm(unit, more)}`)}`,\n\t\twidth,\n\t\t\"…\",\n\t);\n}\n\nfunction renderListCard(theme: BoxTheme, parsed: GhListParsed, out: string[], width: number): string[] {\n\tconst rows = parsed.rows;\n\tconst noun = parsed.kind === \"pr-list\" ? \"PR\" : \"issue\";\n\tif (rows.length === 0) {\n\t\tout.push(theme.fg(\"muted\", ` no open ${pluralForm(noun, 2)}`));\n\t\treturn out;\n\t}\n\tout.push(` ${theme.fg(\"accent\", `${rows.length} ${pluralForm(noun, rows.length)}`)}`);\n\n\tconst visible = rows.slice(0, GH_CARD_HEAD_LIMIT);\n\tconst more = rows.length - visible.length;\n\tconst lastIndex = visible.length - 1;\n\tfor (let i = 0; i < visible.length; i++) {\n\t\tconst row = visible[i];\n\t\tif (!row) continue;\n\t\tconst branchGlyph = i < lastIndex || more > 0 ? \"├─\" : \"└─\";\n\t\tconst color = ghStateColor(row.state);\n\t\tconst num = theme.fg(color, `#${row.number}`);\n\t\tconst title = theme.fg(\"toolOutput\", row.title);\n\t\tconst stateSuffix = row.state !== \"OPEN\" ? theme.fg(\"dim\", ` (${row.state.toLowerCase()})`) : \"\";\n\t\tconst branchPart = row.branch ? theme.fg(\"dim\", ` ${row.branch}`) : \"\";\n\t\tconst line = `${TREE_INDENT}${dimLine(branchGlyph)} ${num} ${title}${stateSuffix}${branchPart}`;\n\t\tout.push(safeTruncateToWidth(line, width, \"…\"));\n\t}\n\tif (more > 0) out.push(renderMoreRow(theme, noun, more, width));\n\treturn out;\n}\n\nfunction renderBodyPreview(theme: BoxTheme, body: string, out: string[], width: number): string[] {\n\tconst bodyLines = body.replace(/\\s+$/u, \"\").split(\"\\n\");\n\tconst visible = bodyLines.slice(0, GH_BODY_PREVIEW_LINES);\n\tfor (const line of visible) {\n\t\tout.push(safeTruncateToWidth(` ${theme.fg(\"muted\", line)}`, width, \"…\"));\n\t}\n\tconst more = bodyLines.length - visible.length;\n\tif (more > 0) {\n\t\tout.push(safeTruncateToWidth(` ${theme.fg(\"dim\", `… ${more} more lines · Ctrl+O`)}`, width, \"…\"));\n\t}\n\treturn out;\n}\n\nfunction renderViewCard(theme: BoxTheme, parsed: GhViewParsed, out: string[], width: number): string[] {\n\tconst stateParts = [theme.fg(ghStateColor(parsed.state), parsed.state)];\n\tif (parsed.baseRefName && parsed.headRefName) {\n\t\tstateParts.push(theme.fg(\"dim\", \"·\"), theme.fg(\"text\", `${parsed.baseRefName} → ${parsed.headRefName}`));\n\t}\n\tout.push(safeTruncateToWidth(` ${stateParts.join(theme.fg(\"dim\", \" \"))}`, width, \"…\"));\n\n\tconst summaryParts: string[] = [];\n\tconst diffParts: string[] = [];\n\tif (parsed.additions !== undefined && parsed.additions > 0) {\n\t\tdiffParts.push(theme.fg(\"toolDiffAdded\", `+${parsed.additions}`));\n\t}\n\tif (parsed.deletions !== undefined && parsed.deletions > 0) {\n\t\tdiffParts.push(theme.fg(\"toolDiffRemoved\", `-${parsed.deletions}`));\n\t}\n\tif (diffParts.length > 0) summaryParts.push(diffParts.join(\" \"));\n\tif (parsed.changedFiles !== undefined) {\n\t\tsummaryParts.push(theme.fg(\"accent\", `${parsed.changedFiles} ${pluralForm(\"file\", parsed.changedFiles)}`));\n\t}\n\tif (summaryParts.length > 0) {\n\t\tout.push(safeTruncateToWidth(` ${summaryParts.join(theme.fg(\"dim\", \" · \"))}`, width, \"…\"));\n\t}\n\n\tif (parsed.author) {\n\t\tout.push(safeTruncateToWidth(` ${theme.fg(\"dim\", \"author\")} ${theme.fg(\"text\", parsed.author)}`, width, \"…\"));\n\t}\n\tif (parsed.reviewers) {\n\t\tout.push(\n\t\t\tsafeTruncateToWidth(` ${theme.fg(\"dim\", \"reviewers\")} ${theme.fg(\"toolOutput\", parsed.reviewers)}`, width, \"…\"),\n\t\t);\n\t} else if (parsed.reviewDecision) {\n\t\tout.push(\n\t\t\tsafeTruncateToWidth(` ${theme.fg(\"dim\", \"review\")} ${theme.fg(\"text\", parsed.reviewDecision)}`, width, \"…\"),\n\t\t);\n\t}\n\tif (parsed.mergeable) {\n\t\tout.push(\n\t\t\tsafeTruncateToWidth(` ${theme.fg(\"dim\", \"mergeable\")} ${theme.fg(\"text\", parsed.mergeable)}`, width, \"…\"),\n\t\t);\n\t}\n\tif (parsed.body?.trim()) renderBodyPreview(theme, parsed.body, out, width);\n\treturn out;\n}\n\nfunction renderChecksCard(theme: BoxTheme, parsed: GhChecksParsed, out: string[], width: number): string[] {\n\tconst rows = parsed.rows;\n\tif (rows.length === 0) {\n\t\tout.push(theme.fg(\"muted\", \" no checks reported\"));\n\t\treturn out;\n\t}\n\tconst visible = rows.slice(0, GH_CARD_HEAD_LIMIT);\n\tconst more = rows.length - visible.length;\n\tconst lastIndex = visible.length - 1;\n\tfor (let i = 0; i < visible.length; i++) {\n\t\tconst row = visible[i];\n\t\tif (!row) continue;\n\t\tconst branchGlyph = i < lastIndex || more > 0 ? \"├─\" : \"└─\";\n\t\tconst name = theme.fg(\"toolOutput\", row.name);\n\t\tconst state = theme.fg(checkStateColor(row.state), row.state);\n\t\tconst duration = row.duration && row.duration !== \"0\" ? theme.fg(\"dim\", ` ${row.duration}`) : \"\";\n\t\tconst line = `${TREE_INDENT}${dimLine(branchGlyph)} ${name} ${state}${duration}`;\n\t\tout.push(safeTruncateToWidth(line, width, \"…\"));\n\t}\n\tif (more > 0) out.push(renderMoreRow(theme, \"check\", more, width));\n\treturn out;\n}\n\nfunction renderCreateCard(theme: BoxTheme, parsed: GhCreateParsed, out: string[], width: number): string[] {\n\tout.push(safeTruncateToWidth(` ${theme.fg(\"text\", parsed.url)}`, width, \"…\"));\n\treturn out;\n}\n\nfunction renderRunListCard(theme: BoxTheme, parsed: GhRunListParsed, out: string[], width: number): string[] {\n\tconst rows = parsed.rows;\n\tif (rows.length === 0) {\n\t\tout.push(theme.fg(\"muted\", \" no recent runs\"));\n\t\treturn out;\n\t}\n\tconst visible = rows.slice(0, GH_CARD_HEAD_LIMIT);\n\tconst more = rows.length - visible.length;\n\tconst lastIndex = visible.length - 1;\n\tfor (let i = 0; i < visible.length; i++) {\n\t\tconst row = visible[i];\n\t\tif (!row) continue;\n\t\tconst branchGlyph = i < lastIndex || more > 0 ? \"├─\" : \"└─\";\n\t\tconst glyph = runGlyph(theme, row.status, row.conclusion);\n\t\tconst workflow = theme.fg(\"text\", row.workflow || row.title);\n\t\tconst branch = theme.fg(\"dim\", ` ${row.branch}`);\n\t\tconst id = theme.fg(\"dim\", ` ${row.id}`);\n\t\tconst line = `${TREE_INDENT}${dimLine(branchGlyph)} ${glyph} ${workflow}${branch}${id}`;\n\t\tout.push(safeTruncateToWidth(line, width, \"…\"));\n\t}\n\tif (more > 0) out.push(renderMoreRow(theme, \"run\", more, width));\n\treturn out;\n}\n\nfunction renderRunViewCard(theme: BoxTheme, parsed: GhRunViewParsed, out: string[], width: number): string[] {\n\tif (parsed.trigger) {\n\t\tout.push(safeTruncateToWidth(` ${theme.fg(\"dim\", parsed.trigger)}`, width, \"…\"));\n\t}\n\tconst visibleJobs = parsed.jobs.slice(0, GH_CARD_HEAD_LIMIT);\n\tconst moreJobs = parsed.jobs.length - visibleJobs.length;\n\tconst lastJobIndex = visibleJobs.length - 1;\n\tfor (let i = 0; i < visibleJobs.length; i++) {\n\t\tconst job = visibleJobs[i];\n\t\tif (!job) continue;\n\t\tconst branchGlyph = i < lastJobIndex || moreJobs > 0 || parsed.annotations.length > 0 ? \"├─\" : \"└─\";\n\t\tconst glyph = runStateGlyph(theme, job.state);\n\t\tconst name = theme.fg(\"toolOutput\", `${job.name}${job.count !== undefined ? ` (${job.count})` : \"\"}`);\n\t\tconst detail = theme.fg(\"dim\", `${job.duration ? ` ${job.duration}` : \"\"}${job.id ? ` · ${job.id}` : \"\"}`);\n\t\tconst line = `${TREE_INDENT}${dimLine(branchGlyph)} ${glyph} ${name}${detail}`;\n\t\tout.push(safeTruncateToWidth(line, width, \"…\"));\n\t}\n\tif (moreJobs > 0) out.push(renderMoreRow(theme, \"job\", moreJobs, width));\n\tfor (let i = 0; i < parsed.annotations.length; i++) {\n\t\tconst annotation = parsed.annotations[i];\n\t\tif (!annotation) continue;\n\t\tconst branchGlyph = i < parsed.annotations.length - 1 ? \"├─\" : \"└─\";\n\t\tconst line = `${TREE_INDENT}${dimLine(branchGlyph)} ${theme.fg(\"warning\", \"!\")} ${theme.fg(\"dim\", annotation.text)}`;\n\t\tout.push(safeTruncateToWidth(line, width, \"…\"));\n\t}\n\treturn out;\n}\n\n/**\n * Render the gh semantic card for one call: the header always renders (so a\n * pending call shows a single summary line); once the result parses, counts,\n * rows, and a body preview follow. `run-job` renders its header here while the\n * log body lives in the boxed result. Every line is width-safe.\n */\nexport function renderGhCardLines(\n\ttheme: BoxTheme,\n\tstate: { readonly cls: GhSemanticClass; readonly parsed?: GhParsedSemantic },\n\twidth: number,\n): string[] {\n\tconst safeWidth = Math.max(1, width);\n\tconst out: string[] = [safeTruncateToWidth(ghCardHeader(theme, state.cls, state.parsed), safeWidth, \"…\")];\n\tconst parsed = state.parsed;\n\tif (!parsed) return out;\n\tif (parsed.kind === \"pr-list\" || parsed.kind === \"issue-list\") renderListCard(theme, parsed, out, safeWidth);\n\telse if (parsed.kind === \"pr-view\" || parsed.kind === \"issue-view\") renderViewCard(theme, parsed, out, safeWidth);\n\telse if (parsed.kind === \"pr-checks\") renderChecksCard(theme, parsed, out, safeWidth);\n\telse if (parsed.kind === \"pr-create\") renderCreateCard(theme, parsed, out, safeWidth);\n\telse if (parsed.kind === \"run-list\") renderRunListCard(theme, parsed, out, safeWidth);\n\telse if (parsed.kind === \"run-view\") renderRunViewCard(theme, parsed, out, safeWidth);\n\t// run-job: header only — the log body renders in the boxed result.\n\treturn out.map((line) => safeTruncateToWidth(line, safeWidth, \"…\"));\n}\n\n// ── Boxed run-job log result (Phase 8D) ────────────────────────────────────\n// `gh run view --job=<id>` log output renders in a `renderBoxedToolResult`\n// frame with a `Log · <job-id>` divider and an elapsed footer, mirroring the\n// git diff boxed result. The call panel renders the boxless `Run job · <id>`\n// header; the log body lives in the box. A render budget bounds very long logs\n// (collapsed/expanded), and `renderBoxedToolResult` width-truncates each line.\n\nconst GH_RUN_JOB_BUDGET_COLLAPSED = 40;\nconst GH_RUN_JOB_BUDGET_EXPANDED = 200;\n\n/** Build a complete boxed-log result component for a parsed `gh run view --job`. */\nexport function renderGhRunJobResult(\n\ttheme: BoxTheme,\n\tparsed: GhRunJobParsed,\n\toptions: { expanded: boolean },\n\tcontext: BoxedToolContext,\n): Component {\n\tconst expanded = Boolean(options.expanded);\n\tconst elapsedMs = getStateElapsedMs(context.state);\n\tconst footerParts: string[] = [];\n\tif (elapsedMs !== undefined) footerParts.push(theme.fg(\"text\", formatElapsedMs(elapsedMs)));\n\tconst footer = footerParts.join(theme.fg(\"dim\", \" · \"));\n\tconst hasLog = parsed.lines.some((line) => line.trim() !== \"\");\n\tconst budget = expanded ? GH_RUN_JOB_BUDGET_EXPANDED : GH_RUN_JOB_BUDGET_COLLAPSED;\n\treturn renderBoxedToolResult(\n\t\ttheme,\n\t\t() => (hasLog ? parsed.lines.map((line) => theme.fg(\"toolOutput\", line)) : [theme.fg(\"muted\", \"No log output\")]),\n\t\t{\n\t\t\tdividerLabel: `Log · ${parsed.jobId}`,\n\t\t\tfooterLines: footer ? [footer] : [],\n\t\t\trenderLineBudget: budget,\n\t\t},\n\t);\n}\n","// Git semantic view renderer (Phase 8A).\n//\n// Bash `git status` / `git diff --stat` / short `git log` results render as a\n// boxless compact card in the call panel, mirroring the ls/find/grep tree path\n// (see bash.ts, which owns the per-call registry and raw-shell fallback).\n//\n// Every parser is fail-closed (ADR 0005): on any ambiguity it returns null and\n// the boxed command/response shell renders the raw output unchanged. Only\n// values git's output actually carries are shown — `git diff --stat` bars are\n// scaled, so per-file rows show the exact `| N` change count instead of a\n// guessed +/− split, and the exact +/− totals come from the summary line.\n\nimport { getLanguageFromPath } from \"@earendil-works/pi-coding-agent\";\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport {\n\ttype BoxTheme,\n\tboxBlankLine,\n\tboxLabeledBorder,\n\tboxWidth,\n\tdimLine,\n\trenderBoxedToolResult,\n} from \"../../../shared/box.js\";\nimport { formatElapsedMs } from \"../../../shared/elapsed.js\";\nimport { safeTruncateToWidth } from \"../../../shared/render-budget.js\";\nimport { AdaptiveDiffComponent, buildSplitRows, countDiffStats } from \"../../../shared/split-diff.js\";\nimport { parseSimpleBashCommand } from \"./command-shape.js\";\nimport { pluralForm, TREE_INDENT } from \"./output-tree.js\";\nimport { getStateElapsedMs, getToolsRenderConfig } from \"./session-config.js\";\nimport type { BoxedToolContext } from \"./shared.js\";\n\n// ── Classification ──────────────────────────────────────────────────────────\n\n/** State-change git commands that render a boxless summary card (Phase 8C):\n * `commit`/`push`/`pull`/`fetch` (8C-1) plus `switch`/`checkout`/`add`/\n * `restore`/`reset`/`merge`/`rebase` (8C-2). Each surfaces a different shape;\n * the parsers are fail-closed and the renderer switches on `command`. */\nexport type GitActionCommand =\n\t| \"commit\"\n\t| \"push\"\n\t| \"pull\"\n\t| \"fetch\"\n\t| \"switch\"\n\t| \"checkout\"\n\t| \"add\"\n\t| \"restore\"\n\t| \"reset\"\n\t| \"merge\"\n\t| \"rebase\";\n\nexport type GitSemanticClass =\n\t| { readonly kind: \"status\"; readonly short: boolean }\n\t| { readonly kind: \"diff-stat\" }\n\t| { readonly kind: \"log\" }\n\t| { readonly kind: \"show-stat\" }\n\t| { readonly kind: \"diff\"; readonly show: boolean }\n\t| { readonly kind: \"action\"; readonly command: GitActionCommand };\n\nconst GIT_SHORT_STATUS_FLAGS = new Set([\"-s\", \"--short\", \"--porcelain\"]);\nconst GIT_DIFF_FORMAT_REJECT = new Set([\n\t\"-p\",\n\t\"--patch\",\n\t\"--numstat\",\n\t\"--shortstat\",\n\t\"--dirstat\",\n\t\"--summary\",\n\t\"--name-only\",\n\t\"--name-status\",\n\t\"--raw\",\n\t\"--word-diff\",\n]);\n/** Flags that switch `git diff` patch output to a non-line-based or summary\n * shape we cannot feed to the adaptive diff component (ADR 0005: fail-closed). */\nconst GIT_DIFF_PATCH_REJECT = new Set([\n\t\"--numstat\",\n\t\"--shortstat\",\n\t\"--dirstat\",\n\t\"--summary\",\n\t\"--name-only\",\n\t\"--name-status\",\n\t\"--raw\",\n\t\"--word-diff\",\n\t\"--binary\",\n\t\"--no-patch\",\n\t\"-s\",\n\t\"--patch-with-stat\",\n\t\"--patch-with-raw\",\n]);\n/** `git show` (plain patch output) additionally rejects `--stat` (commit + stat\n * is a different shape) and commit-format flags that change the header. */\nconst GIT_SHOW_REJECT = new Set([...GIT_DIFF_PATCH_REJECT, \"--stat\", \"--oneline\", \"--format\", \"--pretty\"]);\n/** `git show --stat` (commit header + stat block) rejects any other\n * format-changing flag that would alter that shape: `-p`/`--patch` append a\n * patch, the rest are alternate stat/format/name shapes (ADR 0005). */\nconst GIT_SHOW_STAT_REJECT = new Set([...GIT_DIFF_PATCH_REJECT, \"-p\", \"--patch\", \"--oneline\"]);\nconst GIT_LOG_FORMAT_REJECT = new Set([\n\t\"-p\",\n\t\"--patch\",\n\t\"--stat\",\n\t\"--numstat\",\n\t\"--shortstat\",\n\t\"--dirstat\",\n\t\"--summary\",\n\t\"--name-only\",\n\t\"--name-status\",\n\t\"--raw\",\n\t\"--graph\",\n\t\"--format\",\n\t\"--pretty\",\n\t\"--word-diff\",\n\t\"--color\",\n\t\"--show-signature\",\n]);\n\n/** `git commit` flags that change the output shape: `-v` appends the diff,\n * `-p`/`--patch` open an editor with a patch, `-i`/`--interactive` are\n * interactive, `--porcelain`/`--dry-run` swap to a different report\n * (ADR 0005: fail-closed). */\nconst GIT_COMMIT_REJECT = new Set([\n\t\"-v\",\n\t\"--verbose\",\n\t\"-p\",\n\t\"--patch\",\n\t\"-i\",\n\t\"--interactive\",\n\t\"--porcelain\",\n\t\"--dry-run\",\n]);\n/** `git push` flags that change the output shape: `--porcelain` is machine\n * format, `-v`/`--verbose` add `Pushing to`/`= [up to date]` lines, and\n * `--dry-run` reports what would happen without doing it (ADR 0005). */\nconst GIT_PUSH_REJECT = new Set([\"--porcelain\", \"-v\", \"--verbose\", \"--dry-run\", \"-n\"]);\n/** `git pull` flags that change the output shape: `-v`/`--verbose` add fetch\n * chatter, `--rebase` produces a rebase-shaped report instead of a merge\n * summary (ADR 0005). */\nconst GIT_PULL_REJECT = new Set([\"-v\", \"--verbose\", \"--rebase\"]);\n/** `git fetch` flags that change the output shape: `-v`/`--verbose` add\n * `= [up to date]` per-ref chatter and `--dry-run` reports without fetching\n * (ADR 0005). */\nconst GIT_FETCH_REJECT = new Set([\"-v\", \"--verbose\", \"--dry-run\"]);\n/** `git switch`/`checkout` flags that change the output shape: `-p`/`--patch`\n * open an interactive hunk picker, `-i`/`--interactive` is the classic checkout\n * TUI, and `--orphan` swaps the `Switched to …` line for a creation report\n * (ADR 0005). `-m` (merge on switch) is not rejected here — its clean output\n * still parses, and the merge-rows shape fails closed in the parser. */\nconst GIT_SWITCH_REJECT = new Set([\"-p\", \"--patch\", \"-i\", \"--interactive\", \"--orphan\"]);\n/** `git add`/`restore` flags that change the output shape: `-p`/`--patch` and\n * `-i`/`--interactive` open hunk/TUI pickers, and `-v`/`--verbose` list every\n * staged path instead of staying silent (ADR 0005). */\nconst GIT_ADD_REJECT = new Set([\"-p\", \"--patch\", \"-i\", \"--interactive\", \"-v\", \"--verbose\"]);\n/** `git reset` flags that change the output shape: `-p`/`--patch` opens an\n * interactive hunk picker. The mode flags (`--soft`/`--mixed`/`--hard`) are\n * the shapes the parser reads, so they stay classified (ADR 0005). */\nconst GIT_RESET_REJECT = new Set([\"-p\", \"--patch\"]);\n/** `git merge` flags that change the output shape: `-v`/`--verbose` append the\n * per-file diff. `--squash`/`--abort`/`--continue` produce different reports\n * that fail closed in the parser (ADR 0005). */\nconst GIT_MERGE_REJECT = new Set([\"-v\", \"--verbose\"]);\n/** `git rebase` flags that change the output shape entirely: `-i`/\n * `--interactive` opens the commit-list editor and `-x`/`--exec` runs a shell\n * command per commit, swapping the single success line for a different report\n * (ADR 0005). */\nconst GIT_REBASE_REJECT = new Set([\"-i\", \"--interactive\", \"-x\", \"--exec\"]);\n\n/**\n * Classify a bash command for git semantic rendering, or null to keep the\n * boxed shell. Only porcelain commands with simple output shapes are eligible\n * (`git status`, `git diff --stat`, `git log`); `git -C …`, aliases, plumbing\n * (`cat-file`, `rev-parse`, `for-each-ref`), format-changing flags, and any\n * pipe/redirect fall back raw (ADR 0005).\n */\nexport function classifyGitCommand(command: string): GitSemanticClass | null {\n\tconst shape = parseSimpleBashCommand(command);\n\tif (!shape) return null;\n\tconst rest = shape.tokens;\n\tif ((rest[0] ?? \"\").split(\"/\").pop() !== \"git\") return null;\n\tconst args = rest.slice(1);\n\tif (args.length === 0) return null;\n\tconst sub = args[0] ?? \"\";\n\n\tif (sub === \"status\") {\n\t\t// `-z`/`--porcelain=v2` switch the output format entirely; the v1 short\n\t\t// parser cannot read them.\n\t\tif (args.some((arg) => arg === \"-z\" || arg === \"--null\" || arg.startsWith(\"--porcelain=v2\"))) return null;\n\t\tconst short =\n\t\t\targs.some((arg) => GIT_SHORT_STATUS_FLAGS.has(arg) || /^-[sS][a-zA-Z]*$/.test(arg)) ||\n\t\t\targs.some((arg) => arg.startsWith(\"--porcelain=v1\"));\n\t\treturn { kind: \"status\", short };\n\t}\n\tif (sub === \"diff\") {\n\t\tconst hasStat = args.some((arg) => arg === \"--stat\" || arg.startsWith(\"--stat=\"));\n\t\tif (hasStat) {\n\t\t\tif (\n\t\t\t\targs.some(\n\t\t\t\t\t(arg) => GIT_DIFF_FORMAT_REJECT.has(arg) || arg.startsWith(\"--format=\") || arg.startsWith(\"--pretty=\"),\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn { kind: \"diff-stat\" };\n\t\t}\n\t\t// Plain `git diff` (patch output) renders as a boxed adaptive diff. Reject\n\t\t// format-changing flags; `-p`/`--patch` is the default patch shape and stays.\n\t\tif (args.some((arg) => GIT_DIFF_PATCH_REJECT.has(arg) || arg.startsWith(\"--word-diff=\"))) {\n\t\t\treturn null;\n\t\t}\n\t\treturn { kind: \"diff\", show: false };\n\t}\n\tif (sub === \"show\") {\n\t\tconst hasStat = args.some((arg) => arg === \"--stat\" || arg.startsWith(\"--stat=\"));\n\t\tif (hasStat) {\n\t\t\t// `git show --stat` = commit header + stat block → a diff-stat-shaped\n\t\t\t// card. Reject any other format-changing flag (a patch, numstat,\n\t\t\t// name-only, format override, …). `-p`/`--patch` append a patch; combined\n\t\t\t// short clusters containing `p` (e.g. `-sp`) do too.\n\t\t\tif (\n\t\t\t\targs.some(\n\t\t\t\t\t(arg) =>\n\t\t\t\t\t\tGIT_SHOW_STAT_REJECT.has(arg) ||\n\t\t\t\t\t\t/^-[A-Za-z]*p[A-Za-z]*$/.test(arg) ||\n\t\t\t\t\t\targ.startsWith(\"--word-diff=\") ||\n\t\t\t\t\t\targ.startsWith(\"--format=\") ||\n\t\t\t\t\t\targ.startsWith(\"--pretty=\"),\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn { kind: \"show-stat\" };\n\t\t}\n\t\t// Plain `git show` (patch output) renders as a boxed adaptive diff. Reject\n\t\t// format-changing flags; `-p`/`--patch` is the default patch shape and stays.\n\t\tif (\n\t\t\targs.some(\n\t\t\t\t(arg) =>\n\t\t\t\t\tGIT_SHOW_REJECT.has(arg) ||\n\t\t\t\t\targ.startsWith(\"--word-diff=\") ||\n\t\t\t\t\targ.startsWith(\"--format=\") ||\n\t\t\t\t\targ.startsWith(\"--pretty=\"),\n\t\t\t)\n\t\t) {\n\t\t\treturn null;\n\t\t}\n\t\treturn { kind: \"diff\", show: true };\n\t}\n\tif (sub === \"log\") {\n\t\tif (\n\t\t\targs.some((arg) => GIT_LOG_FORMAT_REJECT.has(arg) || arg.startsWith(\"--format=\") || arg.startsWith(\"--pretty=\"))\n\t\t) {\n\t\t\treturn null;\n\t\t}\n\t\treturn { kind: \"log\" };\n\t}\n\tif (sub === \"commit\") {\n\t\tif (args.some((arg) => GIT_COMMIT_REJECT.has(arg) || /^-[A-Za-z]*[vpi][A-Za-z]*$/.test(arg))) return null;\n\t\treturn { kind: \"action\", command: \"commit\" };\n\t}\n\tif (sub === \"push\") {\n\t\tif (args.some((arg) => GIT_PUSH_REJECT.has(arg) || /^-[A-Za-z]*[vn][A-Za-z]*$/.test(arg))) return null;\n\t\treturn { kind: \"action\", command: \"push\" };\n\t}\n\tif (sub === \"pull\") {\n\t\tif (args.some((arg) => GIT_PULL_REJECT.has(arg) || /^-[A-Za-z]*v[A-Za-z]*$/.test(arg))) return null;\n\t\treturn { kind: \"action\", command: \"pull\" };\n\t}\n\tif (sub === \"fetch\") {\n\t\tif (args.some((arg) => GIT_FETCH_REJECT.has(arg) || /^-[A-Za-z]*v[A-Za-z]*$/.test(arg))) return null;\n\t\treturn { kind: \"action\", command: \"fetch\" };\n\t}\n\tif (sub === \"switch\" || sub === \"checkout\") {\n\t\t// Reject interactive patch/TUI and orphan; `-m` stays (clean output parses,\n\t\t// merge-rows shape fails closed). Short clusters containing `p`/`i` cover\n\t\t// `-p`/`-i` bundled with other flags.\n\t\tif (args.some((arg) => GIT_SWITCH_REJECT.has(arg) || /^-[A-Za-z]*[pi][A-Za-z]*$/.test(arg))) return null;\n\t\treturn { kind: \"action\", command: sub };\n\t}\n\tif (sub === \"add\" || sub === \"restore\") {\n\t\t// Reject interactive patch/TUI and verbose; `-A`/`-u`/`-f`/`-S`/`-W` stay.\n\t\tif (args.some((arg) => GIT_ADD_REJECT.has(arg) || /^-[A-Za-z]*[piv][A-Za-z]*$/.test(arg))) return null;\n\t\treturn { kind: \"action\", command: sub };\n\t}\n\tif (sub === \"reset\") {\n\t\t// Reject interactive patch; the mode flags (`--soft`/`--mixed`/`--hard`)\n\t\t// are the shapes the parser reads.\n\t\tif (args.some((arg) => GIT_RESET_REJECT.has(arg) || /^-[A-Za-z]*p[A-Za-z]*$/.test(arg))) return null;\n\t\treturn { kind: \"action\", command: \"reset\" };\n\t}\n\tif (sub === \"merge\") {\n\t\t// Reject verbose; `--squash`/`--abort`/`--continue` fail closed in the parser.\n\t\tif (args.some((arg) => GIT_MERGE_REJECT.has(arg) || /^-[A-Za-z]*v[A-Za-z]*$/.test(arg))) return null;\n\t\treturn { kind: \"action\", command: \"merge\" };\n\t}\n\tif (sub === \"rebase\") {\n\t\t// Reject interactive/exec; `--abort`/`--continue`/`--skip` fail closed.\n\t\tif (\n\t\t\targs.some(\n\t\t\t\t(arg) => GIT_REBASE_REJECT.has(arg) || arg.startsWith(\"--exec=\") || /^-[A-Za-z]*[ix][A-Za-z]*$/.test(arg),\n\t\t\t)\n\t\t)\n\t\t\treturn null;\n\t\treturn { kind: \"action\", command: \"rebase\" };\n\t}\n\treturn null;\n}\n\n// ── Parsed shapes ───────────────────────────────────────────────────────────\n\nexport interface GitStatusFile {\n\t/** Index (staged) status char: `M`/`A`/`D`/`R`/`C`/`T`/`U`/`?`/`!` or space. */\n\treadonly x: string;\n\t/** Worktree (unstaged) status char, or space. */\n\treadonly y: string;\n\t/** Display path; renames carry `old -> new`. */\n\treadonly path: string;\n}\n\nexport interface GitStatusParsed {\n\treadonly kind: \"status\";\n\treadonly branch?: string;\n\treadonly ahead?: number;\n\treadonly behind?: number;\n\treadonly diverged?: boolean;\n\treadonly files: readonly GitStatusFile[];\n}\n\nexport interface GitDiffStatFile {\n\treadonly path: string;\n\t/** Exact changed-line count from the `| N` column (absent for binary files). */\n\treadonly changes?: number;\n\treadonly binary?: boolean;\n}\n\n/** Per-file stat summary shared by `git diff --stat` and `git show --stat`\n * (the show-stat card adds a commit header on top of these rows). */\ninterface DiffStatSummary {\n\treadonly files: readonly GitDiffStatFile[];\n\treadonly filesChanged?: number;\n\treadonly insertions?: number;\n\treadonly deletions?: number;\n}\n\nexport interface GitDiffStatParsed extends DiffStatSummary {\n\treadonly kind: \"diff-stat\";\n}\n\n/** `git show --stat`: full-format commit header (hash + first message-line\n * subject) followed by the same per-file stat block as `git diff --stat`. */\nexport interface GitShowStatParsed extends DiffStatSummary {\n\treadonly kind: \"show-stat\";\n\t/** Full commit hash from the `commit <hash>` header (shortened for display). */\n\treadonly hash: string;\n\treadonly subject: string;\n}\n\nexport interface GitLogCommit {\n\treadonly hash: string;\n\treadonly refs?: string;\n\treadonly subject: string;\n}\n\nexport interface GitLogParsed {\n\treadonly kind: \"log\";\n\treadonly commits: readonly GitLogCommit[];\n}\n\nexport interface GitDiffFile {\n\t/** Display path (renames carry `old => new`). */\n\treadonly path: string;\n\treadonly status?: \"added\" | \"deleted\" | \"renamed\" | \"modified\";\n\treadonly binary?: boolean;\n\treadonly additions: number;\n\treadonly removals: number;\n\t/** Normalized edit-format diff body for `AdaptiveDiffComponent` (empty for binary). */\n\treadonly body: string;\n}\n\nexport interface GitDiffParsed {\n\treadonly kind: \"diff\";\n\treadonly show: boolean;\n\t/** `git show`: short commit hash from the commit header. */\n\treadonly hash?: string;\n\t/** `git show`: first message-line subject. */\n\treadonly subject?: string;\n\treadonly files: readonly GitDiffFile[];\n}\n\n/** `git commit` / `push` / `pull` / `fetch` / `switch` / `checkout` / `add` /\n * `restore` / `reset` / `merge` / `rebase` state-change results. Each command\n * surfaces a different subset of fields; the renderer switches on `command`.\n * Stat summaries (commit / pull fast-forward / merge) reuse the diff-stat\n * shape so the same `N files changed · +A -D` line and `├─/└─` rows render\n * verbatim. */\nexport interface GitActionParsed extends DiffStatSummary {\n\treadonly kind: \"action\";\n\treadonly command: GitActionCommand;\n\t/** `git commit` success: branch from `[<branch> <hash>]` (status line owns\n\t * the `⎇ main` glyph, so this is not rendered). */\n\treadonly branch?: string;\n\t/** `git commit` success: short hash from `[<branch> <hash>]`; also\n\t * `git reset --hard`: the `HEAD is now at <hash>` target. */\n\treadonly hash?: string;\n\t/** `git commit` success: commit subject line; also `git reset --hard`:\n\t * the `HEAD is now at <hash> <subject>` subject. */\n\treadonly subject?: string;\n\t/** `git push` / `git fetch`: remote URL/path from the `To `/`From ` line. */\n\treadonly remote?: string;\n\t/** `git push` / `git fetch`: normalized ref-update rows (alignment spaces\n\t * collapsed to single spaces). */\n\treadonly refs?: readonly string[];\n\t/** Informational status line: `nothing to commit`, `Everything up-to-date`,\n\t * `Already up to date.`, `Fast-forward`, `no new refs`, `Merge made by the\n\t * 'ort' strategy.`, or `completed, no output` for silent success\n\t * (`add`/`restore`/`reset --soft`/`checkout -- <file>`). */\n\treadonly status?: string;\n\t/** `git pull` / `git merge` fast-forward: the `Updating <a>..<b>` range. */\n\treadonly range?: string;\n\t/** `git switch -c` / `git checkout -b`: the branch was created, not just\n\t * switched to (controls the confirmation row wording). */\n\treadonly created?: boolean;\n\t/** `git reset` (mixed): status-marker + path rows from the\n\t * `Unstaged changes after reset:` block (marker in `x`, `y` is space). */\n\treadonly resetFiles?: readonly GitStatusFile[];\n}\n\nexport type GitParsedSemantic =\n\t| GitStatusParsed\n\t| GitDiffStatParsed\n\t| GitShowStatParsed\n\t| GitLogParsed\n\t| GitDiffParsed\n\t| GitActionParsed;\n\n// ── git status parsers ──────────────────────────────────────────────────────\n\n/** Long-form section verbs → `(index, worktree)` status chars. */\nconst LONG_STATUS_VERBS: Readonly<Record<string, readonly [string, string]>> = {\n\t\"new file\": [\"A\", \" \"],\n\tmodified: [\"M\", \" \"],\n\tdeleted: [\"D\", \" \"],\n\trenamed: [\"R\", \" \"],\n\tcopied: [\"C\", \" \"],\n\ttypechange: [\"T\", \" \"],\n\t\"both modified\": [\"U\", \"U\"],\n\t\"both added\": [\"A\", \"A\"],\n\t\"both deleted\": [\"D\", \"D\"],\n\t\"added by us\": [\"A\", \"U\"],\n\t\"added by them\": [\"U\", \"A\"],\n\t\"deleted by us\": [\"D\", \"U\"],\n\t\"deleted by them\": [\"U\", \"D\"],\n\tunmerged: [\"U\", \"U\"],\n};\n\ntype LongSection = \"staged\" | \"unstaged\" | \"untracked\" | \"ignored\" | \"unmerged\" | null;\n\nconst LONG_SECTION_HEADERS: Readonly<Record<string, LongSection>> = {\n\t\"Changes to be committed:\": \"staged\",\n\t\"Changes not staged for commit:\": \"unstaged\",\n\t\"Untracked files:\": \"untracked\",\n\t\"Ignored files:\": \"ignored\",\n\t\"Unmerged paths:\": \"unmerged\",\n};\n\nconst LONG_STATUS_ENTRY = /^([a-z ]+?):\\s+(.+)$/;\nconst LONG_BRANCH = /^On branch (.+)$/;\nconst LONG_DETACHED = /^HEAD detached at ([0-9a-f]+)/;\nconst LONG_AHEAD = /^Your branch is ahead of '(.*)' by (\\d+) commit/;\nconst LONG_BEHIND = /^Your branch is behind '(.*)' by (\\d+) commit/;\nconst LONG_DIVERGED = /^Your branch and '(.*)' have diverged/;\nconst LONG_DIVERGED_COUNTS = /^and have (\\d+) and (\\d+) different commits each/;\n\nfunction parseGitStatusLong(text: string): GitStatusParsed | null {\n\tconst files: GitStatusFile[] = [];\n\tlet branch: string | undefined;\n\tlet ahead: number | undefined;\n\tlet behind: number | undefined;\n\tlet diverged = false;\n\tlet section: LongSection = null;\n\tlet divergedNext = false;\n\tlet sawContent = false;\n\n\tfor (const rawLine of text.split(\"\\n\")) {\n\t\tconst line = rawLine.trimEnd();\n\t\tif (line === \"\") continue;\n\n\t\tconst branchMatch = LONG_BRANCH.exec(line);\n\t\tif (branchMatch) {\n\t\t\tsawContent = true;\n\t\t\tbranch = branchMatch[1];\n\t\t\tcontinue;\n\t\t}\n\t\tconst detached = LONG_DETACHED.exec(line);\n\t\tif (detached) {\n\t\t\tsawContent = true;\n\t\t\tbranch = detached[1];\n\t\t\tcontinue;\n\t\t}\n\t\tconst aheadMatch = LONG_AHEAD.exec(line);\n\t\tif (aheadMatch) {\n\t\t\tsawContent = true;\n\t\t\tahead = Number(aheadMatch[2]);\n\t\t\tcontinue;\n\t\t}\n\t\tconst behindMatch = LONG_BEHIND.exec(line);\n\t\tif (behindMatch) {\n\t\t\tsawContent = true;\n\t\t\tbehind = Number(behindMatch[2]);\n\t\t\tcontinue;\n\t\t}\n\t\tconst divergedMatch = LONG_DIVERGED.exec(line);\n\t\tif (divergedMatch) {\n\t\t\tsawContent = true;\n\t\t\tdiverged = true;\n\t\t\tdivergedNext = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (divergedNext) {\n\t\t\tconst counts = LONG_DIVERGED_COUNTS.exec(line);\n\t\t\tif (!counts) return null;\n\t\t\tsawContent = true;\n\t\t\tahead = Number(counts[1]);\n\t\t\tbehind = Number(counts[2]);\n\t\t\tdivergedNext = false;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst sectionHeader = LONG_SECTION_HEADERS[line];\n\t\tif (sectionHeader !== undefined) {\n\t\t\tsawContent = true;\n\t\t\tsection = sectionHeader;\n\t\t\tcontinue;\n\t\t}\n\t\t// Hint lines (` (use \"git add …\" …)`, ` (fix conflicts …)`) and\n\t\t// clean/empty-state markers.\n\t\tif (/^\\s{2}\\(/.test(line)) continue;\n\t\tif (\n\t\t\tline.startsWith(\"no changes added to commit\") ||\n\t\t\tline === \"nothing to commit, working tree clean\" ||\n\t\t\tline === \"You have unmerged paths.\" ||\n\t\t\tline === \"No commits yet\"\n\t\t) {\n\t\t\tsawContent = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.startsWith(\"Your branch is up to date with \")) {\n\t\t\tsawContent = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (line.startsWith(\"\\t\")) {\n\t\t\tconst body = line.slice(1).trimStart();\n\t\t\tif (!body) return null;\n\t\t\t// Untracked/ignored entries are bare paths.\n\t\t\tif (section === \"untracked\" || section === \"ignored\") {\n\t\t\t\tconst mark = section === \"untracked\" ? \"?\" : \"!\";\n\t\t\t\tsawContent = true;\n\t\t\t\tfiles.push({ x: mark, y: mark, path: body });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst verbMatch = LONG_STATUS_ENTRY.exec(body);\n\t\t\tif (!verbMatch) return null;\n\t\t\tconst xy = LONG_STATUS_VERBS[verbMatch[1] ?? \"\"];\n\t\t\tif (!xy) return null; // unknown verb (localized git, unexpected section)\n\t\t\tconst path = (verbMatch[2] ?? \"\").trim();\n\t\t\tif (!path) return null;\n\t\t\tsawContent = true;\n\t\t\tif (section === \"staged\") files.push({ x: xy[0], y: \" \", path });\n\t\t\telse if (section === \"unstaged\") files.push({ x: \" \", y: xy[0], path });\n\t\t\telse files.push({ x: xy[0], y: xy[1], path });\n\t\t\tcontinue;\n\t\t}\n\n\t\treturn null; // unrecognized non-tab line → localized/hostile output\n\t}\n\tif (divergedNext) return null;\n\tif (!sawContent) return null;\n\treturn {\n\t\tkind: \"status\",\n\t\tfiles,\n\t\t...(branch !== undefined ? { branch } : {}),\n\t\t...(ahead !== undefined ? { ahead } : {}),\n\t\t...(behind !== undefined ? { behind } : {}),\n\t\t...(diverged ? { diverged: true } : {}),\n\t};\n}\n\nconst SHORT_STATUS_BRANCH = /^## (.+)$/;\nconst SHORT_STATUS_BRANCH_DETAIL = /^(.+?)(?:\\.\\.\\.(.+?))?(?: \\[([^\\]]+)\\])?$/;\nconst SHORT_STATUS_FILE = /^([ MADRCU?!])([ MADRCU?!]) (.*)$/;\n\nfunction parseGitStatusShort(text: string): GitStatusParsed | null {\n\tif (text.includes(\"\\u0000\")) return null; // `-z` NUL-separated format\n\tconst files: GitStatusFile[] = [];\n\tlet branch: string | undefined;\n\tlet ahead: number | undefined;\n\tlet behind: number | undefined;\n\tlet diverged = false;\n\tlet sawStatus = false;\n\n\tfor (const rawLine of text.split(\"\\n\")) {\n\t\tconst line = rawLine.trimEnd();\n\t\tif (line === \"\") continue;\n\n\t\tconst branchLine = SHORT_STATUS_BRANCH.exec(line);\n\t\tif (branchLine) {\n\t\t\tsawStatus = true;\n\t\t\tconst detail = SHORT_STATUS_BRANCH_DETAIL.exec(branchLine[1] ?? \"\");\n\t\t\tif (detail) {\n\t\t\t\tbranch = detail[1];\n\t\t\t\tconst bracket = detail[3];\n\t\t\t\tif (bracket) {\n\t\t\t\t\tconst aheadM = /ahead (\\d+)/.exec(bracket);\n\t\t\t\t\tconst behindM = /behind (\\d+)/.exec(bracket);\n\t\t\t\t\tif (aheadM) ahead = Number(aheadM[1]);\n\t\t\t\t\tif (behindM) behind = Number(behindM[1]);\n\t\t\t\t\tif (aheadM && behindM) diverged = true;\n\t\t\t\t\t// `[gone]` and other bracket states carry no counts — ignored.\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst fileMatch = SHORT_STATUS_FILE.exec(line);\n\t\tif (!fileMatch) return null; // unrecognized line → hostile output\n\t\tsawStatus = true;\n\t\tfiles.push({ x: fileMatch[1] ?? \"\", y: fileMatch[2] ?? \"\", path: fileMatch[3] ?? \"\" });\n\t}\n\n\tif (!sawStatus && text.trim() !== \"\") return null;\n\treturn {\n\t\tkind: \"status\",\n\t\tfiles,\n\t\t...(branch !== undefined ? { branch } : {}),\n\t\t...(ahead !== undefined ? { ahead } : {}),\n\t\t...(behind !== undefined ? { behind } : {}),\n\t\t...(diverged ? { diverged: true } : {}),\n\t};\n}\n\nfunction parseGitStatus(cls: GitSemanticClass, text: string): GitStatusParsed | null {\n\tif (cls.kind !== \"status\") return null;\n\treturn cls.short ? parseGitStatusShort(text) : parseGitStatusLong(text);\n}\n\n// ── git diff --stat parser ──────────────────────────────────────────────────\n\nconst DIFF_STAT_SUMMARY = /^\\s*(\\d+) files? changed(?:, (\\d+) insertions?\\(\\+\\))?(?:, (\\d+) deletions?\\(-\\))?$/;\nconst DIFF_STAT_FILE = /^(.*)\\s+\\|\\s+(\\d+)\\s*.*$/;\nconst DIFF_STAT_BINARY = /^(.*)\\s+\\|\\s+Bin\\s+.*$/;\n\nfunction parseGitDiffStat(text: string): GitDiffStatParsed | null {\n\tconst files: GitDiffStatFile[] = [];\n\tlet filesChanged: number | undefined;\n\tlet insertions: number | undefined;\n\tlet deletions: number | undefined;\n\tlet sawLine = false;\n\n\tfor (const rawLine of text.split(\"\\n\")) {\n\t\tconst line = rawLine.trimEnd();\n\t\tif (line === \"\") continue;\n\t\tsawLine = true;\n\n\t\tconst summary = DIFF_STAT_SUMMARY.exec(line);\n\t\tif (summary) {\n\t\t\tfilesChanged = Number(summary[1]);\n\t\t\tif (summary[2] !== undefined) insertions = Number(summary[2]);\n\t\t\tif (summary[3] !== undefined) deletions = Number(summary[3]);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst binary = DIFF_STAT_BINARY.exec(line);\n\t\tif (binary) {\n\t\t\tconst path = (binary[1] ?? \"\").trim();\n\t\t\tif (!path) return null;\n\t\t\tfiles.push({ path, binary: true });\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst file = DIFF_STAT_FILE.exec(line);\n\t\tif (file) {\n\t\t\tconst path = (file[1] ?? \"\").trim();\n\t\t\tif (!path) return null;\n\t\t\tfiles.push({ path, changes: Number(file[2]) });\n\t\t\tcontinue;\n\t\t}\n\n\t\treturn null; // unrecognized line (--numstat/-z output, stat=width oddities)\n\t}\n\n\tif (!sawLine) return { kind: \"diff-stat\", files }; // empty diff → no changes\n\tif (files.length === 0 && filesChanged === undefined) return null;\n\treturn {\n\t\tkind: \"diff-stat\",\n\t\tfiles,\n\t\t...(filesChanged !== undefined ? { filesChanged } : {}),\n\t\t...(insertions !== undefined ? { insertions } : {}),\n\t\t...(deletions !== undefined ? { deletions } : {}),\n\t};\n}\n\n// ── git log parser ──────────────────────────────────────────────────────────\n\nconst LOG_COMMIT_LINE = /^commit ([0-9a-f]{4,40})(?: \\((.*)\\))?$/;\nconst LOG_ONELINE = /^([0-9a-f]{4,40})(?: \\(([^)]*)\\))?\\s*(.*)$/;\nconst LOG_HEADER_LINE = /^(?:Author|Date|Merge):/;\nconst LOG_MESSAGE_LINE = /^\\s{4}(.*)$/;\n\nfunction parseGitLog(text: string): GitLogParsed | null {\n\tconst lines = text\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trimEnd())\n\t\t.filter((line) => line.length > 0);\n\tif (lines.length === 0) return { kind: \"log\", commits: [] };\n\n\t// Oneline format (`git log --oneline`): every line is `hash [refs] subject`.\n\tif (lines.every((line) => LOG_ONELINE.test(line))) {\n\t\tconst commits = lines.map((line) => {\n\t\t\tconst match = LOG_ONELINE.exec(line);\n\t\t\tconst refs = match?.[2];\n\t\t\treturn {\n\t\t\t\thash: match?.[1] ?? \"\",\n\t\t\t\t...(refs ? { refs } : {}),\n\t\t\t\tsubject: (match?.[3] ?? \"\").trim(),\n\t\t\t};\n\t\t});\n\t\treturn { kind: \"log\", commits };\n\t}\n\n\t// Full format: `commit <hash> [refs]` blocks with Author/Date/Merge headers\n\t// and a 4-space-indented message.\n\tconst commits: GitLogCommit[] = [];\n\tlet current: { hash: string; refs?: string; subject: string } | null = null;\n\tfor (const line of lines) {\n\t\tconst start = LOG_COMMIT_LINE.exec(line);\n\t\tif (start) {\n\t\t\tcurrent = {\n\t\t\t\thash: start[1] ?? \"\",\n\t\t\t\t...(start[2] ? { refs: start[2] } : {}),\n\t\t\t\tsubject: \"\",\n\t\t\t};\n\t\t\tcommits.push(current);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!current) return null;\n\t\tif (LOG_HEADER_LINE.test(line)) continue;\n\t\tconst message = LOG_MESSAGE_LINE.exec(line);\n\t\tif (message) {\n\t\t\tif (current.subject === \"\") current.subject = (message[1] ?? \"\").trim();\n\t\t\tcontinue;\n\t\t}\n\t\treturn null; // unexpected line inside a commit block (patch/format output)\n\t}\n\tif (commits.length === 0) return null;\n\treturn { kind: \"log\", commits };\n}\n\n// ── git show --stat parser ───────────────────────────────────────────────────\n// `git show --stat` = a full-format commit header (the same shape `parseGitLog`\n// reads: `commit <hash>`, Author/Date/Merge, 4-space-indented message) followed\n// by the same stat block `parseGitDiffStat` reads. The header is consumed first\n// (subject = first message line), then the remainder is handed to the diff-stat\n// line parser; any hostile line fails closed → raw boxed shell (ADR 0005).\n\nfunction parseGitShowStat(text: string): GitShowStatParsed | null {\n\tconst lines = String(text ?? \"\")\n\t\t.replace(/\\r/g, \"\")\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trimEnd());\n\tlet i = 0;\n\twhile (i < lines.length && (lines[i] ?? \"\") === \"\") i++; // skip leading blanks\n\tif (i >= lines.length) return null;\n\tconst commitMatch = LOG_COMMIT_LINE.exec(lines[i] ?? \"\");\n\tif (!commitMatch) return null; // not a `git show` commit header\n\tconst hash = commitMatch[1] ?? \"\";\n\ti++;\n\tlet subject = \"\";\n\t// Consume the commit header: Author/Date/Merge lines, blank lines, and the\n\t// 4-space-indented message block (subject = first message line). The first\n\t// line that is none of these begins the stat block. Stat rows carry only a\n\t// single leading space, so they never match the 4-space message pattern.\n\twhile (i < lines.length) {\n\t\tconst line = lines[i] ?? \"\";\n\t\tif (line === \"\") {\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (LOG_HEADER_LINE.test(line)) {\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tconst message = LOG_MESSAGE_LINE.exec(line);\n\t\tif (message) {\n\t\t\tif (subject === \"\") subject = (message[1] ?? \"\").trim();\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tbreak;\n\t}\n\t// The remainder is the diff-stat block (empty for a commit with no file\n\t// changes). Reuse the diff-stat line parser, fail-closed on hostile lines.\n\tconst stat = parseGitDiffStat(lines.slice(i).join(\"\\n\"));\n\tif (!stat) return null;\n\treturn {\n\t\tkind: \"show-stat\",\n\t\thash,\n\t\tsubject,\n\t\tfiles: stat.files,\n\t\t...(stat.filesChanged !== undefined ? { filesChanged: stat.filesChanged } : {}),\n\t\t...(stat.insertions !== undefined ? { insertions: stat.insertions } : {}),\n\t\t...(stat.deletions !== undefined ? { deletions: stat.deletions } : {}),\n\t};\n}\n\n// ── git diff / git show parser ──────────────────────────────────────────────\n// Splits unified diff output into per-file chunks, strips file headers and\n// hunk headers, and converts content lines into the numbered `<prefix> <num>\n// <content>` shape `buildSplitRows` (the `AdaptiveDiffComponent` input) reads.\n// Every ambiguity returns null → the boxed Bash shell renders raw (ADR 0005).\n\nconst DIFF_GIT_HEADER = /^diff --git a\\/(.*) b\\/(.*)$/;\nconst HUNK_HEADER = /^@@ -(\\d+)(?:,\\d+)? \\+(\\d+)(?:,\\d+)? @@/;\nconst NEW_FILE_MODE = /^new file mode /;\nconst DELETED_FILE_MODE = /^deleted file mode /;\n\n/** Strip the `a/` / `b/` prefix (and surrounding quotes) from a `--- `/`+++ ` path. */\nfunction stripDiffPathPrefix(rawPath: string): string {\n\tlet path = rawPath;\n\tif (path.startsWith('\"') && path.endsWith('\"')) path = path.slice(1, -1);\n\tif (path.startsWith(\"a/\")) return path.slice(2);\n\tif (path.startsWith(\"b/\")) return path.slice(2);\n\treturn path;\n}\n\nfunction parseDiffChunk(chunk: readonly string[]): GitDiffFile | null {\n\tconst header = chunk[0] ?? \"\";\n\tconst dgMatch = DIFF_GIT_HEADER.exec(header);\n\tif (!dgMatch) return null;\n\tconst dgOld = dgMatch[1] ?? undefined;\n\tconst dgNew = dgMatch[2] ?? undefined;\n\n\tlet oldPath: string | undefined;\n\tlet newPath: string | undefined;\n\tlet status: GitDiffFile[\"status\"];\n\tlet binary = false;\n\tlet renameDetected = false;\n\tconst bodyLines: string[] = [];\n\tlet additions = 0;\n\tlet removals = 0;\n\tlet inHunk = false;\n\tlet oldLine = 0;\n\tlet newLine = 0;\n\n\tfor (let i = 1; i < chunk.length; i++) {\n\t\tconst line = chunk[i] ?? \"\";\n\n\t\tconst hunk = HUNK_HEADER.exec(line);\n\t\tif (hunk) {\n\t\t\toldLine = Number(hunk[1] ?? 0);\n\t\t\tnewLine = Number(hunk[2] ?? 0);\n\t\t\tinHunk = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!inHunk) {\n\t\t\tif (line === \"\") continue; // section separator\n\t\t\tif (line.startsWith(\"index \")) continue;\n\t\t\tif (NEW_FILE_MODE.test(line)) {\n\t\t\t\tstatus = \"added\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (DELETED_FILE_MODE.test(line)) {\n\t\t\t\tstatus = \"deleted\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (line.startsWith(\"old mode \") || line.startsWith(\"new mode \")) continue;\n\t\t\tif (line.startsWith(\"similarity index \") || line.startsWith(\"dissimilarity index \")) {\n\t\t\t\trenameDetected = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (line.startsWith(\"rename from \")) {\n\t\t\t\toldPath = line.slice(\"rename from \".length);\n\t\t\t\trenameDetected = true;\n\t\t\t\tstatus = \"renamed\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (line.startsWith(\"rename to \")) {\n\t\t\t\tnewPath = line.slice(\"rename to \".length);\n\t\t\t\trenameDetected = true;\n\t\t\t\tstatus = \"renamed\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (line.startsWith(\"copy from \") || line.startsWith(\"copy to \")) continue;\n\t\t\tif (line.startsWith(\"--- \")) {\n\t\t\t\tconst value = line.slice(4);\n\t\t\t\tif (value !== \"/dev/null\") oldPath = stripDiffPathPrefix(value);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (line.startsWith(\"+++ \")) {\n\t\t\t\tconst value = line.slice(4);\n\t\t\t\tif (value !== \"/dev/null\") newPath = stripDiffPathPrefix(value);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (line.startsWith(\"Binary files \") || line === \"Binary files differ\") {\n\t\t\t\tbinary = true;\n\t\t\t\tconst bm = line.match(/^Binary files (?:a\\/(\\S*) )?and (?:b\\/(\\S*) )?differ/);\n\t\t\t\tif (bm) {\n\t\t\t\t\tif (!oldPath && bm[1]) oldPath = bm[1];\n\t\t\t\t\tif (!newPath && bm[2]) newPath = bm[2];\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (line.startsWith(\"GIT binary patch\")) return null; // unparseable binary patch body\n\t\t\treturn null; // unrecognized header line → hostile/localized output\n\t\t}\n\n\t\t// inside a hunk\n\t\tif (line.startsWith(\"\\\\ No newline\")) continue;\n\t\tif (line.startsWith(\"+\")) {\n\t\t\tbodyLines.push(`+ ${newLine} ${line.slice(1)}`);\n\t\t\tnewLine++;\n\t\t\tadditions++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.startsWith(\"-\")) {\n\t\t\tbodyLines.push(`- ${oldLine} ${line.slice(1)}`);\n\t\t\toldLine++;\n\t\t\tremovals++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.startsWith(\" \")) {\n\t\t\tbodyLines.push(` ${oldLine} ${line.slice(1)}`);\n\t\t\toldLine++;\n\t\t\tnewLine++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (line === \"\") {\n\t\t\t// Blank context line whose leading space was stripped (trailing-ws\n\t\t\t// safety): keep it as an empty context row so the diff stays aligned.\n\t\t\tbodyLines.push(` ${oldLine} `);\n\t\t\toldLine++;\n\t\t\tnewLine++;\n\t\t\tcontinue;\n\t\t}\n\t\treturn null; // unexpected line inside a hunk\n\t}\n\n\tif (!newPath) newPath = dgNew;\n\tif (!oldPath) oldPath = dgOld;\n\tlet displayPath: string;\n\tif (renameDetected && oldPath && newPath && oldPath !== newPath) {\n\t\tdisplayPath = `${oldPath} => ${newPath}`;\n\t} else {\n\t\tdisplayPath = newPath ?? oldPath ?? \"(unknown)\";\n\t}\n\tif (!status) {\n\t\tif (binary) status = \"modified\";\n\t\telse if (oldPath && newPath) status = \"modified\";\n\t\telse if (newPath && !oldPath) status = \"added\";\n\t\telse if (oldPath && !newPath) status = \"deleted\";\n\t}\n\n\treturn {\n\t\tpath: displayPath,\n\t\t...(status ? { status } : {}),\n\t\t...(binary ? { binary: true } : {}),\n\t\tadditions,\n\t\tremovals,\n\t\tbody: bodyLines.join(\"\\n\"),\n\t};\n}\n\nfunction parseUnifiedDiff(text: string): GitDiffFile[] | null {\n\tif (text === \"\") return []; // empty diff (no changes)\n\tconst lines = text.split(\"\\n\");\n\t// Drop a single trailing empty line produced by the final newline.\n\tif (lines.length > 0 && lines[lines.length - 1] === \"\") lines.pop();\n\tconst chunks: string[][] = [];\n\tlet current: string[] | null = null;\n\tfor (const line of lines) {\n\t\tif (line.startsWith(\"diff --git \")) {\n\t\t\tif (current) chunks.push(current);\n\t\t\tcurrent = [line];\n\t\t} else if (current) {\n\t\t\tcurrent.push(line);\n\t\t} else {\n\t\t\treturn null; // content before the first `diff --git` (unrecognized prefix)\n\t\t}\n\t}\n\tif (current) chunks.push(current);\n\tif (chunks.length === 0) return null;\n\tconst files: GitDiffFile[] = [];\n\tfor (const chunk of chunks) {\n\t\tconst file = parseDiffChunk(chunk);\n\t\tif (!file) return null;\n\t\tfiles.push(file);\n\t}\n\treturn files;\n}\n\nconst SHOW_COMMIT_LINE = /^commit ([0-9a-f]{4,40})/;\nconst SHOW_SUBJECT_LINE = /^ {4}(.+)$/;\n\nfunction parseGitDiff(text: string, show: boolean): GitDiffParsed | null {\n\tconst raw = String(text ?? \"\").replace(/\\r/g, \"\");\n\tlet body = raw;\n\tlet hash: string | undefined;\n\tlet subject: string | undefined;\n\tif (show) {\n\t\tconst diffIndex = raw.indexOf(\"diff --git\");\n\t\tif (diffIndex < 0) return null; // commit with no patch / blob content → raw shell\n\t\tconst headerPart = raw.slice(0, diffIndex);\n\t\tbody = raw.slice(diffIndex);\n\t\tconst commitMatch = SHOW_COMMIT_LINE.exec(headerPart);\n\t\tif (commitMatch) hash = commitMatch[1];\n\t\tfor (const headerLine of headerPart.split(\"\\n\")) {\n\t\t\tconst subjectMatch = SHOW_SUBJECT_LINE.exec(headerLine);\n\t\t\tif (subjectMatch) {\n\t\t\t\tsubject = (subjectMatch[1] ?? \"\").trim();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tconst files = parseUnifiedDiff(body);\n\tif (!files) return null;\n\treturn {\n\t\tkind: \"diff\",\n\t\tshow,\n\t\tfiles,\n\t\t...(hash !== undefined ? { hash } : {}),\n\t\t...(subject !== undefined ? { subject } : {}),\n\t};\n}\n\n// ── git commit / push / pull / fetch parsers ─────────────────────────────────\n// State-change commands render a boxless summary card when their output parses\n// (ADR 0005). Every parser is fail-closed: a single unrecognized line returns\n// null and the boxed Bash shell renders raw. `git commit` with nothing staged\n// exits nonzero; those informational exit-1 shapes (clean tree, unstaged-only)\n// still parse to a `nothing to commit` card, while genuine errors (push\n// rejected, hook failure) hold an unrecognized line and fall back raw.\n\n/** `[<branch> <hash>] <subject>` — the first line of a successful commit. */\nconst COMMIT_SUCCESS = /^\\[(\\S+) ([0-9a-f]{7,40})\\] (.*)$/;\n\n/** Ref-update line with a status marker + bracketed/bare label, after leading\n * whitespace is trimmed: `* [new branch] src -> dst`, `* branch src -> dst`,\n * `= [up to date] src -> dst`. `!` (rejected) is excluded so rejected pushes\n * fall back to the raw shell instead of rendering a partial card. */\nconst REF_CHAR_LABEL = /^([*=.-]) (?:\\[([^\\]]*)\\]|(\\S+))\\s+(\\S+)\\s+->\\s+(\\S+)$/;\n/** Ref-update line carrying a hash range (update), after trimming:\n * `<a>..<b> src -> dst`. */\nconst REF_RANGE = /^([0-9a-f]{4,}\\.\\.[0-9a-f]{4,})\\s+(\\S+)\\s+->\\s+(\\S+)$/;\n\n/** Normalize a push/fetch ref-update line by collapsing alignment whitespace\n * to single spaces. Returns null when the line is neither a char-labeled nor a\n * range ref update (caller fails closed). */\nfunction normalizeRefLine(trimmed: string): string | null {\n\tconst labeled = REF_CHAR_LABEL.exec(trimmed);\n\tif (labeled) {\n\t\tconst marker = labeled[1] ?? \"\";\n\t\tconst label = labeled[2] !== undefined ? `[${labeled[2]}]` : (labeled[3] ?? \"\");\n\t\treturn `${marker} ${label} ${labeled[4]} -> ${labeled[5]}`;\n\t}\n\tconst range = REF_RANGE.exec(trimmed);\n\tif (range) return `${range[1]} ${range[2]} -> ${range[3]}`;\n\treturn null;\n}\n\n/** Push/fetch progress chatter lines (stderr mixed into the captured output)\n * that carry no ref information — skipped without failing the parse. */\nfunction isProgressNoise(line: string): boolean {\n\treturn (\n\t\t/^(?:Enumerating|Counting|Compressing|Writing|Deltaing|Resolving|Using) objects:/i.test(line) ||\n\t\t/^Total \\d+/i.test(line) ||\n\t\tline.startsWith(\"remote: \") ||\n\t\tline.startsWith(\"remote:\")\n\t);\n}\n\nfunction parseGitCommit(text: string): GitActionParsed | null {\n\tconst lines = String(text ?? \"\")\n\t\t.replace(/\\r/g, \"\")\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trimEnd());\n\tlet start = 0;\n\twhile (start < lines.length && (lines[start] ?? \"\") === \"\") start++;\n\tlet end = lines.length;\n\twhile (end > start && (lines[end - 1] ?? \"\") === \"\") end--;\n\tconst body = lines.slice(start, end);\n\tif (body.length === 0) return null;\n\n\tconst head = COMMIT_SUCCESS.exec(body[0] ?? \"\");\n\tif (head) {\n\t\tconst branch = head[1] ?? \"\";\n\t\tconst hash = head[2] ?? \"\";\n\t\tconst subject = (head[3] ?? \"\").trim();\n\t\tif (!branch || !hash) return null;\n\t\t// Without `-v` only an optional summary line follows; any other extra line\n\t\t// (a per-file row, editor output) fails closed.\n\t\tlet filesChanged: number | undefined;\n\t\tlet insertions: number | undefined;\n\t\tlet deletions: number | undefined;\n\t\tfor (const line of body.slice(1)) {\n\t\t\tconst summary = DIFF_STAT_SUMMARY.exec(line);\n\t\t\tif (!summary) return null;\n\t\t\tfilesChanged = Number(summary[1]);\n\t\t\tif (summary[2] !== undefined) insertions = Number(summary[2]);\n\t\t\tif (summary[3] !== undefined) deletions = Number(summary[3]);\n\t\t}\n\t\treturn {\n\t\t\tkind: \"action\",\n\t\t\tcommand: \"commit\",\n\t\t\tfiles: [],\n\t\t\tbranch,\n\t\t\thash,\n\t\t\t...(subject ? { subject } : {}),\n\t\t\t...(filesChanged !== undefined ? { filesChanged } : {}),\n\t\t\t...(insertions !== undefined ? { insertions } : {}),\n\t\t\t...(deletions !== undefined ? { deletions } : {}),\n\t\t};\n\t}\n\n\t// `git commit` with nothing to commit exits 1: either a clean tree or\n\t// unstaged/untracked-only changes. Both carry `On branch <name>` and a\n\t// terminator line; render a single `nothing to commit` row.\n\tconst first = body[0] ?? \"\";\n\tconst last = body[body.length - 1] ?? \"\";\n\tconst cleanNothing = body.some((line) => line === \"nothing to commit, working tree clean\");\n\tconst unstagedNothing = last.startsWith(\"no changes added to commit\");\n\tif (/^On branch .+/.test(first) && (cleanNothing || unstagedNothing)) {\n\t\treturn { kind: \"action\", command: \"commit\", files: [], status: \"nothing to commit\" };\n\t}\n\treturn null;\n}\n\nfunction parseGitPush(text: string): GitActionParsed | null {\n\tlet remote: string | undefined;\n\tlet status: string | undefined;\n\tconst refs: string[] = [];\n\tlet sawContent = false;\n\tfor (const rawLine of String(text ?? \"\")\n\t\t.replace(/\\r/g, \"\")\n\t\t.split(\"\\n\")) {\n\t\tconst line = rawLine.trimEnd();\n\t\tif (line === \"\") continue;\n\t\tif (isProgressNoise(line)) continue;\n\t\tif (/^branch '.*' set up to track '.*'\\.$/.test(line)) continue; // tracking info\n\t\tif (line.startsWith(\"Pushing to \")) continue; // verbose (rejected) preamble\n\t\tconst toLine = /^To (.+)$/.exec(line);\n\t\tif (toLine) {\n\t\t\tsawContent = true;\n\t\t\tremote = toLine[1] ?? \"\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (line === \"Everything up-to-date\") {\n\t\t\tsawContent = true;\n\t\t\tstatus = \"Everything up-to-date\";\n\t\t\tcontinue;\n\t\t}\n\t\tconst ref = normalizeRefLine(line.trim());\n\t\tif (ref) {\n\t\t\tsawContent = true;\n\t\t\trefs.push(ref);\n\t\t\tcontinue;\n\t\t}\n\t\treturn null; // rejected (`! [...]`), error:, or unknown line → fail closed\n\t}\n\tif (!sawContent) return null;\n\treturn {\n\t\tkind: \"action\",\n\t\tcommand: \"push\",\n\t\tfiles: [],\n\t\t...(remote !== undefined ? { remote } : {}),\n\t\t...(status !== undefined ? { status } : {}),\n\t\t...(refs.length > 0 ? { refs } : {}),\n\t};\n}\n\nfunction parseGitPull(text: string): GitActionParsed | null {\n\tconst lines = String(text ?? \"\")\n\t\t.replace(/\\r/g, \"\")\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trimEnd());\n\tconst nonEmpty = lines.filter((line) => line !== \"\");\n\tif (nonEmpty.length === 0) return null;\n\tif (nonEmpty.length === 1 && nonEmpty[0] === \"Already up to date.\") {\n\t\treturn { kind: \"action\", command: \"pull\", files: [], status: \"Already up to date.\" };\n\t}\n\n\t// Fast-forward: an optional `From <url>`/ref block, then `Updating a..b`,\n\t// `Fast-forward`, and the same per-file stat block `git diff --stat` reads.\n\tlet range: string | undefined;\n\tlet ffIndex = -1;\n\tfor (let idx = 0; idx < lines.length; idx++) {\n\t\tconst line = lines[idx] ?? \"\";\n\t\tif (line === \"\") continue;\n\t\tif (line.startsWith(\"From \")) continue;\n\t\tif (/^\\s+[0-9a-f]{4,}\\.\\.[0-9a-f]{4,}\\s+.+ -> .+$/.test(line)) continue; // fetch-style ref row\n\t\tconst updating = /^Updating ([0-9a-f]{4,}\\.\\.[0-9a-f]{4,})$/.exec(line);\n\t\tif (updating) {\n\t\t\trange = updating[1] ?? \"\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (line === \"Fast-forward\") {\n\t\t\tffIndex = idx;\n\t\t\tbreak;\n\t\t}\n\t\treturn null; // merge output, conflict markers, localized text → fail closed\n\t}\n\tif (!range || ffIndex < 0) return null;\n\tconst stat = parseGitDiffStat(lines.slice(ffIndex + 1).join(\"\\n\"));\n\tif (!stat) return null;\n\treturn {\n\t\tkind: \"action\",\n\t\tcommand: \"pull\",\n\t\tfiles: stat.files,\n\t\tstatus: \"Fast-forward\",\n\t\trange,\n\t\t...(stat.filesChanged !== undefined ? { filesChanged: stat.filesChanged } : {}),\n\t\t...(stat.insertions !== undefined ? { insertions: stat.insertions } : {}),\n\t\t...(stat.deletions !== undefined ? { deletions: stat.deletions } : {}),\n\t};\n}\n\nfunction parseGitFetch(text: string): GitActionParsed | null {\n\tlet remote: string | undefined;\n\tconst refs: string[] = [];\n\tlet sawContent = false;\n\tfor (const rawLine of String(text ?? \"\")\n\t\t.replace(/\\r/g, \"\")\n\t\t.split(\"\\n\")) {\n\t\tconst line = rawLine.trimEnd();\n\t\tif (line === \"\") continue;\n\t\tif (isProgressNoise(line)) continue;\n\t\tconst fromLine = /^From (.+)$/.exec(line);\n\t\tif (fromLine) {\n\t\t\tsawContent = true;\n\t\t\tremote = fromLine[1] ?? \"\";\n\t\t\tcontinue;\n\t\t}\n\t\tconst ref = normalizeRefLine(line.trim());\n\t\tif (ref) {\n\t\t\tsawContent = true;\n\t\t\trefs.push(ref);\n\t\t\tcontinue;\n\t\t}\n\t\treturn null; // unknown line → fail closed\n\t}\n\tif (!sawContent) return { kind: \"action\", command: \"fetch\", files: [], status: \"no new refs\" };\n\treturn {\n\t\tkind: \"action\",\n\t\tcommand: \"fetch\",\n\t\tfiles: [],\n\t\t...(remote !== undefined ? { remote } : {}),\n\t\t...(refs.length > 0 ? { refs } : {}),\n\t};\n}\n\n/** Lines appended to a merge/pull fast-forward stat block (after the summary)\n * that carry no per-file change count — file mode/creation/deletion/rename\n * notices. Filtered before the diff-stat line parser runs so merge stat\n * blocks parse; legit stat rows (`path | N`, `path | Bin`, the summary) never\n * match these shapes, so filtering is safe (ADR 0005). */\nconst DIFF_STAT_NOTICE_LINE =\n\t/^\\s+(?:create|delete) mode \\d+ |^\\s+(?:old|new) mode |^\\s+mode change |^\\s+(?:similarity|dissimilarity) index |^\\s+(?:rename|copy) (?:from|to) |^\\s+rewrite /;\n\n/** Parse a diff-stat block that may carry trailing file-mode/rename notices\n * (merge / pull fast-forward output). Shares `parseGitDiffStat` after the\n * notices are stripped; fails closed on any other hostile line. */\nfunction parseGitDiffStatTolerant(text: string): GitDiffStatParsed | null {\n\tconst filtered = String(text ?? \"\")\n\t\t.split(\"\\n\")\n\t\t.filter((line) => !DIFF_STAT_NOTICE_LINE.test(line))\n\t\t.join(\"\\n\");\n\treturn parseGitDiffStat(filtered);\n}\n\n/** `git switch`/`checkout`: `Switched to a new branch 'X'`, `Switched to branch\n * 'X'`, `Already on 'X'`, silent success (empty), or `Updated N paths from\n * the index` (checkout of paths). Advisory `Your branch …` lines are skipped\n * (the status line owns branch state). */\nconst SWITCH_NEW_BRANCH = /^Switched to a new branch '(.+)'$/;\nconst SWITCH_BRANCH = /^Switched to branch '(.+)'$/;\nconst SWITCH_ALREADY = /^Already on '(.+)'$/;\nconst CHECKOUT_PATHS = /^Updated (\\d+) paths? from the index$/;\n\nfunction parseGitSwitchCheckout(text: string, command: \"switch\" | \"checkout\"): GitActionParsed | null {\n\tconst significant: string[] = [];\n\tfor (const rawLine of String(text ?? \"\")\n\t\t.replace(/\\r/g, \"\")\n\t\t.split(\"\\n\")) {\n\t\tconst line = rawLine.trimEnd();\n\t\tif (line === \"\") continue;\n\t\t// Advisory branch-state lines and their hints — the status line owns `⎇ main`.\n\t\tif (line.startsWith(\"Your branch \")) continue;\n\t\tif (/^\\s+\\(/.test(line)) continue;\n\t\tsignificant.push(line);\n\t}\n\tif (significant.length === 0) {\n\t\treturn { kind: \"action\", command, files: [], status: \"completed, no output\" };\n\t}\n\tif (significant.length === 1) {\n\t\tconst line = significant[0] ?? \"\";\n\t\tconst created = SWITCH_NEW_BRANCH.exec(line);\n\t\tif (created && created[1] !== undefined)\n\t\t\treturn { kind: \"action\", command, files: [], branch: created[1], created: true };\n\t\tconst existing = SWITCH_BRANCH.exec(line);\n\t\tif (existing && existing[1] !== undefined) return { kind: \"action\", command, files: [], branch: existing[1] };\n\t\tconst already = SWITCH_ALREADY.exec(line);\n\t\tif (already && already[1] !== undefined) return { kind: \"action\", command, files: [], branch: already[1] };\n\t\tconst paths = CHECKOUT_PATHS.exec(line);\n\t\tif (paths) {\n\t\t\tconst count = Number(paths[1]);\n\t\t\treturn {\n\t\t\t\tkind: \"action\",\n\t\t\t\tcommand,\n\t\t\t\tfiles: [],\n\t\t\t\tstatus: `Updated ${count} ${pluralForm(\"file\", count)} from the index`,\n\t\t\t};\n\t\t}\n\t}\n\treturn null; // detached-HEAD note, `switch -m` merge rows, localized text → fail closed\n}\n\n/** `git add`/`restore`: success is silent (empty output). Any non-empty output\n * is an error/`-v` listing/localized text → fail closed. */\nfunction parseGitAddRestore(text: string, command: \"add\" | \"restore\"): GitActionParsed | null {\n\tconst body = String(text ?? \"\").replace(/\\r/g, \"\");\n\tif (body.trim() === \"\") {\n\t\treturn { kind: \"action\", command, files: [], status: \"completed, no output\" };\n\t}\n\treturn null;\n}\n\n/** `git reset`: `HEAD is now at <hash> <subject>` (`--hard`/`--keep`), the\n * `Unstaged changes after reset:` block with `<marker>\\t<path>` rows\n * (`--mixed`), or silent success (`--soft`, or a clean mixed reset). */\nconst RESET_HEAD_NOW = /^HEAD is now at ([0-9a-f]{4,40}) (.*)$/;\nconst RESET_UNSTAGED_HEADER = \"Unstaged changes after reset:\";\nconst RESET_UNSTAGED_ROW = /^([MADRC?!]{1,2})\\t(.+)$/;\n\nfunction parseGitReset(text: string): GitActionParsed | null {\n\tconst lines = String(text ?? \"\")\n\t\t.replace(/\\r/g, \"\")\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trimEnd());\n\tconst nonEmpty = lines.filter((line) => line !== \"\");\n\tif (nonEmpty.length === 0) {\n\t\treturn { kind: \"action\", command: \"reset\", files: [], status: \"completed, no output\" };\n\t}\n\tif (nonEmpty.length === 1) {\n\t\tconst head = RESET_HEAD_NOW.exec(nonEmpty[0] ?? \"\");\n\t\tif (head && head[1] !== undefined) {\n\t\t\tconst subject = (head[2] ?? \"\").trim();\n\t\t\treturn {\n\t\t\t\tkind: \"action\",\n\t\t\t\tcommand: \"reset\",\n\t\t\t\tfiles: [],\n\t\t\t\thash: head[1],\n\t\t\t\t...(subject ? { subject } : {}),\n\t\t\t};\n\t\t}\n\t\treturn null;\n\t}\n\tif ((nonEmpty[0] ?? \"\") === RESET_UNSTAGED_HEADER) {\n\t\tconst resetFiles: GitStatusFile[] = [];\n\t\tfor (const row of nonEmpty.slice(1)) {\n\t\t\tconst match = RESET_UNSTAGED_ROW.exec(row ?? \"\");\n\t\t\tif (!match) return null;\n\t\t\tconst marker = match[1] ?? \"\";\n\t\t\tresetFiles.push({ x: marker[0] ?? \" \", y: marker[1] ?? \" \", path: match[2] ?? \"\" });\n\t\t}\n\t\tif (resetFiles.length === 0) return null;\n\t\treturn { kind: \"action\", command: \"reset\", files: [], resetFiles };\n\t}\n\treturn null; // unrecognized multi-line shape → fail closed\n}\n\n/** `git merge`: `Already up to date.`, a fast-forward (`Updating a..b` +\n * `Fast-forward` + stat block), or `Merge made by the '…' strategy.` + stat\n * block. Conflicts exit nonzero and hold unrecognized lines → fail closed. */\nconst MERGE_UPDATING = /^Updating ([0-9a-f]{4,}\\.\\.[0-9a-f]{4,})$/;\nconst MERGE_MADE = /^Merge made by the '.*' strategy\\.$/;\n\nfunction parseGitMerge(text: string): GitActionParsed | null {\n\tconst lines = String(text ?? \"\")\n\t\t.replace(/\\r/g, \"\")\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trimEnd());\n\tlet start = 0;\n\twhile (start < lines.length && (lines[start] ?? \"\") === \"\") start++;\n\tlet end = lines.length;\n\twhile (end > start && (lines[end - 1] ?? \"\") === \"\") end--;\n\tconst body = lines.slice(start, end);\n\tif (body.length === 0) return null; // merge always reports; empty → hostile\n\n\tif (body.length === 1 && (body[0] ?? \"\") === \"Already up to date.\") {\n\t\treturn { kind: \"action\", command: \"merge\", files: [], status: \"Already up to date.\" };\n\t}\n\n\tlet idx = 0;\n\tlet range: string | undefined;\n\tconst updating = MERGE_UPDATING.exec(body[0] ?? \"\");\n\tif (updating) {\n\t\trange = updating[1];\n\t\tidx = 1;\n\t}\n\tconst marker = body[idx] ?? \"\";\n\tif (range && marker === \"Fast-forward\") {\n\t\tconst stat = parseGitDiffStatTolerant(body.slice(idx + 1).join(\"\\n\"));\n\t\tif (!stat) return null;\n\t\treturn {\n\t\t\tkind: \"action\",\n\t\t\tcommand: \"merge\",\n\t\t\tfiles: stat.files,\n\t\t\tstatus: \"Fast-forward\",\n\t\t\trange,\n\t\t\t...(stat.filesChanged !== undefined ? { filesChanged: stat.filesChanged } : {}),\n\t\t\t...(stat.insertions !== undefined ? { insertions: stat.insertions } : {}),\n\t\t\t...(stat.deletions !== undefined ? { deletions: stat.deletions } : {}),\n\t\t};\n\t}\n\tif (MERGE_MADE.exec(marker)) {\n\t\tconst stat = parseGitDiffStatTolerant(body.slice(idx + 1).join(\"\\n\"));\n\t\tif (!stat) return null;\n\t\treturn {\n\t\t\tkind: \"action\",\n\t\t\tcommand: \"merge\",\n\t\t\tfiles: stat.files,\n\t\t\tstatus: marker,\n\t\t\t...(stat.filesChanged !== undefined ? { filesChanged: stat.filesChanged } : {}),\n\t\t\t...(stat.insertions !== undefined ? { insertions: stat.insertions } : {}),\n\t\t\t...(stat.deletions !== undefined ? { deletions: stat.deletions } : {}),\n\t\t};\n\t}\n\treturn null; // conflict markers, `--squash`/`--abort` output → fail closed\n}\n\n/** `git rebase`: `Successfully rebased and updated refs/heads/<branch>.` or\n * `Current branch <branch> is up to date.`. The `Rebasing (N/M)` progress is\n * carriage-return-separated; `\\r` is split into its own line and dropped.\n * Conflicts/`--abort`/`--continue` exit nonzero and fail closed. */\nconst REBASE_SUCCESS = /^Successfully rebased and updated refs\\/heads\\/(.+)$/;\nconst REBASE_UPTODATE = /^Current branch (.+) is up to date\\.$/;\n\nfunction parseGitRebase(text: string): GitActionParsed | null {\n\tconst significant: string[] = [];\n\tfor (const rawLine of String(text ?? \"\")\n\t\t.replace(/\\r/g, \"\\n\")\n\t\t.split(\"\\n\")) {\n\t\tconst line = rawLine.trimEnd();\n\t\tif (line === \"\") continue;\n\t\t// Progress chatter written with a carriage return, then overwritten.\n\t\tif (/^Rebasing \\(\\d+\\/\\d+\\)/.test(line)) continue;\n\t\tif (/^Rewriting commits \\(\\d+\\/\\d+\\)/.test(line)) continue;\n\t\tsignificant.push(line);\n\t}\n\tif (significant.length === 1) {\n\t\tconst line = significant[0] ?? \"\";\n\t\tconst success = REBASE_SUCCESS.exec(line);\n\t\tif (success && success[1] !== undefined)\n\t\t\treturn {\n\t\t\t\tkind: \"action\",\n\t\t\t\tcommand: \"rebase\",\n\t\t\t\tfiles: [],\n\t\t\t\tbranch: success[1].replace(/\\.$/, \"\"),\n\t\t\t\tstatus: \"Rebased\",\n\t\t\t};\n\t\tconst upToDate = REBASE_UPTODATE.exec(line);\n\t\tif (upToDate && upToDate[1] !== undefined)\n\t\t\treturn { kind: \"action\", command: \"rebase\", files: [], branch: upToDate[1], status: \"Up to date.\" };\n\t}\n\treturn null; // conflict, `--abort`/`--continue`, interactive editor → fail closed\n}\n\nfunction parseGitAction(command: GitActionParsed[\"command\"], text: string): GitActionParsed | null {\n\tif (command === \"commit\") return parseGitCommit(text);\n\tif (command === \"push\") return parseGitPush(text);\n\tif (command === \"pull\") return parseGitPull(text);\n\tif (command === \"fetch\") return parseGitFetch(text);\n\tif (command === \"switch\" || command === \"checkout\") return parseGitSwitchCheckout(text, command);\n\tif (command === \"add\" || command === \"restore\") return parseGitAddRestore(text, command);\n\tif (command === \"reset\") return parseGitReset(text);\n\tif (command === \"merge\") return parseGitMerge(text);\n\treturn parseGitRebase(text);\n}\n\n// ── Rendering ───────────────────────────────────────────────────────────────\n\n/** Nerd Font git-branch glyph used on git card headers in Nerd Font mode. */\nexport const GIT_ICON = \"\\u{E725}\";\n\nconst GIT_CARD_HEAD_LIMIT = 6;\nconst GIT_CONFLICT_PAIRS = new Set([\"UU\", \"AA\", \"DD\", \"AU\", \"UA\", \"DU\", \"UD\"]);\n\nfunction gitCardHeader(theme: BoxTheme, cls: GitSemanticClass, parsed?: GitParsedSemantic): string {\n\tconst icon = getToolsRenderConfig().nerdFonts ? `${GIT_ICON} ` : \"\";\n\tlet prefix: string;\n\tif (cls.kind === \"diff\") {\n\t\tconst label = cls.show ? \"Git show\" : \"Git diff\";\n\t\tprefix = `${icon}${label}`;\n\t\tif (cls.show && parsed?.kind === \"diff\" && parsed.hash) {\n\t\t\tconst shortHash = parsed.hash.slice(0, 7);\n\t\t\tprefix += ` · ${shortHash}`;\n\t\t\tif (parsed.subject) prefix += ` · ${parsed.subject}`;\n\t\t}\n\t} else if (cls.kind === \"show-stat\") {\n\t\tprefix = `${icon}Git show`;\n\t\tif (parsed?.kind === \"show-stat\") {\n\t\t\tprefix += ` · ${parsed.hash.slice(0, 7)}`;\n\t\t\tif (parsed.subject) prefix += ` · ${parsed.subject}`;\n\t\t}\n\t} else if (cls.kind === \"action\") {\n\t\tconst label =\n\t\t\tcls.command === \"commit\"\n\t\t\t\t? \"Git commit\"\n\t\t\t\t: cls.command === \"push\"\n\t\t\t\t\t? \"Git push\"\n\t\t\t\t\t: cls.command === \"pull\"\n\t\t\t\t\t\t? \"Git pull\"\n\t\t\t\t\t\t: cls.command === \"fetch\"\n\t\t\t\t\t\t\t? \"Git fetch\"\n\t\t\t\t\t\t\t: cls.command === \"switch\"\n\t\t\t\t\t\t\t\t? \"Git switch\"\n\t\t\t\t\t\t\t\t: cls.command === \"checkout\"\n\t\t\t\t\t\t\t\t\t? \"Git checkout\"\n\t\t\t\t\t\t\t\t\t: cls.command === \"add\"\n\t\t\t\t\t\t\t\t\t\t? \"Git add\"\n\t\t\t\t\t\t\t\t\t\t: cls.command === \"restore\"\n\t\t\t\t\t\t\t\t\t\t\t? \"Git restore\"\n\t\t\t\t\t\t\t\t\t\t\t: cls.command === \"reset\"\n\t\t\t\t\t\t\t\t\t\t\t\t? \"Git reset\"\n\t\t\t\t\t\t\t\t\t\t\t\t: cls.command === \"merge\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t? \"Git merge\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t: \"Git rebase\";\n\t\tprefix = `${icon}${label}`;\n\t\t// Header detail carries the parsed identity, matching `Git show · hash ·\n\t\t// subject`: a commit's `[<branch> <hash>] <subject>`, a switch/checkout\n\t\t// target branch, a reset --hard `HEAD is now at <hash> <subject>`, or a\n\t\t// rebase `<branch>`. add/restore/merge stay label-only.\n\t\tif (parsed?.kind === \"action\") {\n\t\t\tif ((parsed.command === \"commit\" || parsed.command === \"reset\") && parsed.hash) {\n\t\t\t\tprefix += ` · ${parsed.hash.slice(0, 7)}`;\n\t\t\t\tif (parsed.subject) prefix += ` · ${parsed.subject}`;\n\t\t\t} else if (\n\t\t\t\t(parsed.command === \"switch\" || parsed.command === \"checkout\" || parsed.command === \"rebase\") &&\n\t\t\t\tparsed.branch\n\t\t\t) {\n\t\t\t\tprefix += ` · ${parsed.branch}`;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tconst label = cls.kind === \"status\" ? \"Git status\" : cls.kind === \"diff-stat\" ? \"Git diff --stat\" : \"Git log\";\n\t\tprefix = `${icon}${label}`;\n\t}\n\treturn typeof theme?.bold === \"function\" ? theme.bold(prefix) : prefix;\n}\n\nfunction statusMarker(file: GitStatusFile): string {\n\tconst xy = `${file.x}${file.y}`;\n\tif (GIT_CONFLICT_PAIRS.has(xy)) return \"U\";\n\tif (file.x === \"?\" || file.x === \"!\") return file.x;\n\tconst staged = file.x !== \" \" ? file.x : \"\";\n\tconst worktree = file.y !== \" \" && file.y !== \"?\" && file.y !== \"!\" ? file.y : \"\";\n\treturn `${staged}${worktree}` || \" \";\n}\n\nfunction statusMarkColor(file: GitStatusFile): string {\n\tconst xy = `${file.x}${file.y}`;\n\tif (GIT_CONFLICT_PAIRS.has(xy)) return \"error\";\n\tif (file.x === \"?\") return \"warning\";\n\tif (file.x === \"!\") return \"dim\";\n\tif (file.x !== \" \") return \"accent\";\n\treturn \"toolOutput\";\n}\n\nfunction statusCounts(theme: BoxTheme, parsed: GitStatusParsed): string[] {\n\tlet staged = 0;\n\tlet modified = 0;\n\tlet untracked = 0;\n\tlet ignored = 0;\n\tlet conflicted = 0;\n\tfor (const file of parsed.files) {\n\t\tconst xy = `${file.x}${file.y}`;\n\t\tif (GIT_CONFLICT_PAIRS.has(xy)) conflicted++;\n\t\telse if (file.x === \"?\" || file.x === \"!\") {\n\t\t\tif (file.x === \"!\") ignored++;\n\t\t\telse untracked++;\n\t\t} else if (file.x !== \" \") staged++;\n\t\telse if (file.y !== \" \") modified++;\n\t}\n\n\tconst parts: string[] = [];\n\tif (conflicted > 0) parts.push(theme.fg(\"error\", `${conflicted} conflicted`));\n\tif (staged > 0) parts.push(theme.fg(\"accent\", `${staged} staged`));\n\tif (modified > 0) parts.push(theme.fg(\"accent\", `${modified} modified`));\n\tif (untracked > 0) parts.push(theme.fg(\"warning\", `${untracked} untracked`));\n\tif (ignored > 0) parts.push(theme.fg(\"dim\", `${ignored} ignored`));\n\treturn parts;\n}\n\nfunction renderStatusCard(theme: BoxTheme, parsed: GitStatusParsed, out: string[], width: number): string[] {\n\tconst counts = statusCounts(theme, parsed);\n\tif (counts.length > 0) out.push(` ${counts.join(theme.fg(\"dim\", \" · \"))}`);\n\telse out.push(theme.fg(\"muted\", \" nothing to commit, working tree clean\"));\n\n\t// Branch is only shown when it affects the result (push/merge/ahead-behind);\n\t// the status line owns `⎇ main` (ADR 0005).\n\tif (parsed.branch && (parsed.ahead !== undefined || parsed.behind !== undefined)) {\n\t\tconst parts = [theme.fg(\"text\", parsed.branch)];\n\t\tif (parsed.ahead !== undefined) parts.push(theme.fg(\"accent\", `ahead ${parsed.ahead}`));\n\t\tif (parsed.behind !== undefined) parts.push(theme.fg(\"warning\", `behind ${parsed.behind}`));\n\t\tout.push(` ${parts.join(theme.fg(\"dim\", \" · \"))}`);\n\t}\n\n\tconst files = parsed.files;\n\treturn renderStatusFileRows(theme, files, out, width);\n}\n\n/** Shared `├─ M path` rows for status-style file lists (status card + reset). */\nfunction renderStatusFileRows(\n\ttheme: BoxTheme,\n\tfiles: readonly GitStatusFile[],\n\tout: string[],\n\twidth: number,\n): string[] {\n\tconst visible = files.slice(0, GIT_CARD_HEAD_LIMIT);\n\tconst more = files.length - visible.length;\n\tconst lastIndex = visible.length - 1;\n\tfor (let i = 0; i < visible.length; i++) {\n\t\tconst file = visible[i];\n\t\tif (!file) continue;\n\t\tconst branch = i < lastIndex || more > 0 ? \"├─\" : \"└─\";\n\t\tconst mark = statusMarker(file);\n\t\tconst line = `${TREE_INDENT}${dimLine(branch)} ${theme.fg(statusMarkColor(file), mark)} ${theme.fg(\"toolOutput\", file.path)}`;\n\t\tout.push(safeTruncateToWidth(line, width, \"…\"));\n\t}\n\tif (more > 0) {\n\t\tout.push(\n\t\t\tsafeTruncateToWidth(\n\t\t\t\t`${TREE_INDENT}${dimLine(\"└─\")} ${theme.fg(\"dim\", `… ${more} more ${pluralForm(\"file\", more)}`)}`,\n\t\t\t\twidth,\n\t\t\t\t\"…\",\n\t\t\t),\n\t\t);\n\t}\n\treturn out;\n}\n\nfunction renderDiffStatCard(theme: BoxTheme, parsed: DiffStatSummary, out: string[], width: number): string[] {\n\tconst summaryParts: string[] = [];\n\tif (parsed.filesChanged !== undefined) {\n\t\tsummaryParts.push(theme.fg(\"accent\", `${parsed.filesChanged} ${pluralForm(\"file\", parsed.filesChanged)} changed`));\n\t}\n\t// +/− totals sit adjacent (no separator between them), unlike the `·`-joined parts.\n\tconst diffParts: string[] = [];\n\tif (parsed.insertions !== undefined && parsed.insertions > 0) {\n\t\tdiffParts.push(theme.fg(\"toolDiffAdded\", `+${parsed.insertions}`));\n\t}\n\tif (parsed.deletions !== undefined && parsed.deletions > 0) {\n\t\tdiffParts.push(theme.fg(\"toolDiffRemoved\", `-${parsed.deletions}`));\n\t}\n\tif (diffParts.length > 0) summaryParts.push(diffParts.join(\" \"));\n\tif (summaryParts.length > 0) out.push(` ${summaryParts.join(theme.fg(\"dim\", \" · \"))}`);\n\telse out.push(theme.fg(\"muted\", \" no changes\"));\n\n\tconst files = parsed.files;\n\tconst visible = files.slice(0, GIT_CARD_HEAD_LIMIT);\n\tconst more = files.length - visible.length;\n\tconst lastIndex = visible.length - 1;\n\tfor (let i = 0; i < visible.length; i++) {\n\t\tconst file = visible[i];\n\t\tif (!file) continue;\n\t\tconst branch = i < lastIndex || more > 0 ? \"├─\" : \"└─\";\n\t\tconst changes = file.changes ?? 0;\n\t\tconst detail = theme.fg(\"dim\", file.binary ? \"· binary\" : `· ${changes} ${pluralForm(\"change\", changes)}`);\n\t\tconst line = `${TREE_INDENT}${dimLine(branch)} ${theme.fg(\"toolOutput\", file.path)} ${detail}`;\n\t\tout.push(safeTruncateToWidth(line, width, \"…\"));\n\t}\n\tif (more > 0) {\n\t\tout.push(\n\t\t\tsafeTruncateToWidth(\n\t\t\t\t`${TREE_INDENT}${dimLine(\"└─\")} ${theme.fg(\"dim\", `… ${more} more ${pluralForm(\"file\", more)}`)}`,\n\t\t\t\twidth,\n\t\t\t\t\"…\",\n\t\t\t),\n\t\t);\n\t}\n\treturn out;\n}\n\nfunction renderLogCard(theme: BoxTheme, parsed: GitLogParsed, out: string[], width: number): string[] {\n\tconst commits = parsed.commits;\n\tif (commits.length === 0) {\n\t\tout.push(theme.fg(\"muted\", \" no commits\"));\n\t\treturn out;\n\t}\n\n\tconst visible = commits.slice(0, GIT_CARD_HEAD_LIMIT);\n\tconst more = commits.length - visible.length;\n\tconst lastIndex = visible.length - 1;\n\tfor (let i = 0; i < visible.length; i++) {\n\t\tconst commit = visible[i];\n\t\tif (!commit) continue;\n\t\tconst branch = i < lastIndex || more > 0 ? \"├─\" : \"└─\";\n\t\tconst refs = commit.refs ? ` (${commit.refs})` : \"\";\n\t\tconst subject = commit.subject ? ` ${commit.subject}` : \"\";\n\t\tconst line = `${TREE_INDENT}${dimLine(branch)} ${theme.fg(\"accent\", commit.hash)}${theme.fg(\"dim\", refs)}${theme.fg(\"toolOutput\", subject)}`;\n\t\tout.push(line);\n\t}\n\tif (more > 0) {\n\t\tout.push(\n\t\t\tsafeTruncateToWidth(\n\t\t\t\t`${TREE_INDENT}${dimLine(\"└─\")} ${theme.fg(\"dim\", `… ${more} more ${pluralForm(\"commit\", more)}`)}`,\n\t\t\t\twidth,\n\t\t\t\t\"…\",\n\t\t\t),\n\t\t);\n\t}\n\treturn out;\n}\n\nfunction renderDiffCard(theme: BoxTheme, parsed: GitDiffParsed, out: string[], width: number): string[] {\n\tconst files = parsed.files;\n\tif (files.length === 0) {\n\t\tout.push(theme.fg(\"muted\", \" no changes\"));\n\t\treturn out;\n\t}\n\tlet additions = 0;\n\tlet removals = 0;\n\tfor (const file of files) {\n\t\tadditions += file.additions;\n\t\tremovals += file.removals;\n\t}\n\tconst parts: string[] = [theme.fg(\"accent\", `${files.length} ${pluralForm(\"file\", files.length)}`)];\n\tif (additions > 0) parts.push(theme.fg(\"toolDiffAdded\", `+${additions}`));\n\tif (removals > 0) parts.push(theme.fg(\"toolDiffRemoved\", `-${removals}`));\n\tout.push(safeTruncateToWidth(` ${parts.join(\" \")}`, width, \"…\"));\n\treturn out;\n}\n\n/** Render a state-change card. `commit`/`pull` reuse the diff-stat summary +\n * `├─/└─` rows; `push`/`fetch` show the remote (dim) and normalized ref rows.\n * Every line is width-safe (the caller truncates again). */\nfunction renderActionCard(theme: BoxTheme, parsed: GitActionParsed, out: string[], width: number): string[] {\n\tif (parsed.command === \"commit\") {\n\t\tif (parsed.status) {\n\t\t\tout.push(theme.fg(\"muted\", ` ${parsed.status}`)); // nothing to commit\n\t\t\treturn out;\n\t\t}\n\t\trenderDiffStatCard(theme, parsed, out, width); // success: summary line only (no -v rows)\n\t\treturn out;\n\t}\n\tif (parsed.command === \"pull\") {\n\t\tif (parsed.status === \"Already up to date.\") {\n\t\t\tout.push(theme.fg(\"muted\", \" Already up to date.\"));\n\t\t\treturn out;\n\t\t}\n\t\t// Fast-forward: range + Fast-forward + diff-stat summary/rows.\n\t\tif (parsed.range) out.push(` ${theme.fg(\"text\", parsed.range)}`);\n\t\tout.push(` ${theme.fg(\"accent\", \"Fast-forward\")}`);\n\t\trenderDiffStatCard(theme, parsed, out, width);\n\t\treturn out;\n\t}\n\tif (parsed.command === \"push\") {\n\t\tif (parsed.remote) out.push(theme.fg(\"dim\", ` To ${parsed.remote}`));\n\t\tfor (const ref of parsed.refs ?? []) out.push(safeTruncateToWidth(` ${theme.fg(\"toolOutput\", ref)}`, width, \"…\"));\n\t\tif (parsed.status) out.push(theme.fg(\"muted\", ` ${parsed.status}`)); // Everything up-to-date\n\t\treturn out;\n\t}\n\tif (parsed.command === \"fetch\") {\n\t\tif (parsed.status) {\n\t\t\tout.push(theme.fg(\"muted\", ` ${parsed.status}`)); // no new refs (empty fetch)\n\t\t\treturn out;\n\t\t}\n\t\tif (parsed.remote) out.push(theme.fg(\"dim\", ` From ${parsed.remote}`));\n\t\tfor (const ref of parsed.refs ?? []) out.push(safeTruncateToWidth(` ${theme.fg(\"toolOutput\", ref)}`, width, \"…\"));\n\t\treturn out;\n\t}\n\tif (parsed.command === \"merge\") {\n\t\tif (parsed.status === \"Already up to date.\") {\n\t\t\tout.push(theme.fg(\"muted\", \" Already up to date.\"));\n\t\t\treturn out;\n\t\t}\n\t\t// Fast-forward / `Merge made by the '…' strategy.` + stat summary/rows.\n\t\tif (parsed.range) out.push(` ${theme.fg(\"text\", parsed.range)}`);\n\t\tif (parsed.status) out.push(` ${theme.fg(\"accent\", parsed.status)}`);\n\t\trenderDiffStatCard(theme, parsed, out, width);\n\t\treturn out;\n\t}\n\tif (parsed.command === \"reset\") {\n\t\t// Mixed reset with unstaged changes: `M path` rows (hash/subject live in\n\t\t// the header for --hard/--soft via `HEAD is now at`).\n\t\tif (parsed.resetFiles && parsed.resetFiles.length > 0) {\n\t\t\treturn renderStatusFileRows(theme, parsed.resetFiles, out, width);\n\t\t}\n\t\tif (parsed.status) out.push(theme.fg(\"muted\", ` ${parsed.status}`)); // completed, no output\n\t\treturn out;\n\t}\n\t// switch/checkout (branch in the header), add/restore/rebase (status line).\n\tif (parsed.status) out.push(theme.fg(\"muted\", ` ${parsed.status}`));\n\treturn out;\n}\n\n// ── Dispatch helpers (used by bash.ts) ──────────────────────────────────────\n\nexport function parseGitOutput(cls: GitSemanticClass, output: string): GitParsedSemantic | null {\n\tconst text = String(output ?? \"\");\n\tif (cls.kind === \"status\") return parseGitStatus(cls, text);\n\tif (cls.kind === \"diff-stat\") return parseGitDiffStat(text);\n\tif (cls.kind === \"show-stat\") return parseGitShowStat(text);\n\tif (cls.kind === \"diff\") return parseGitDiff(text, cls.show);\n\tif (cls.kind === \"action\") return parseGitAction(cls.command, text);\n\treturn parseGitLog(text);\n}\n\n/**\n * Render the git semantic card for one call: the header always renders (so a\n * pending call shows a single summary line); once the result parses, counts,\n * file/commit rows, and the `… N more` collapse follow. Every line is\n * width-safe.\n */\nexport function renderGitCardLines(\n\ttheme: BoxTheme,\n\tstate: { readonly cls: GitSemanticClass; readonly parsed?: GitParsedSemantic },\n\twidth: number,\n): string[] {\n\tconst safeWidth = Math.max(1, width);\n\tconst out: string[] = [safeTruncateToWidth(gitCardHeader(theme, state.cls, state.parsed), safeWidth, \"…\")];\n\tconst parsed = state.parsed;\n\tif (!parsed) return out;\n\tif (parsed.kind === \"status\") renderStatusCard(theme, parsed, out, safeWidth);\n\telse if (parsed.kind === \"diff-stat\") renderDiffStatCard(theme, parsed, out, safeWidth);\n\telse if (parsed.kind === \"show-stat\") renderDiffStatCard(theme, parsed, out, safeWidth);\n\telse if (parsed.kind === \"diff\") renderDiffCard(theme, parsed, out, safeWidth);\n\telse if (parsed.kind === \"action\") renderActionCard(theme, parsed, out, safeWidth);\n\telse renderLogCard(theme, parsed, out, safeWidth);\n\treturn out.map((line) => safeTruncateToWidth(line, safeWidth, \"…\"));\n}\n\n// ── Boxed diff result (Phase 8B) ──────────────────────────────────────────\n// `git diff` / `git show` results render one frame per file via\n// `renderBoxedToolResult` + the same `AdaptiveDiffComponent` `Edit` uses — no\n// second diff visual language (ADR 0005 / GIT-002). The Git header lives\n// outside the box (the call panel card); each file gets its own `╭…╰` frame\n// with a `Diff · +N -M` divider and a `Ctrl+O more` expand hint when collapsed.\n\nconst GIT_DIFF_MAX_HIGHLIGHT_CHARS = 12000;\nconst GIT_DIFF_MAX_HIGHLIGHT_ROWS = 120;\nconst GIT_DIFF_MAX_ROWS_COLLAPSED = 36;\nconst GIT_DIFF_MAX_ROWS_EXPANDED = 160;\n\nfunction diffDividerLabel(theme: BoxTheme, stats: { additions: number; removals: number }): string {\n\tconst plus = stats.additions > 0 ? theme.fg(\"toolDiffAdded\", `+${stats.additions}`) : theme.fg(\"dim\", \"+0\");\n\tconst minus = stats.removals > 0 ? theme.fg(\"toolDiffRemoved\", `-${stats.removals}`) : theme.fg(\"dim\", \"-0\");\n\treturn `Diff · ${plus} ${minus}`;\n}\n\nfunction fileBoxTopLabel(theme: BoxTheme, path: string): string {\n\tconst body = theme.fg(\"text\", path);\n\treturn typeof theme?.bold === \"function\" ? theme.bold(body) : body;\n}\n\nfunction binaryBodyLine(theme: BoxTheme, status: GitDiffFile[\"status\"]): string {\n\tconst verb =\n\t\tstatus === \"added\" ? \"added\" : status === \"deleted\" ? \"removed\" : status === \"renamed\" ? \"renamed\" : \"changed\";\n\treturn theme.fg(\"muted\", `Binary file ${verb} (content not shown)`);\n}\n\ninterface DiffFileBox {\n\treadonly topLabel: string;\n\treadonly resultComponent: Component;\n}\n\n/** Build a complete boxed-diff result component for a parsed `git diff`/`show`.\n * The call panel renders the boxless Git header; this component renders one\n * `╭…╰` frame per file (or a single `No changes` frame for an empty diff). */\nexport function renderGitDiffResult(\n\ttheme: BoxTheme,\n\tparsed: GitDiffParsed,\n\toptions: { expanded: boolean },\n\tcontext: BoxedToolContext,\n): Component {\n\tconst expanded = Boolean(options.expanded);\n\tconst elapsedMs = getStateElapsedMs(context.state);\n\tconst fileCount = parsed.files.length;\n\n\tconst footerParts: string[] = [];\n\tif (elapsedMs !== undefined) footerParts.push(theme.fg(\"text\", formatElapsedMs(elapsedMs)));\n\tfooterParts.push(theme.fg(\"dim\", `${fileCount} ${pluralForm(\"file\", fileCount)}`));\n\tconst footer = footerParts.join(theme.fg(\"dim\", \" · \"));\n\n\tconst fileBoxes: DiffFileBox[] = [];\n\tif (parsed.files.length === 0) {\n\t\t// Empty diff (`git diff` with no changes): a single `No changes` frame so\n\t\t// the result is not a blank panel.\n\t\tconst emptyFooterParts: string[] = [];\n\t\tif (elapsedMs !== undefined) emptyFooterParts.push(theme.fg(\"text\", formatElapsedMs(elapsedMs)));\n\t\tconst emptyFooter = emptyFooterParts.join(theme.fg(\"dim\", \" · \"));\n\t\tfileBoxes.push({\n\t\t\ttopLabel: fileBoxTopLabel(theme, parsed.show ? \"Git show\" : \"Git diff\"),\n\t\t\tresultComponent: renderBoxedToolResult(theme, () => [theme.fg(\"muted\", \"No changes\")], {\n\t\t\t\tshowDivider: false,\n\t\t\t\tfooterLines: emptyFooter ? [emptyFooter] : [],\n\t\t\t}),\n\t\t});\n\t} else {\n\t\tfor (const file of parsed.files) {\n\t\t\tconst topLabel = fileBoxTopLabel(theme, file.path);\n\t\t\tif (file.binary) {\n\t\t\t\tfileBoxes.push({\n\t\t\t\t\ttopLabel,\n\t\t\t\t\tresultComponent: renderBoxedToolResult(theme, () => [binaryBodyLine(theme, file.status)], {\n\t\t\t\t\t\tdividerLabel: \"Binary\",\n\t\t\t\t\t\tfooterLines: [footer],\n\t\t\t\t\t}),\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst rows = buildSplitRows(file.body);\n\t\t\tconst language = getLanguageFromPath(file.path);\n\t\t\tconst shouldHighlight =\n\t\t\t\tBoolean(language) &&\n\t\t\t\tfile.body.length <= GIT_DIFF_MAX_HIGHLIGHT_CHARS &&\n\t\t\t\trows.length <= GIT_DIFF_MAX_HIGHLIGHT_ROWS;\n\t\t\tconst maxRows = expanded ? GIT_DIFF_MAX_ROWS_EXPANDED : GIT_DIFF_MAX_ROWS_COLLAPSED;\n\t\t\tconst view = new AdaptiveDiffComponent(theme, rows, maxRows, shouldHighlight ? language : undefined);\n\t\t\tconst expandHint = !expanded && view.hasCollapsed() ? \"Ctrl+O more\" : undefined;\n\t\t\tfileBoxes.push({\n\t\t\t\ttopLabel,\n\t\t\t\tresultComponent: renderBoxedToolResult(theme, view, {\n\t\t\t\t\tdividerLabel: diffDividerLabel(theme, countDiffStats(file.body)),\n\t\t\t\t\tfooterLines: [footer],\n\t\t\t\t\t...(expandHint ? { expandHint } : {}),\n\t\t\t\t}),\n\t\t\t});\n\t\t}\n\t}\n\n\tlet cacheWidth: number | undefined;\n\tlet cacheLines: string[] | undefined;\n\n\treturn {\n\t\tinvalidate() {\n\t\t\tcacheWidth = undefined;\n\t\t\tcacheLines = undefined;\n\t\t\tfor (const box of fileBoxes) box.resultComponent.invalidate();\n\t\t},\n\t\trender(width: number): string[] {\n\t\t\tif (cacheWidth === width && cacheLines) return cacheLines;\n\t\t\tconst renderedWidth = boxWidth(width);\n\t\t\tconst lines: string[] = [];\n\t\t\tfor (const box of fileBoxes) {\n\t\t\t\tlines.push(boxLabeledBorder(theme, \"╭\", \"╮\", box.topLabel, undefined, renderedWidth));\n\t\t\t\tlines.push(boxBlankLine(theme, renderedWidth));\n\t\t\t\tlines.push(...box.resultComponent.render(width));\n\t\t\t}\n\t\t\tcacheWidth = width;\n\t\t\tcacheLines = lines;\n\t\t\treturn lines;\n\t\t},\n\t};\n}\n","// Adaptive diff renderer — side-by-side (split) for short corresponding\n// changes, unified for additions/removals-only diffs and narrow terminals,\n// with long runs of unchanged context collapsed into a single\n// \"⋯ N unchanged lines hidden\" row instead of arbitrary output truncation.\n\nimport { highlightCode } from \"@earendil-works/pi-coding-agent\";\nimport type { Component } from \"@earendil-works/pi-tui\";\n\nimport { stripAnsi } from \"./ansi.js\";\nimport { dimLine } from \"./box.js\";\nimport { safeTruncateToWidth, safeVisibleWidth } from \"./render-budget.js\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\ntype DiffLine = {\n\tprefix: \"+\" | \"-\" | \" \";\n\tline: string;\n\tlineNumber: string;\n};\n\ntype SplitDiffRow = {\n\tkind: \"context\" | \"changed\" | \"added\" | \"removed\";\n\tleft?: DiffLine;\n\tright?: DiffLine;\n};\n\ntype CellLineKind = \"add\" | \"remove\" | \"context\";\n\ntype DiffSpan = { start: number; end: number };\n\ntype RgbColor = { r: number; g: number; b: number };\n\n/** Structural view of the theme as used by the diff renderers. */\nexport interface SplitDiffTheme {\n\tfg(color: string, text: string): string;\n\tgetBgAnsi?(color: string): string;\n\tgetFgAnsi?(color: string): string;\n}\n\nexport type DiffMode = \"unified\" | \"split\";\n\ntype DiffPalette = {\n\taddRowBgAnsi: string;\n\tremoveRowBgAnsi: string;\n\taddEmphasisBgAnsi: string;\n\tremoveEmphasisBgAnsi: string;\n};\n\n/** A planned render entry: a diff row, a collapsed context gap, or a budget omission. */\ntype DiffEntry =\n\t| { kind: \"row\"; row: SplitDiffRow }\n\t| { kind: \"gap\"; hidden: number }\n\t| { kind: \"omitted\"; count: number };\n\n// ── Constants ──────────────────────────────────────────────────────\n\nconst ESC = \"\\x1b\";\nconst BG_ANSI_PATTERN = new RegExp(`${ESC}\\\\[(?:4\\\\d|10\\\\d|48;5;\\\\d{1,3}|48;2;\\\\d{1,3};\\\\d{1,3};\\\\d{1,3}|49)m`, \"g\");\nconst CONTROL_CHARS = \"\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F\";\n\nconst ADD_ROW_BACKGROUND_MIX_RATIO = 0.24;\nconst REMOVE_ROW_BACKGROUND_MIX_RATIO = 0.12;\nconst ADD_INLINE_EMPHASIS_MIX_RATIO = 0.44;\nconst REMOVE_INLINE_EMPHASIS_MIX_RATIO = 0.26;\n\n/** Context lines kept on each side of a collapsed run of unchanged lines. */\nconst CONTEXT_KEEP_DEFAULT = 2;\n/** Context runs of this length (or less) are shown in full. */\nconst CONTEXT_RUN_SHOW_MAX = 4;\n\n/**\n * Minimum diff content width before split mode is even considered. Box chrome\n * (2 borders + 4 side padding) costs ~6 columns, so this corresponds to a\n * ~120-column terminal — below that the two panes wrap too aggressively and\n * unified is always used.\n */\nconst SPLIT_DIFF_MIN_WIDTH = 114;\n\n// ── ANSI color utilities (diff-specific) ───────────────────────────\n\nfunction ansi256ToRgb(code: number): RgbColor {\n\tif (code <= 15) {\n\t\tconst base16: RgbColor[] = [\n\t\t\t{ r: 0, g: 0, b: 0 },\n\t\t\t{ r: 128, g: 0, b: 0 },\n\t\t\t{ r: 0, g: 128, b: 0 },\n\t\t\t{ r: 128, g: 128, b: 0 },\n\t\t\t{ r: 0, g: 0, b: 128 },\n\t\t\t{ r: 128, g: 0, b: 128 },\n\t\t\t{ r: 0, g: 128, b: 128 },\n\t\t\t{ r: 192, g: 192, b: 192 },\n\t\t\t{ r: 128, g: 128, b: 128 },\n\t\t\t{ r: 255, g: 0, b: 0 },\n\t\t\t{ r: 0, g: 255, b: 0 },\n\t\t\t{ r: 255, g: 255, b: 0 },\n\t\t\t{ r: 0, g: 0, b: 255 },\n\t\t\t{ r: 255, g: 0, b: 255 },\n\t\t\t{ r: 0, g: 255, b: 255 },\n\t\t\t{ r: 255, g: 255, b: 255 },\n\t\t];\n\t\treturn base16[code] ?? { r: 255, g: 255, b: 255 };\n\t}\n\tif (code >= 232) {\n\t\tconst value = Math.max(0, Math.min(255, 8 + (code - 232) * 10));\n\t\treturn { r: value, g: value, b: value };\n\t}\n\tconst cube = code - 16;\n\tconst levels = [0, 95, 135, 175, 215, 255];\n\tconst blue = cube % 6;\n\tconst green = Math.floor(cube / 6) % 6;\n\tconst red = Math.floor(cube / 36) % 6;\n\treturn {\n\t\tr: levels[red] ?? 0,\n\t\tg: levels[green] ?? 0,\n\t\tb: levels[blue] ?? 0,\n\t};\n}\n\nfunction parseAnsiColorCode(ansi: string | undefined): RgbColor | null {\n\tif (!ansi) return null;\n\tconst rgbMatch = new RegExp(`${ESC}\\\\[(?:3|4)8;2;(\\\\d{1,3});(\\\\d{1,3});(\\\\d{1,3})m`).exec(ansi);\n\tif (rgbMatch) {\n\t\tconst r = Number.parseInt(rgbMatch[1] ?? \"0\", 10);\n\t\tconst g = Number.parseInt(rgbMatch[2] ?? \"0\", 10);\n\t\tconst b = Number.parseInt(rgbMatch[3] ?? \"0\", 10);\n\t\treturn { r, g, b };\n\t}\n\tconst bitMatch = new RegExp(`${ESC}\\\\[(?:3|4)8;5;(\\\\d{1,3})m`).exec(ansi);\n\tif (bitMatch) {\n\t\tconst code = Number.parseInt(bitMatch[1] ?? \"0\", 10);\n\t\treturn ansi256ToRgb(code);\n\t}\n\treturn null;\n}\n\nfunction rgbToBgAnsi(color: RgbColor): string {\n\tconst r = Math.max(0, Math.min(255, Math.round(color.r)));\n\tconst g = Math.max(0, Math.min(255, Math.round(color.g)));\n\tconst b = Math.max(0, Math.min(255, Math.round(color.b)));\n\treturn `\\x1b[48;2;${r};${g};${b}m`;\n}\n\nfunction mixRgb(base: RgbColor, tint: RgbColor, ratio: number): RgbColor {\n\tconst clamped = Math.max(0, Math.min(1, ratio));\n\treturn {\n\t\tr: base.r * (1 - clamped) + tint.r * clamped,\n\t\tg: base.g * (1 - clamped) + tint.g * clamped,\n\t\tb: base.b * (1 - clamped) + tint.b * clamped,\n\t};\n}\n\nfunction resolveDiffPalette(theme: SplitDiffTheme): DiffPalette {\n\tconst baseBg = parseAnsiColorCode(theme.getBgAnsi?.(\"toolSuccessBg\")) ??\n\t\tparseAnsiColorCode(theme.getBgAnsi?.(\"toolPendingBg\")) ?? { r: 32, g: 35, b: 42 };\n\tconst addFg = parseAnsiColorCode(theme.getFgAnsi?.(\"toolDiffAdded\")) ?? { r: 88, g: 173, b: 88 };\n\tconst removeFg = parseAnsiColorCode(theme.getFgAnsi?.(\"toolDiffRemoved\")) ?? { r: 196, g: 98, b: 98 };\n\n\tconst addRowBg = mixRgb(baseBg, addFg, ADD_ROW_BACKGROUND_MIX_RATIO);\n\tconst removeRowBg = mixRgb(baseBg, removeFg, REMOVE_ROW_BACKGROUND_MIX_RATIO);\n\tconst addEmphasisBg = mixRgb(baseBg, addFg, ADD_INLINE_EMPHASIS_MIX_RATIO);\n\tconst removeEmphasisBg = mixRgb(baseBg, removeFg, REMOVE_INLINE_EMPHASIS_MIX_RATIO);\n\n\treturn {\n\t\taddRowBgAnsi: rgbToBgAnsi(addRowBg),\n\t\tremoveRowBgAnsi: rgbToBgAnsi(removeRowBg),\n\t\taddEmphasisBgAnsi: rgbToBgAnsi(addEmphasisBg),\n\t\tremoveEmphasisBgAnsi: rgbToBgAnsi(removeEmphasisBg),\n\t};\n}\n\n// ── ANSI background helpers ────────────────────────────────────────\n\nfunction keepBackgroundAcrossResets(text: string, rowBgAnsi: string): string {\n\tif (!text) return text;\n\n\treturn text.replace(new RegExp(`${ESC}\\\\[([0-9;]*)m`, \"g\"), (sequence, rawCodes) => {\n\t\tconst split = String(rawCodes ?? \"\")\n\t\t\t.split(\";\")\n\t\t\t.filter(Boolean);\n\t\tconst codes = split.length > 0 ? split : [\"0\"]; // ESC[m == reset\n\t\tconst hasGlobalReset = codes.includes(\"0\");\n\t\tconst hasBgReset = codes.includes(\"49\");\n\t\tif (!hasGlobalReset && !hasBgReset) return sequence;\n\n\t\tconst rebuiltCodes = codes.filter((code: string) => code !== \"49\");\n\t\tconst rebuilt = rebuiltCodes.length > 0 ? `\\x1b[${rebuiltCodes.join(\";\")}m` : \"\";\n\t\treturn `${rebuilt}${rowBgAnsi}`;\n\t});\n}\n\nfunction applyBackgroundToVisibleRange(\n\tansiText: string,\n\tstart: number,\n\tend: number,\n\tbackgroundAnsi: string,\n\trestoreBackgroundAnsi: string,\n): string {\n\tif (!ansiText || start >= end || end <= 0) return ansiText;\n\n\tlet output = \"\";\n\tlet visibleIndex = 0;\n\tlet index = 0;\n\tlet inRange = false;\n\n\twhile (index < ansiText.length) {\n\t\tif (ansiText[index] === \"\\x1b\") {\n\t\t\tconst sequenceEnd = ansiText.indexOf(\"m\", index);\n\t\t\tif (sequenceEnd !== -1) {\n\t\t\t\toutput += ansiText.slice(index, sequenceEnd + 1);\n\t\t\t\tindex = sequenceEnd + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (visibleIndex === start && !inRange) {\n\t\t\toutput += backgroundAnsi;\n\t\t\tinRange = true;\n\t\t}\n\t\tif (visibleIndex === end && inRange) {\n\t\t\toutput += restoreBackgroundAnsi;\n\t\t\tinRange = false;\n\t\t}\n\n\t\toutput += ansiText[index] ?? \"\";\n\t\tvisibleIndex++;\n\t\tindex++;\n\t}\n\n\tif (inRange) output += restoreBackgroundAnsi;\n\treturn output;\n}\n\n// ── Text utilities ─────────────────────────────────────────────────\n\nfunction sanitizeSingleLineText(value: string): string {\n\treturn value\n\t\t.replace(/\\r/g, \"\")\n\t\t.replace(/\\n/g, \"\")\n\t\t.replace(new RegExp(`[${CONTROL_CHARS}]`, \"g\"), \"\");\n}\n\nfunction stripInlineBreaksPreserveAnsi(value: string): string {\n\treturn value.replace(/\\r/g, \"\").replace(/\\n/g, \"\");\n}\n\nfunction padRight(value: string, width: number): string {\n\tconst visual = safeVisibleWidth(stripAnsi(value));\n\tif (visual >= width) return value;\n\treturn value + \" \".repeat(width - visual);\n}\n\nfunction fitToWidth(value: string, width: number): string {\n\treturn padRight(safeTruncateToWidth(value, width), width);\n}\n\nfunction padRenderedLineWidth(line: string, width: number): string {\n\tconst safeWidth = Math.max(1, width);\n\tconst current = safeVisibleWidth(stripAnsi(line));\n\tif (current >= safeWidth) return line;\n\treturn line + \" \".repeat(safeWidth - current);\n}\n\nfunction wrapPlainText(text: string, width: number): string[] {\n\tconst safeWidth = Math.max(1, width);\n\tconst safeText = sanitizeSingleLineText(text);\n\tif (!safeText) return [\"\"];\n\n\tconst lines: string[] = [];\n\tlet cursor = 0;\n\n\twhile (cursor < safeText.length) {\n\t\tconst remaining = safeText.length - cursor;\n\t\tif (remaining <= safeWidth) {\n\t\t\tlines.push(safeText.slice(cursor));\n\t\t\tbreak;\n\t\t}\n\n\t\tconst window = safeText.slice(cursor, cursor + safeWidth);\n\t\tconst breakOnSpace = window.lastIndexOf(\" \");\n\n\t\tif (breakOnSpace > 0) {\n\t\t\tconst next = breakOnSpace + 1; // keep the space so offsets stay stable for inline diff spans\n\t\t\tlines.push(safeText.slice(cursor, cursor + next));\n\t\t\tcursor += next;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Fallback for long uninterrupted tokens (paths, hashes, etc.)\n\t\tlines.push(window);\n\t\tcursor += safeWidth;\n\t}\n\n\treturn lines.length > 0 ? lines : [\"\"];\n}\n\n// ── Diff parsing ───────────────────────────────────────────────────\n\nfunction parseLineNumber(value: string): number | undefined {\n\tconst trimmed = value.trim();\n\tif (!/^\\d+$/.test(trimmed)) return undefined;\n\tconst parsed = Number.parseInt(trimmed, 10);\n\treturn Number.isFinite(parsed) ? parsed : undefined;\n}\n\nfunction makeDiffLine(prefix: \"+\" | \"-\" | \" \", lineNumber: string | number | undefined, line: string): DiffLine {\n\treturn {\n\t\tprefix,\n\t\tlineNumber: lineNumber === undefined ? \"\" : String(lineNumber),\n\t\tline,\n\t};\n}\n\nfunction parseDiffLine(rawLine: string): DiffLine | undefined {\n\tconst match = rawLine.match(/^([+\\- ])\\s?(.*)$/);\n\tif (!match) return undefined;\n\tconst [, prefix, rest = \"\"] = match;\n\tif (prefix !== \"+\" && prefix !== \"-\" && prefix !== \" \") return undefined;\n\n\tconst gutterMatch = rest.match(/^(\\d+)\\s(.*)$/);\n\tconst lineNumber = gutterMatch?.[1] ?? \"\";\n\tconst line = gutterMatch?.[2] ?? rest;\n\tconst cleanLineNumber = sanitizeSingleLineText(lineNumber);\n\tconst cleanLine = sanitizeSingleLineText(line).replace(/\\t/g, \" \");\n\treturn { prefix, lineNumber: cleanLineNumber, line: cleanLine };\n}\n\nfunction computeInlineDiffSpans(leftLine: string, rightLine: string): { left: DiffSpan[]; right: DiffSpan[] } {\n\tif (leftLine === rightLine) return { left: [], right: [] };\n\tlet start = 0;\n\tconst minLen = Math.min(leftLine.length, rightLine.length);\n\twhile (start < minLen && leftLine[start] === rightLine[start]) start++;\n\n\tlet leftEnd = leftLine.length;\n\tlet rightEnd = rightLine.length;\n\twhile (leftEnd > start && rightEnd > start && leftLine[leftEnd - 1] === rightLine[rightEnd - 1]) {\n\t\tleftEnd--;\n\t\trightEnd--;\n\t}\n\n\tconst leftSpan = leftEnd > start ? [{ start, end: leftEnd }] : [];\n\tconst rightSpan = rightEnd > start ? [{ start, end: rightEnd }] : [];\n\treturn { left: leftSpan, right: rightSpan };\n}\n\n// ── Exported helpers ───────────────────────────────────────────────\n\nexport function buildSplitRows(diff: string): SplitDiffRow[] {\n\tconst rows: SplitDiffRow[] = [];\n\tconst pendingLeft: DiffLine[] = [];\n\tconst pendingRight: DiffLine[] = [];\n\tlet oldCursor: number | undefined;\n\tlet newCursor: number | undefined;\n\n\tconst flushPending = () => {\n\t\twhile (pendingLeft.length > 0 || pendingRight.length > 0) {\n\t\t\tconst left = pendingLeft.shift();\n\t\t\tconst right = pendingRight.shift();\n\t\t\tif (left && right) rows.push({ kind: \"changed\", left, right });\n\t\t\telse if (left) rows.push({ kind: \"removed\", left });\n\t\t\telse if (right) rows.push({ kind: \"added\", right });\n\t\t}\n\t};\n\n\tfor (const rawLine of diff.split(\"\\n\")) {\n\t\tconst parsed = parseDiffLine(rawLine);\n\t\tif (!parsed) continue;\n\n\t\tconst parsedNum = parseLineNumber(parsed.lineNumber);\n\t\tif (parsed.prefix === \"-\") {\n\t\t\tconst oldNum = parsedNum ?? oldCursor;\n\t\t\tif (oldNum !== undefined) oldCursor = oldNum + 1;\n\t\t\tpendingLeft.push(makeDiffLine(\"-\", oldNum, parsed.line));\n\t\t\tcontinue;\n\t\t}\n\t\tif (parsed.prefix === \"+\") {\n\t\t\tconst newNum = parsedNum ?? newCursor;\n\t\t\tif (newNum !== undefined) newCursor = newNum + 1;\n\t\t\tpendingRight.push(makeDiffLine(\"+\", newNum, parsed.line));\n\t\t\tcontinue;\n\t\t}\n\n\t\tflushPending();\n\n\t\tconst oldNum = parsedNum ?? oldCursor;\n\t\tconst newNum = newCursor ?? oldNum;\n\t\tif (oldNum !== undefined) oldCursor = oldNum + 1;\n\t\tif (newNum !== undefined) newCursor = newNum + 1;\n\n\t\trows.push({\n\t\t\tkind: \"context\",\n\t\t\tleft: makeDiffLine(\" \", oldNum, parsed.line),\n\t\t\tright: makeDiffLine(\" \", newNum, parsed.line),\n\t\t});\n\t}\n\n\tflushPending();\n\treturn rows;\n}\n\nexport function countDiffStats(diff: string): { additions: number; removals: number } {\n\tlet additions = 0;\n\tlet removals = 0;\n\tfor (const line of diff.split(\"\\n\")) {\n\t\tif (line.startsWith(\"+++\") || line.startsWith(\"---\")) continue;\n\t\tif (line.startsWith(\"+\")) additions += 1;\n\t\tif (line.startsWith(\"-\")) removals += 1;\n\t}\n\treturn { additions, removals };\n}\n\nexport function extractEditedPath(message: string): string | undefined {\n\tconst m = message.match(/Successfully replaced (?:text|\\d+ block\\(s\\)|lines L\\d+-\\d+) in (.+)\\.$/);\n\treturn m?.[1];\n}\n\nexport function firstText(content: Array<{ type: string; text?: string }>): string {\n\tfor (const part of content) {\n\t\tif (part.type === \"text\" && typeof part.text === \"string\") {\n\t\t\treturn part.text;\n\t\t}\n\t}\n\treturn \"\";\n}\n\nfunction longestChangedLineWidth(rows: SplitDiffRow[]): number {\n\tlet longest = 0;\n\tfor (const row of rows) {\n\t\tconst candidates: string[] = [];\n\t\tif (row.kind === \"changed\") {\n\t\t\tif (row.left) candidates.push(row.left.line);\n\t\t\tif (row.right) candidates.push(row.right.line);\n\t\t} else if (row.kind === \"added\" && row.right) {\n\t\t\tcandidates.push(row.right.line);\n\t\t} else if (row.kind === \"removed\" && row.left) {\n\t\t\tcandidates.push(row.left.line);\n\t\t}\n\t\tfor (const candidate of candidates) {\n\t\t\tlongest = Math.max(longest, safeVisibleWidth(candidate));\n\t\t}\n\t}\n\treturn longest;\n}\n\n/**\n * Adaptive layout rule: split side-by-side only when the change has both\n * additions and removals (so both panes carry content), the terminal is wide\n * enough, and no changed line is so long that it would wrap badly in a half\n * pane. Everything else renders as a unified diff.\n */\nexport function pickDiffMode(\n\tstats: { additions: number; removals: number },\n\trows: SplitDiffRow[],\n\twidth: number,\n): DiffMode {\n\tif (stats.additions <= 0 || stats.removals <= 0) return \"unified\";\n\tif (width < SPLIT_DIFF_MIN_WIDTH) return \"unified\";\n\tif (longestChangedLineWidth(rows) > width / 2) return \"unified\";\n\treturn \"split\";\n}\n\nfunction collapseContextRows(rows: SplitDiffRow[], options: { keep: number; runShowMax?: number }): DiffEntry[] {\n\tconst keep = options.keep;\n\tconst runShowMax = options.runShowMax ?? CONTEXT_RUN_SHOW_MAX;\n\tconst out: DiffEntry[] = [];\n\tlet i = 0;\n\n\twhile (i < rows.length) {\n\t\tconst row = rows[i];\n\t\tif (row?.kind !== \"context\") {\n\t\t\tif (row) out.push({ kind: \"row\", row });\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet j = i;\n\t\twhile (j < rows.length && rows[j]?.kind === \"context\") j++;\n\t\tconst run = j - i;\n\n\t\tif (run <= runShowMax) {\n\t\t\tfor (let k = i; k < j; k++) out.push({ kind: \"row\", row: rows[k] as SplitDiffRow });\n\t\t} else {\n\t\t\tconst leading = i === 0;\n\t\t\tconst trailing = j >= rows.length;\n\t\t\tconst keepHead = leading ? 0 : Math.min(keep, run);\n\t\t\tconst keepTail = trailing ? 0 : Math.min(keep, Math.max(0, run - keepHead));\n\t\t\tconst hidden = Math.max(0, run - keepHead - keepTail);\n\n\t\t\tif (keepHead > 0) {\n\t\t\t\tfor (let k = i; k < i + keepHead; k++) out.push({ kind: \"row\", row: rows[k] as SplitDiffRow });\n\t\t\t}\n\t\t\tif (hidden > 0) out.push({ kind: \"gap\", hidden });\n\t\t\tif (keepTail > 0) {\n\t\t\t\tfor (let k = j - keepTail; k < j; k++) out.push({ kind: \"row\", row: rows[k] as SplitDiffRow });\n\t\t\t}\n\t\t}\n\n\t\ti = j;\n\t}\n\n\treturn out;\n}\n\n/**\n * Plan the render entries under a row budget: collapse long context runs with\n * the default padding first, then drop all context if the diff is still too\n * tall, then finally trim the head and append an omission marker. The budget\n * applies to entries (each renders at least one line, gaps included).\n */\nfunction planEntries(rows: SplitDiffRow[], maxRows: number): DiffEntry[] {\n\tconst budget = Math.max(1, maxRows);\n\n\tlet entries = collapseContextRows(rows, { keep: CONTEXT_KEEP_DEFAULT });\n\tif (entries.length <= budget) return entries;\n\n\tentries = collapseContextRows(rows, { keep: 0, runShowMax: 0 });\n\tif (entries.length <= budget) return entries;\n\n\tconst kept = entries.slice(0, Math.max(1, budget - 1));\n\tconst omitted = Math.max(0, entries.length - kept.length);\n\tif (omitted <= 0) return kept;\n\treturn [...kept, { kind: \"omitted\", count: omitted }];\n}\n\nfunction formatGapLabel(hidden: number): string {\n\treturn `⋯ ${hidden} unchanged ${hidden === 1 ? \"line\" : \"lines\"} hidden`;\n}\n\nfunction formatOmittedLabel(count: number): string {\n\treturn `⋯ ${count} ${count === 1 ? \"line\" : \"lines\"} omitted · Ctrl+O to show full diff`;\n}\n\n// ── DiffRenderContext ──────────────────────────────────────────────\n// Shared per-instance state: palette, gutter width, syntax-highlight cache,\n// and inline-emphasis spans for paired changed rows.\n\nclass DiffRenderContext {\n\treadonly lineNumberWidth: number;\n\treadonly palette: DiffPalette;\n\treadonly containerBgAnsi: string;\n\tprivate readonly highlightCache = new Map<string, string>();\n\tprivate readonly inlineHighlights = new WeakMap<DiffLine, DiffSpan[]>();\n\n\tconstructor(\n\t\tprivate readonly theme: SplitDiffTheme,\n\t\trows: SplitDiffRow[],\n\t\tprivate readonly language?: string,\n\t) {\n\t\tlet maxDigits = 3;\n\t\tfor (const row of rows) {\n\t\t\tconst leftDigits = row.left?.lineNumber.trim().length ?? 0;\n\t\t\tconst rightDigits = row.right?.lineNumber.trim().length ?? 0;\n\t\t\tmaxDigits = Math.max(maxDigits, leftDigits, rightDigits);\n\n\t\t\tif (row.kind === \"changed\" && row.left && row.right) {\n\t\t\t\tconst spans = computeInlineDiffSpans(row.left.line, row.right.line);\n\t\t\t\tif (spans.left.length > 0) this.inlineHighlights.set(row.left, spans.left);\n\t\t\t\tif (spans.right.length > 0) this.inlineHighlights.set(row.right, spans.right);\n\t\t\t}\n\t\t}\n\t\tthis.lineNumberWidth = maxDigits;\n\t\tthis.palette = resolveDiffPalette(theme);\n\t\tthis.containerBgAnsi = theme.getBgAnsi?.(\"toolSuccessBg\") ?? \"\";\n\t}\n\n\tfg(color: string, text: string): string {\n\t\treturn this.theme.fg(color, text);\n\t}\n\n\tinlineSpans(line: DiffLine): DiffSpan[] {\n\t\treturn this.inlineHighlights.get(line) ?? [];\n\t}\n\n\tsyntaxHighlight(line: string): string {\n\t\tif (!this.language) return stripInlineBreaksPreserveAnsi(line);\n\t\tconst safeLine = sanitizeSingleLineText(line);\n\t\tconst key = `${this.language}\\n${safeLine}`;\n\t\tconst cached = this.highlightCache.get(key);\n\t\tif (cached) return cached;\n\n\t\tlet highlighted = safeLine;\n\t\ttry {\n\t\t\thighlighted = highlightCode(safeLine, this.language)[0] ?? safeLine;\n\t\t\thighlighted = stripInlineBreaksPreserveAnsi(highlighted).replace(BG_ANSI_PATTERN, \"\");\n\t\t} catch {\n\t\t\thighlighted = safeLine;\n\t\t}\n\t\tthis.highlightCache.set(key, highlighted);\n\t\treturn highlighted;\n\t}\n}\n\n// ── Unified diff renderer ──────────────────────────────────────────\n// One column: marker + gutter + content, with added/removed lines carrying\n// the same row backgrounds as the split view. Changed rows expand back into\n// their removed-then-added pair (like `git diff`).\n\nclass UnifiedDiffRenderer {\n\tconstructor(\n\t\tprivate readonly ctx: DiffRenderContext,\n\t\tprivate readonly entries: DiffEntry[],\n\t) {}\n\n\tprivate gapLine(entry: { hidden: number }, width: number): string {\n\t\treturn padRenderedLineWidth(this.ctx.fg(\"muted\", formatGapLabel(entry.hidden)), width);\n\t}\n\n\tprivate omittedLine(entry: { count: number }, width: number): string {\n\t\treturn padRenderedLineWidth(this.ctx.fg(\"muted\", formatOmittedLabel(entry.count)), width);\n\t}\n\n\trender(width: number): string[] {\n\t\tconst safeWidth = Math.max(20, width);\n\t\tconst prefixWidth = 1 + 1 + this.ctx.lineNumberWidth + 2; // marker + space + gutter + 2 spaces\n\t\tconst codeWidth = Math.max(1, safeWidth - prefixWidth);\n\t\tconst lines: string[] = [];\n\n\t\tfor (const entry of this.entries) {\n\t\t\tif (entry.kind === \"gap\") {\n\t\t\t\tlines.push(this.gapLine(entry, safeWidth));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (entry.kind === \"omitted\") {\n\t\t\t\tlines.push(this.omittedLine(entry, safeWidth));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlines.push(...this.rowLines(entry.row, codeWidth, safeWidth));\n\t\t}\n\n\t\treturn lines;\n\t}\n\n\tprivate rowLines(row: SplitDiffRow, codeWidth: number, width: number): string[] {\n\t\tconst segments: Array<{ kind: CellLineKind; line: DiffLine }> = [];\n\t\tif (row.kind === \"changed\") {\n\t\t\tif (row.left) segments.push({ kind: \"remove\", line: row.left });\n\t\t\tif (row.right) segments.push({ kind: \"add\", line: row.right });\n\t\t} else if (row.kind === \"added\" && row.right) {\n\t\t\tsegments.push({ kind: \"add\", line: row.right });\n\t\t} else if (row.kind === \"removed\" && row.left) {\n\t\t\tsegments.push({ kind: \"remove\", line: row.left });\n\t\t} else {\n\t\t\tconst line = row.left ?? row.right;\n\t\t\tif (line) segments.push({ kind: \"context\", line });\n\t\t}\n\n\t\tconst out: string[] = [];\n\t\tfor (const segment of segments) {\n\t\t\tout.push(...this.segmentLines(segment.kind, segment.line, codeWidth, width));\n\t\t}\n\t\treturn out;\n\t}\n\n\tprivate segmentLines(kind: CellLineKind, line: DiffLine, codeWidth: number, width: number): string[] {\n\t\tconst isAdd = kind === \"add\";\n\t\tconst isRemove = kind === \"remove\";\n\t\tconst blank = line.line === \"\";\n\t\t// Blank added/removed lines render like context (no tinted band), but the\n\t\t// +/- marker still shows that a line was inserted/removed.\n\t\tconst visualKind: CellLineKind = kind === \"context\" || blank ? \"context\" : kind;\n\t\tconst markerChar = kind === \"context\" ? \" \" : isAdd ? \"+\" : \"-\";\n\t\tconst markerColor = isAdd ? \"toolDiffAdded\" : isRemove ? \"toolDiffRemoved\" : \"dim\";\n\t\tconst gutterColor = visualKind === \"context\" ? \"dim\" : isAdd ? \"toolDiffAdded\" : \"toolDiffRemoved\";\n\t\tconst gutter = line.lineNumber.trim().padStart(this.ctx.lineNumberWidth, \" \");\n\n\t\tconst firstPrefixAnsi = `${this.ctx.fg(markerColor, markerChar)} ${this.ctx.fg(gutterColor, gutter)} `;\n\t\tconst firstPrefixPlain = `${markerChar} ${gutter} `;\n\t\tconst contPrefixAnsi = `${this.ctx.fg(\"dim\", \" \")} ${this.ctx.fg(\"dim\", \" \".repeat(this.ctx.lineNumberWidth))} `;\n\t\tconst contPrefixPlain = ` ${\" \".repeat(1 + this.ctx.lineNumberWidth)} `;\n\n\t\tconst rowBg =\n\t\t\tvisualKind === \"add\"\n\t\t\t\t? this.ctx.palette.addRowBgAnsi\n\t\t\t\t: visualKind === \"remove\"\n\t\t\t\t\t? this.ctx.palette.removeRowBgAnsi\n\t\t\t\t\t: undefined;\n\n\t\tconst plainSegments = wrapPlainText(line.line, codeWidth);\n\t\tconst out: string[] = [];\n\n\t\tfor (let i = 0; i < plainSegments.length; i++) {\n\t\t\tconst prefixAnsi = i === 0 ? firstPrefixAnsi : contPrefixAnsi;\n\t\t\tconst prefixPlain = i === 0 ? firstPrefixPlain : contPrefixPlain;\n\t\t\tconst plainSegment = plainSegments[i] ?? \"\";\n\t\t\tlet segment = this.ctx.syntaxHighlight(plainSegment);\n\t\t\tsegment = fitToWidth(segment, codeWidth);\n\n\t\t\tlet rendered = prefixAnsi + segment;\n\t\t\tconst expectedWidth = safeVisibleWidth(prefixPlain) + codeWidth;\n\t\t\tconst currentWidth = safeVisibleWidth(stripAnsi(rendered));\n\t\t\tif (currentWidth < expectedWidth) {\n\t\t\t\trendered += \" \".repeat(expectedWidth - currentWidth);\n\t\t\t}\n\n\t\t\tif (rowBg) {\n\t\t\t\trendered = `${rowBg}${keepBackgroundAcrossResets(rendered, rowBg)}${this.ctx.containerBgAnsi}`;\n\t\t\t}\n\t\t\tout.push(padRenderedLineWidth(rendered, width));\n\t\t}\n\n\t\treturn out;\n\t}\n}\n\n// ── Split (side-by-side) diff renderer ─────────────────────────────\n\nclass SplitDiffRenderer {\n\tconstructor(\n\t\tprivate readonly ctx: DiffRenderContext,\n\t\tprivate readonly entries: DiffEntry[],\n\t) {}\n\n\tprivate getCellLineKind(kind: SplitDiffRow[\"kind\"], side: \"left\" | \"right\"): CellLineKind {\n\t\tif (kind === \"changed\") return side === \"left\" ? \"remove\" : \"add\";\n\t\tif (kind === \"removed\" && side === \"left\") return \"remove\";\n\t\tif (kind === \"added\" && side === \"right\") return \"add\";\n\t\treturn \"context\";\n\t}\n\n\tprivate getVisualLineKind(kind: SplitDiffRow[\"kind\"], side: \"left\" | \"right\", line?: DiffLine): CellLineKind {\n\t\tconst base = this.getCellLineKind(kind, side);\n\t\tif ((kind === \"added\" || kind === \"removed\") && (line?.line ?? \"\") === \"\") {\n\t\t\treturn \"context\";\n\t\t}\n\t\treturn base;\n\t}\n\n\tprivate getNumberColor(lineKind: CellLineKind): \"toolDiffRemoved\" | \"toolDiffAdded\" | \"dim\" {\n\t\tif (lineKind === \"remove\") return \"toolDiffRemoved\";\n\t\tif (lineKind === \"add\") return \"toolDiffAdded\";\n\t\treturn \"dim\";\n\t}\n\n\tprivate getRowBackground(lineKind: CellLineKind): string | undefined {\n\t\tif (lineKind === \"add\") return this.ctx.palette.addRowBgAnsi;\n\t\tif (lineKind === \"remove\") return this.ctx.palette.removeRowBgAnsi;\n\t\treturn undefined;\n\t}\n\n\tprivate getEmphasisBackground(lineKind: CellLineKind): string | undefined {\n\t\tif (lineKind === \"add\") return this.ctx.palette.addEmphasisBgAnsi;\n\t\tif (lineKind === \"remove\") return this.ctx.palette.removeEmphasisBgAnsi;\n\t\treturn undefined;\n\t}\n\n\tprivate getCellFillBackground(kind: SplitDiffRow[\"kind\"], side: \"left\" | \"right\"): string | undefined {\n\t\tswitch (kind) {\n\t\t\tcase \"changed\":\n\t\t\t\treturn side === \"left\" ? this.ctx.palette.removeRowBgAnsi : this.ctx.palette.addRowBgAnsi;\n\t\t\tcase \"removed\":\n\t\t\t\treturn side === \"left\" ? this.ctx.palette.removeRowBgAnsi : undefined;\n\t\t\tcase \"added\":\n\t\t\t\treturn side === \"right\" ? this.ctx.palette.addRowBgAnsi : undefined;\n\t\t\tdefault:\n\t\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate blankCell(kind: SplitDiffRow[\"kind\"], side: \"left\" | \"right\", columnWidth: number): string {\n\t\tconst lineKind = this.getCellLineKind(kind, side);\n\t\tconst markerChar = lineKind === \"add\" || lineKind === \"remove\" ? \"▌\" : \" \";\n\t\tconst markerColor =\n\t\t\tlineKind === \"add\" ? \"toolDiffAdded\" : lineKind === \"remove\" ? \"toolDiffRemoved\" : \"borderMuted\";\n\t\tconst marker = this.ctx.fg(markerColor, markerChar);\n\t\tconst lineNumber = this.ctx.fg(\"dim\", \" \".repeat(this.ctx.lineNumberWidth));\n\t\tconst divider = dimLine(\" │ \");\n\t\tconst prefix = `${marker} ${lineNumber}${divider}`;\n\t\tconst prefixPlain = `${markerChar} ${\" \".repeat(this.ctx.lineNumberWidth)} │ `;\n\t\tconst tailWidth = Math.max(0, columnWidth - safeVisibleWidth(prefixPlain));\n\t\tlet rendered = prefix + \" \".repeat(tailWidth);\n\n\t\tconst bg = this.getCellFillBackground(kind, side);\n\t\tif (!bg) return padRenderedLineWidth(rendered, columnWidth);\n\t\trendered = `${bg}${keepBackgroundAcrossResets(rendered, bg)}${this.ctx.containerBgAnsi}`;\n\t\treturn padRenderedLineWidth(rendered, columnWidth);\n\t}\n\n\tprivate formatCellLines(\n\t\tkind: SplitDiffRow[\"kind\"],\n\t\tside: \"left\" | \"right\",\n\t\tline: DiffLine | undefined,\n\t\tcolumnWidth: number,\n\t): string[] {\n\t\tif (!line) return [this.blankCell(kind, side, columnWidth)];\n\n\t\tconst lineKind = this.getVisualLineKind(kind, side, line);\n\t\tconst markerChar = lineKind === \"add\" || lineKind === \"remove\" ? \"▌\" : \" \";\n\t\tconst markerColor =\n\t\t\tlineKind === \"add\" ? \"toolDiffAdded\" : lineKind === \"remove\" ? \"toolDiffRemoved\" : \"borderMuted\";\n\t\tconst lineNumber = line.lineNumber.trim().padStart(this.ctx.lineNumberWidth, \" \");\n\n\t\tconst firstPrefixAnsi =\n\t\t\tthis.ctx.fg(markerColor, markerChar) +\n\t\t\t\" \" +\n\t\t\tthis.ctx.fg(this.getNumberColor(lineKind), lineNumber) +\n\t\t\tdimLine(\" │ \");\n\t\tconst firstPrefixPlain = `${markerChar} ${lineNumber} │ `;\n\n\t\tconst contPrefixAnsi =\n\t\t\tthis.ctx.fg(markerColor, markerChar) +\n\t\t\t\" \" +\n\t\t\tthis.ctx.fg(\"dim\", \" \".repeat(this.ctx.lineNumberWidth)) +\n\t\t\tdimLine(\" │ \");\n\t\tconst contPrefixPlain = `${markerChar} ${\" \".repeat(this.ctx.lineNumberWidth)} │ `;\n\n\t\tconst codeWidth = Math.max(1, columnWidth - safeVisibleWidth(firstPrefixPlain));\n\t\tconst rowBg = this.getRowBackground(lineKind);\n\t\tconst emphasisBg = this.getEmphasisBackground(lineKind);\n\n\t\tconst plainSegments = wrapPlainText(line.line, codeWidth);\n\t\tconst lines: string[] = [];\n\t\tconst spans = this.ctx.inlineSpans(line);\n\n\t\tlet consumed = 0;\n\t\tfor (let i = 0; i < plainSegments.length; i++) {\n\t\t\tconst prefixAnsi = i === 0 ? firstPrefixAnsi : contPrefixAnsi;\n\t\t\tconst prefixPlain = i === 0 ? firstPrefixPlain : contPrefixPlain;\n\t\t\tconst plainSegment = plainSegments[i] ?? \"\";\n\t\t\tlet segment = this.ctx.syntaxHighlight(plainSegment);\n\n\t\t\tif (spans.length > 0 && emphasisBg) {\n\t\t\t\tconst segmentStart = consumed;\n\t\t\t\tfor (let si = spans.length - 1; si >= 0; si--) {\n\t\t\t\t\tconst span = spans[si];\n\t\t\t\t\tif (!span) continue;\n\t\t\t\t\tconst localStart = Math.max(0, span.start - segmentStart);\n\t\t\t\t\tconst localEnd = Math.min(plainSegment.length, span.end - segmentStart);\n\t\t\t\t\tif (localEnd > localStart) {\n\t\t\t\t\t\tsegment = applyBackgroundToVisibleRange(\n\t\t\t\t\t\t\tsegment,\n\t\t\t\t\t\t\tlocalStart,\n\t\t\t\t\t\t\tlocalEnd,\n\t\t\t\t\t\t\temphasisBg,\n\t\t\t\t\t\t\trowBg ?? this.ctx.containerBgAnsi,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsegment = fitToWidth(segment, codeWidth);\n\t\t\tlet rendered = prefixAnsi + segment;\n\n\t\t\t// Defensive pad if prefix widths diverge because of unicode widths\n\t\t\tconst expectedWidth = safeVisibleWidth(prefixPlain) + codeWidth;\n\t\t\tconst currentWidth = safeVisibleWidth(stripAnsi(rendered));\n\t\t\tif (currentWidth < expectedWidth) {\n\t\t\t\trendered += \" \".repeat(expectedWidth - currentWidth);\n\t\t\t}\n\n\t\t\tif (rowBg) {\n\t\t\t\trendered = `${rowBg}${keepBackgroundAcrossResets(rendered, rowBg)}${this.ctx.containerBgAnsi}`;\n\t\t\t}\n\t\t\tlines.push(padRenderedLineWidth(rendered, columnWidth));\n\t\t\tconsumed += plainSegment.length;\n\t\t}\n\n\t\treturn lines;\n\t}\n\n\tprivate gapLine(entry: { hidden: number }, width: number): string {\n\t\treturn padRenderedLineWidth(this.ctx.fg(\"muted\", formatGapLabel(entry.hidden)), width);\n\t}\n\n\tprivate omittedLine(entry: { count: number }, width: number): string {\n\t\treturn padRenderedLineWidth(this.ctx.fg(\"muted\", formatOmittedLabel(entry.count)), width);\n\t}\n\n\trender(width: number): string[] {\n\t\tconst safeWidth = Math.max(20, width);\n\t\tconst columnSeparator = dimLine(\" │ \");\n\t\tconst separatorWidth = safeVisibleWidth(stripAnsi(columnSeparator));\n\t\tconst leftWidth = Math.max(20, Math.floor((safeWidth - separatorWidth) / 2));\n\t\tconst rightWidth = Math.max(20, safeWidth - separatorWidth - leftWidth);\n\n\t\tconst formatBorderCell = (columnWidth: number, junction: string): string => {\n\t\t\tconst safeColumnWidth = Math.max(1, columnWidth);\n\t\t\tconst chars = \"─\".repeat(safeColumnWidth).split(\"\");\n\t\t\tconst dividerIndex = this.ctx.lineNumberWidth + 3;\n\t\t\tif (dividerIndex >= 0 && dividerIndex < chars.length) {\n\t\t\t\tchars[dividerIndex] = junction;\n\t\t\t}\n\t\t\treturn dimLine(chars.join(\"\"));\n\t\t};\n\n\t\tconst formatHeaderCell = (label: string, columnWidth: number): string => {\n\t\t\t// Keep marker+space columns, then place label inside the line-number column.\n\t\t\tconst markerPad = \" \";\n\t\t\tconst lineNumberLabel = fitToWidth(label, this.ctx.lineNumberWidth);\n\t\t\tconst prefixAnsi = dimLine(markerPad) + this.ctx.fg(\"dim\", lineNumberLabel) + dimLine(\" │ \");\n\t\t\tconst prefixPlain = `${markerPad}${stripAnsi(lineNumberLabel)} │ `;\n\t\t\tconst codeWidth = Math.max(0, columnWidth - safeVisibleWidth(prefixPlain));\n\t\t\treturn padRenderedLineWidth(prefixAnsi + \" \".repeat(codeWidth), columnWidth);\n\t\t};\n\n\t\tconst lines: string[] = [];\n\t\tlines.push(\n\t\t\tpadRenderedLineWidth(\n\t\t\t\tformatBorderCell(leftWidth, \"┬\") + dimLine(\"─┬─\") + formatBorderCell(rightWidth, \"┬\"),\n\t\t\t\tsafeWidth,\n\t\t\t),\n\t\t);\n\t\tlines.push(\n\t\t\tpadRenderedLineWidth(\n\t\t\t\tformatHeaderCell(\"old\", leftWidth) + columnSeparator + formatHeaderCell(\"new\", rightWidth),\n\t\t\t\tsafeWidth,\n\t\t\t),\n\t\t);\n\n\t\tfor (const entry of this.entries) {\n\t\t\tif (entry.kind === \"gap\") {\n\t\t\t\tlines.push(this.gapLine(entry, safeWidth));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (entry.kind === \"omitted\") {\n\t\t\t\tlines.push(this.omittedLine(entry, safeWidth));\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst row = entry.row;\n\t\t\tconst leftCellLines = this.formatCellLines(row.kind, \"left\", row.left, leftWidth);\n\t\t\tconst rightCellLines = this.formatCellLines(row.kind, \"right\", row.right, rightWidth);\n\t\t\tconst rowHeight = Math.max(leftCellLines.length, rightCellLines.length);\n\n\t\t\tfor (let i = 0; i < rowHeight; i++) {\n\t\t\t\tconst fallbackKind: SplitDiffRow[\"kind\"] = row.kind === \"changed\" ? \"context\" : row.kind;\n\t\t\t\tconst leftCell = leftCellLines[i] ?? this.blankCell(fallbackKind, \"left\", leftWidth);\n\t\t\t\tconst rightCell = rightCellLines[i] ?? this.blankCell(fallbackKind, \"right\", rightWidth);\n\t\t\t\tconst joined = padRenderedLineWidth(leftCell + columnSeparator + rightCell, safeWidth);\n\t\t\t\tlines.push(joined);\n\t\t\t}\n\t\t}\n\n\t\tlines.push(\n\t\t\tpadRenderedLineWidth(\n\t\t\t\tformatBorderCell(leftWidth, \"┴\") + dimLine(\"─┴─\") + formatBorderCell(rightWidth, \"┴\"),\n\t\t\t\tsafeWidth,\n\t\t\t),\n\t\t);\n\t\treturn lines;\n\t}\n}\n\n// ── AdaptiveDiffComponent ──────────────────────────────────────────\n\n/**\n * Boxed diff component that picks unified vs split layout per render width\n * (see `pickDiffMode`) and collapses long unchanged context instead of\n * truncating arbitrarily.\n */\nexport class AdaptiveDiffComponent implements Component {\n\tprivate cacheWidth: number | undefined;\n\tprivate cacheLines: string[] | undefined;\n\tprivate readonly ctx: DiffRenderContext;\n\tprivate readonly stats: { additions: number; removals: number };\n\tprivate readonly unified: UnifiedDiffRenderer;\n\tprivate readonly split: SplitDiffRenderer;\n\tprivate readonly collapsed: boolean;\n\n\tconstructor(\n\t\ttheme: SplitDiffTheme,\n\t\tprivate readonly rows: SplitDiffRow[],\n\t\tmaxRows: number,\n\t\tlanguage?: string,\n\t) {\n\t\tthis.ctx = new DiffRenderContext(theme, rows, language);\n\t\tthis.stats = { additions: 0, removals: 0 };\n\t\tfor (const row of rows) {\n\t\t\tif (row.kind === \"added\" || row.kind === \"changed\") this.stats.additions++;\n\t\t\tif (row.kind === \"removed\" || row.kind === \"changed\") this.stats.removals++;\n\t\t}\n\t\tconst entries = planEntries(rows, maxRows);\n\t\tthis.collapsed = entries.some((entry) => entry.kind !== \"row\");\n\t\tthis.unified = new UnifiedDiffRenderer(this.ctx, entries);\n\t\tthis.split = new SplitDiffRenderer(this.ctx, entries);\n\t}\n\n\t/** True when any unchanged context was collapsed or rows were omitted. */\n\thasCollapsed(): boolean {\n\t\treturn this.collapsed;\n\t}\n\n\tmodeForWidth(width: number): DiffMode {\n\t\treturn pickDiffMode(this.stats, this.rows, Math.max(20, width));\n\t}\n\n\trender(width: number): string[] {\n\t\tif (this.cacheWidth === width && this.cacheLines) return this.cacheLines;\n\n\t\tconst safeWidth = Math.max(20, width);\n\t\tconst mode = this.modeForWidth(safeWidth);\n\t\tconst lines = mode === \"split\" ? this.split.render(safeWidth) : this.unified.render(safeWidth);\n\n\t\tthis.cacheWidth = width;\n\t\tthis.cacheLines = lines;\n\t\treturn lines;\n\t}\n\n\tinvalidate(): void {\n\t\tthis.cacheWidth = undefined;\n\t\tthis.cacheLines = undefined;\n\t}\n}\n","// Shared context/view types + common helpers for the boxed tool renderers.\n\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport type { BoxTheme } from \"../../../shared/box.js\";\nimport {\n\tboxedToolWidthKey,\n\tclearCompactBoxedFooter,\n\tformatBoxedFooter,\n\tformatBoxedFooterFromValues,\n\tgetTextOutput,\n\trenderCompactBoxedFooter,\n\trenderCompactBoxedToolCall,\n\tresolveRelativePath,\n\tshortenPath,\n} from \"../../../shared/box.js\";\nimport {\n\tgetStateElapsedMs,\n\tisResultSeen,\n\tmarkResultSeen,\n\trecordExecutionEnded,\n\trecordExecutionStarted,\n\tstartElapsedTicker,\n\tstopElapsedTicker,\n} from \"./session-config.js\";\n\n/** Renderer context delivered by Pi's ToolExecutionComponent (getRenderContext). */\nexport interface BoxedToolContext {\n\treadonly args: Record<string, unknown>;\n\treadonly toolCallId: string;\n\treadonly invalidate: () => void;\n\treadonly state: Record<string, unknown>;\n\treadonly cwd: string;\n\treadonly executionStarted: boolean;\n\treadonly argsComplete: boolean;\n\treadonly isPartial: boolean;\n\treadonly expanded: boolean;\n\treadonly showImages: boolean;\n\treadonly isError: boolean;\n\treadonly lastComponent?: unknown;\n}\n\n/** Result view delivered to result renderers: { content, details }. */\nexport interface BoxedToolResult {\n\treadonly content?: readonly unknown[];\n\treadonly details?: unknown;\n}\n\nexport type BoxedCallRenderer = (\n\targs: Record<string, unknown>,\n\ttheme: BoxTheme,\n\tcontext: BoxedToolContext,\n) => Component;\nexport type BoxedResultRenderer = (\n\tresult: BoxedToolResult,\n\toptions: { expanded: boolean; isPartial: boolean },\n\ttheme: BoxTheme,\n\tcontext: BoxedToolContext,\n) => Component;\n\nexport interface BoxedToolDefinition {\n\treadonly call: BoxedCallRenderer;\n\treadonly result: BoxedResultRenderer;\n}\n\nexport function pendingFlag(context: BoxedToolContext): boolean {\n\treturn Boolean(context.isPartial);\n}\n\n/** Normalized display path: shortens HOME and resolves relative to the session cwd. */\nexport function displayPath(rawPath: string, context: BoxedToolContext): string {\n\tconst path = String(rawPath ?? \"\");\n\tif (!path) return \"(unknown)\";\n\treturn shortenPath(resolveRelativePath(path, context.cwd));\n}\n\nexport function pathRangeDetail(rawPath: string, offset: unknown, limit: unknown, context: BoxedToolContext): string {\n\tconst path = displayPath(rawPath, context);\n\tlet range = \"\";\n\tif (offset !== undefined || limit !== undefined) {\n\t\tconst start = offset ?? 1;\n\t\tconst end = limit !== undefined ? Number(start) + Number(limit) - 1 : \"\";\n\t\trange = `:${start}${end ? `-${end}` : \"\"}`;\n\t}\n\treturn path ? `${path}${range}` : \"(unknown)\";\n}\n\n/** Compact boxed call header for summary-style tools (read/write/ls/find/grep). */\nexport function compactCall(\n\ttheme: BoxTheme,\n\ttoolName: string,\n\tdetailLine: string,\n\toptions: { detailKey: string; context: BoxedToolContext },\n): Component {\n\treturn renderCompactBoxedToolCall(theme, toolName, detailLine, {\n\t\twidthKey: boxedToolWidthKey(toolName, options.detailKey),\n\t\tstate: options.context.state,\n\t\tisError: Boolean(options.context.isError),\n\t\tisPartial: Boolean(options.context.isPartial),\n\t\tisPending: pendingFlag(options.context),\n\t\trunning: Boolean(options.context.executionStarted),\n\t});\n}\n\n/** Record wall-clock start when execution begins (first render with executionStarted). */\nexport function noteExecutionStart(context: BoxedToolContext): void {\n\trecordExecutionStarted(context.state, context.executionStarted);\n}\n\n/**\n * Keep running/ended execution state in sync from a call renderer pass. While\n * the tool runs, a 1s re-render ticker keeps live elapsed labels current; once\n * the call renders in its terminal form the elapsed freezes.\n */\nexport function noteBoxedCallState(context: BoxedToolContext): void {\n\tif (!context.executionStarted) return;\n\tif (context.isPartial) startElapsedTicker(context.state, context.invalidate);\n\telse {\n\t\trecordExecutionEnded(context.state);\n\t\tstopElapsedTicker(context.state);\n\t}\n}\n\n/**\n * Record a result renderer pass and keep the ticker/ended state in sync.\n * Returns whether this is the first result pass for the call, so renderers can\n * render nothing while the pending/running call card stands alone.\n */\nexport function noteBoxedResultPhase(context: BoxedToolContext, isPartial: boolean): boolean {\n\tconst firstResultPass = !isResultSeen(context.state);\n\tmarkResultSeen(context.state);\n\tif (isPartial) startElapsedTicker(context.state, context.invalidate);\n\telse {\n\t\trecordExecutionEnded(context.state);\n\t\tstopElapsedTicker(context.state);\n\t}\n\treturn firstResultPass;\n}\n\nexport function stateElapsedMs(context: BoxedToolContext): number | undefined {\n\treturn getStateElapsedMs(context.state);\n}\n\n/** Footer parts with state-based elapsed when result.details lacks timing. */\nexport function boxedFooterWithState(\n\ttheme: BoxTheme,\n\tresult: BoxedToolResult | undefined,\n\tcontext: BoxedToolContext,\n\textraParts: string[] = [],\n): string {\n\treturn formatBoxedFooterFromValues(theme, stateElapsedMs(context), getTextOutput(result), extraParts);\n}\n\nexport function compactFooterWithState(\n\ttheme: BoxTheme,\n\tresult: BoxedToolResult,\n\tcontext: BoxedToolContext,\n\toptions: { isError?: boolean; isPartial?: boolean } = {},\n): Component {\n\tconst elapsedMs = stateElapsedMs(context);\n\treturn renderCompactBoxedFooter(theme, result, {\n\t\tstate: context.state,\n\t\tisError: Boolean(options.isError ?? context.isError),\n\t\tisPartial: Boolean(options.isPartial ?? context.isPartial),\n\t\t...(elapsedMs === undefined ? {} : { elapsedMs }),\n\t});\n}\n\nexport function resultFooterLines(\n\ttheme: BoxTheme,\n\tresult: BoxedToolResult,\n\tcontext: BoxedToolContext,\n\textraParts: string[] = [],\n): string[] {\n\treturn [formatBoxedFooter(theme, result, extraParts, stateElapsedMs(context))];\n}\n\nexport function clearFooterState(context: BoxedToolContext): void {\n\tclearCompactBoxedFooter(context.state);\n}\n\n/** Result-details truncation line count when the native tool truncated output. */\nexport function truncationOutputLines(result: BoxedToolResult | undefined): number | undefined {\n\tif (!result) return undefined;\n\tconst details = result.details as { truncation?: { outputLines?: number } } | undefined;\n\tconst value = details?.truncation?.outputLines;\n\treturn typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\n/** Result-details grep match-limit reached counter. */\nexport function matchLimitReached(result: BoxedToolResult | undefined): number | undefined {\n\tif (!result) return undefined;\n\tconst details = result.details as { matchLimitReached?: number } | undefined;\n\tconst value = details?.matchLimitReached;\n\treturn typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nexport { boxedToolWidthKey, getTextOutput, resolveRelativePath, shortenPath };\n","// Boxed grep/search tool renderer.\n//\n// grep renders a **boxless tree panel**: a summary header\n// (`Grep: <pattern> <N> matches · <M> files · in <path>`) followed by match rows\n// grouped by file (`├─ *line│content`). Like the quiet-tool batch panel, the\n// whole panel lives in the call component and reads a live registry on every\n// render, so the result's match data is picked up without cross-component\n// invalidation. grep does not batch (each call owns its own panel).\n//\n// Lifecycle: panels are keyed by toolCallId and cleared on session reset and new\n// message boundaries (see resetGrepRegistry wiring in session-coordinator.ts and\n// pi/index.ts), mirroring the batch registry.\n\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport { stripAnsi } from \"../../../shared/ansi.js\";\nimport { type BoxTheme, dimLine, getTextOutput, shortenPath } from \"../../../shared/box.js\";\nimport { safeTruncateToWidth } from \"../../../shared/render-budget.js\";\nimport {\n\ttype GrepMatch,\n\tgroupMatchesByFile,\n\tparseGrepOutput,\n\tpluralForm,\n\trenderGrepTree,\n\tSEARCH_ICON,\n\tTREE_INDENT,\n} from \"./output-tree.js\";\nimport { getToolsRenderConfig } from \"./session-config.js\";\nimport { type BoxedToolDefinition, noteExecutionStart } from \"./shared.js\";\n\nconst GREP_HEAD_LIMIT = 6;\nconst GREP_ERROR_LINES = 2;\n\ninterface GrepPanelState {\n\tpattern: string;\n\tpathLabel: string;\n\t/** `undefined` until the result arrives; an empty array means zero matches. */\n\tmatches: GrepMatch[] | undefined;\n\tisError: boolean;\n\terrorText: string | undefined;\n\tisPartial: boolean;\n}\n\nconst grepPanels = new Map<string, GrepPanelState>();\n\n/** Reset all grep panel state (session start/shutdown). */\nexport function resetGrepRegistry(): void {\n\tgrepPanels.clear();\n}\n\nfunction pathLabel(rawPath: string): string {\n\tconst displayPath = String(rawPath ?? \".\");\n\treturn displayPath === \".\" || displayPath === \"\" ? \"current directory\" : shortenPath(displayPath);\n}\n\nfunction registerGrepCall(toolCallId: string, pattern: string, label: string): void {\n\tconst existing = grepPanels.get(toolCallId);\n\tif (existing) {\n\t\texisting.pattern = pattern;\n\t\texisting.pathLabel = label;\n\t\treturn;\n\t}\n\tgrepPanels.set(toolCallId, {\n\t\tpattern,\n\t\tpathLabel: label,\n\t\tmatches: undefined,\n\t\tisError: false,\n\t\terrorText: undefined,\n\t\tisPartial: true,\n\t});\n}\n\nfunction registerGrepResult(\n\ttoolCallId: string,\n\tdata: { matches: GrepMatch[]; isError: boolean; errorText: string | undefined; isPartial: boolean },\n): void {\n\tconst state = grepPanels.get(toolCallId);\n\tif (!state) return;\n\tstate.matches = data.matches;\n\tstate.isError = data.isError;\n\tstate.errorText = data.errorText;\n\tstate.isPartial = data.isPartial;\n}\n\nfunction bold(theme: BoxTheme, text: string): string {\n\treturn typeof theme?.bold === \"function\" ? theme.bold(text) : text;\n}\n\n/** `Grep: <pattern> <N> matches · <M> files · in <path>` (done) /\n * `Grep: <pattern> · in <path>` (pending). */\nfunction formatGrepHeader(theme: BoxTheme, state: GrepPanelState): string {\n\tconst icon = getToolsRenderConfig().nerdFonts ? `${SEARCH_ICON} ` : \"\";\n\tconst label = bold(theme, \"Grep:\");\n\tconst patternPart = state.pattern ? ` ${theme.fg(\"text\", state.pattern)}` : \"\";\n\tconst pathPart = state.pathLabel ? theme.fg(\"dim\", ` · in ${state.pathLabel}`) : \"\";\n\tif (state.isError) {\n\t\treturn `${icon}${theme.fg(\"error\", bold(theme, \"✗ Grep:\"))}${state.pattern ? ` ${theme.fg(\"error\", state.pattern)}` : \"\"}${pathPart}`;\n\t}\n\tif (state.matches === undefined) {\n\t\treturn `${icon}${label}${patternPart}${pathPart}`;\n\t}\n\tconst matchCount = state.matches.length;\n\tconst fileCount = groupMatchesByFile(state.matches).length;\n\tconst matchesPart = theme.fg(\"accent\", `${matchCount} ${pluralForm(\"match\", matchCount)}`);\n\tconst filesPart = theme.fg(\"dim\", ` · ${fileCount} ${pluralForm(\"file\", fileCount)}`);\n\treturn `${icon}${label}${patternPart} ${matchesPart}${filesPart}${pathPart}`;\n}\n\nfunction renderErrorLines(theme: BoxTheme, errorText: string, width: number): string[] {\n\tconst raw = stripAnsi(errorText)\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trim())\n\t\t.filter((line) => line.length > 0);\n\tif (raw.length === 0) return [];\n\tconst prefix = `${TREE_INDENT}${dimLine(\"└─\")} `;\n\tconst out = raw\n\t\t.slice(0, GREP_ERROR_LINES)\n\t\t.map((line) => safeTruncateToWidth(`${prefix}${theme.fg(\"error\", line)}`, Math.max(1, width), \"…\"));\n\tif (raw.length > GREP_ERROR_LINES)\n\t\tout.push(safeTruncateToWidth(`${prefix}${theme.fg(\"error\", \"…\")}`, Math.max(1, width), \"…\"));\n\treturn out;\n}\n\nfunction renderGrepPanelLines(theme: BoxTheme, state: GrepPanelState, width: number): string[] {\n\tconst safeWidth = Math.max(1, width);\n\tconst header = safeTruncateToWidth(formatGrepHeader(theme, state), safeWidth, \"…\");\n\tif (state.isError) {\n\t\treturn [header, ...(state.errorText ? renderErrorLines(theme, state.errorText, width) : [])];\n\t}\n\tif (state.matches === undefined) return [header];\n\treturn renderGrepTree(theme, header, state.matches, safeWidth, {\n\t\theadLimit: GREP_HEAD_LIMIT,\n\t\twithIcons: getToolsRenderConfig().nerdFonts,\n\t});\n}\n\n/** Live panel component reading the registry on every render pass. The state\n * reference is captured at creation (like the batch panel): a registry clear\n * on session reset/resume must not blank already-rendered panels — the result\n * renderer mutates this same object, so live updates still flow. */\nfunction renderGrepPanel(theme: BoxTheme, toolCallId: string): Component {\n\tconst state = grepPanels.get(toolCallId);\n\treturn {\n\t\tinvalidate() {},\n\t\trender(width: number): string[] {\n\t\t\tif (!state) return [safeTruncateToWidth(bold(theme, \"Grep:\"), Math.max(1, width), \"…\")];\n\t\t\treturn renderGrepPanelLines(theme, state, width);\n\t\t},\n\t};\n}\n\n/** Empty result component — the panel lives in the call component, which\n * re-renders when the result arrives (Pi re-renders the tool execution\n * component on tool_execution_end), picking up the stored matches. */\nconst EMPTY_GREP_RESULT: Component = {\n\tinvalidate() {},\n\trender() {\n\t\treturn [];\n\t},\n};\n\nexport const grepTool: BoxedToolDefinition = {\n\tcall(args, theme, context) {\n\t\tnoteExecutionStart(context);\n\t\tconst pattern = String(args?.pattern ?? \"\");\n\t\tregisterGrepCall(context.toolCallId, pattern, pathLabel(String(args?.path ?? \".\")));\n\t\treturn renderGrepPanel(theme, context.toolCallId);\n\t},\n\tresult(result, options, _theme, context) {\n\t\tconst output = stripAnsi(getTextOutput(result)).trimEnd();\n\t\tconst isError = Boolean(context.isError);\n\t\tconst matches = isError ? [] : parseGrepOutput(output);\n\t\tregisterGrepResult(context.toolCallId, {\n\t\t\tmatches,\n\t\t\tisError,\n\t\t\terrorText: isError ? output || undefined : undefined,\n\t\t\tisPartial: Boolean(options.isPartial),\n\t\t});\n\t\treturn EMPTY_GREP_RESULT;\n\t},\n};\n","import type { NormalizedPiStyleConfig } from \"./config-types.js\";\n\nexport interface TierCAuthorizationInput {\n\treadonly certifiedHost: boolean;\n\treadonly coreFlag: boolean;\n\treadonly surfaceFlag: boolean;\n\treadonly surface: \"messages\" | \"tools\" | \"assistantMessage\" | \"specialBlocks\";\n\treadonly config: NormalizedPiStyleConfig;\n}\n\n/** Persisted and ordinary command state is intentionally not an input: authorization is session-bound. */\nexport function isTierCAuthorized(input: TierCAuthorizationInput): boolean {\n\tif (!input.certifiedHost || !input.coreFlag || !input.surfaceFlag || !input.config.enabled) return false;\n\tif (input.surface === \"tools\") return input.config.tools.enabled;\n\tif (input.surface === \"assistantMessage\")\n\t\treturn input.config.messages.enabled && input.config.messages.assistantPrefix;\n\tif (input.surface === \"specialBlocks\") return input.config.messages.enabled && input.config.messages.specialBlocks;\n\treturn input.config.messages.enabled;\n}\n","import { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n\tAssistantMessageComponent,\n\tBashExecutionComponent,\n\tBranchSummaryMessageComponent,\n\tCompactionSummaryMessageComponent,\n\tCustomMessageComponent,\n\tSkillInvocationMessageComponent,\n\tToolExecutionComponent,\n} from \"@earendil-works/pi-coding-agent\";\nimport {\n\tdecorateMessageRender,\n\tdecorateMessageUpdate,\n\ttype MessageDecorationSnapshot,\n} from \"../features/messages/index.js\";\nimport { renderSpecialMessageBlock, type SpecialBlockSubtype } from \"../features/messages/special-blocks.js\";\nimport { renderBashExecutionBox } from \"../features/tools/bash-execution.js\";\nimport { createToolDecorationOwner } from \"../features/tools/index.js\";\nimport {\n\ttype CompatibilityRecord,\n\tcurrentGeneration,\n\tinstallDelegatingPatch,\n\tnextGeneration,\n} from \"./compatibility-registry.js\";\n\nconst PI_VERSION_RANGE = \">=0.83.0 <0.84.0\";\nconst TRUSTED_PI_VERSION = \"0.83.0\";\nconst reportStates = new WeakMap<\n\tobject,\n\t{ records: CompatibilityRecord[]; toolOwner: ReturnType<typeof createToolDecorationOwner> | undefined }\n>();\n// These fingerprints are coupled to the installed 0.83.0 package source. A matching\n// name/arity/hash is evidence of the shipped native method, not a cryptographic proof:\n// code loaded before this module could spoof the same function source. We therefore\n// fail closed on every unrecorded Pi build and never use module-load capture as trust.\nexport const TRUSTED_NATIVE_FINGERPRINTS: Readonly<Record<string, string>> = Object.freeze({\n\t\"native-assistant-message:render\": \"2a39243f\",\n\t\"native-assistant-message:updateContent\": \"4a2f15ff\",\n\t\"native-compaction-message:updateDisplay\": \"f8c44e78\",\n\t\"native-branch-message:updateDisplay\": \"415d57b7\",\n\t\"native-skill-message:updateDisplay\": \"48099ea6\",\n\t\"native-custom-message:rebuild\": \"76ae2e3a\",\n\t\"tool-call-renderer:getCallRenderer\": \"951ea0e0\",\n\t\"tool-result-renderer:getResultRenderer\": \"8a25cd71\",\n\t\"native-bash-execution:render\": \"a5b5abca\",\n});\n\nexport const CERTIFICATION_TABLE = Object.freeze({\n\t\"0.83.0\": Object.freeze({\n\t\t\"native-assistant-message:render\": Object.freeze({\n\t\t\tfeature: \"messages\",\n\t\t\tsubtype: \"native-assistant-message\",\n\t\t\ttarget: AssistantMessageComponent.prototype,\n\t\t\tmethod: \"render\",\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t\tname: \"render\",\n\t\t\tarity: 1,\n\t\t\tfingerprint: TRUSTED_NATIVE_FINGERPRINTS[\"native-assistant-message:render\"],\n\t\t\tadapterId: \"message-prefix-osc133-v1\",\n\t\t\tstatus: \"certified\" as const,\n\t\t}),\n\t\t\"tool-call-renderer:getCallRenderer\": Object.freeze({\n\t\t\tfeature: \"tools\",\n\t\t\tsubtype: \"tool-call-renderer\",\n\t\t\ttarget: ToolExecutionComponent.prototype,\n\t\t\tmethod: \"getCallRenderer\",\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t\tname: \"getCallRenderer\",\n\t\t\tarity: 0,\n\t\t\tfingerprint: TRUSTED_NATIVE_FINGERPRINTS[\"tool-call-renderer:getCallRenderer\"],\n\t\t\tadapterId: \"tool-renderer-component-v1\",\n\t\t\tstatus: \"certified\" as const,\n\t\t}),\n\t\t\"tool-result-renderer:getResultRenderer\": Object.freeze({\n\t\t\tfeature: \"tools\",\n\t\t\tsubtype: \"tool-result-renderer\",\n\t\t\ttarget: ToolExecutionComponent.prototype,\n\t\t\tmethod: \"getResultRenderer\",\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t\tname: \"getResultRenderer\",\n\t\t\tarity: 0,\n\t\t\tfingerprint: TRUSTED_NATIVE_FINGERPRINTS[\"tool-result-renderer:getResultRenderer\"],\n\t\t\tadapterId: \"tool-renderer-component-v1\",\n\t\t\tstatus: \"certified\" as const,\n\t\t}),\n\t\t\"native-assistant-message:updateContent\": Object.freeze({\n\t\t\tfeature: \"messages\",\n\t\t\tsubtype: \"native-assistant-message\",\n\t\t\ttarget: AssistantMessageComponent.prototype,\n\t\t\tmethod: \"updateContent\",\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t\tname: \"updateContent\",\n\t\t\tarity: 1,\n\t\t\tfingerprint: TRUSTED_NATIVE_FINGERPRINTS[\"native-assistant-message:updateContent\"],\n\t\t\tadapterId: \"message-thinking-collapse-v1\",\n\t\t\tstatus: \"certified\" as const,\n\t\t}),\n\t\t\"native-compaction-message:updateDisplay\": Object.freeze({\n\t\t\tfeature: \"messages\",\n\t\t\tsubtype: \"native-compaction-message\",\n\t\t\ttarget: CompactionSummaryMessageComponent.prototype,\n\t\t\tmethod: \"updateDisplay\",\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t\tadapterId: \"message-block-boxed-v1\",\n\t\t\tstatus: \"certified\" as const,\n\t\t}),\n\t\t\"native-branch-message:updateDisplay\": Object.freeze({\n\t\t\tfeature: \"messages\",\n\t\t\tsubtype: \"native-branch-message\",\n\t\t\ttarget: BranchSummaryMessageComponent.prototype,\n\t\t\tmethod: \"updateDisplay\",\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t\tadapterId: \"message-block-boxed-v1\",\n\t\t\tstatus: \"certified\" as const,\n\t\t}),\n\t\t\"native-skill-message:updateDisplay\": Object.freeze({\n\t\t\tfeature: \"messages\",\n\t\t\tsubtype: \"native-skill-message\",\n\t\t\ttarget: SkillInvocationMessageComponent.prototype,\n\t\t\tmethod: \"updateDisplay\",\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t\tadapterId: \"message-block-boxed-v1\",\n\t\t\tstatus: \"certified\" as const,\n\t\t}),\n\t\t\"native-custom-message:rebuild\": Object.freeze({\n\t\t\tfeature: \"messages\",\n\t\t\tsubtype: \"native-custom-message\",\n\t\t\ttarget: CustomMessageComponent.prototype,\n\t\t\tmethod: \"rebuild\",\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t\tadapterId: \"message-block-boxed-v1\",\n\t\t\tstatus: \"certified\" as const,\n\t\t}),\n\t\t\"native-bash-execution:render\": Object.freeze({\n\t\t\tfeature: \"tools\",\n\t\t\tsubtype: \"native-bash-execution\",\n\t\t\ttarget: BashExecutionComponent.prototype,\n\t\t\tmethod: \"render\",\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t\t// The additive render patch is certified by the class constructor identity\n\t\t\t// (name/arity/source fingerprint): the class defines no own `render`, so\n\t\t\t// the installed own method is the only one and the inherited Container\n\t\t\t// render is the native fallback.\n\t\t\tname: \"BashExecutionComponent\",\n\t\t\tarity: 2,\n\t\t\tfingerprint: TRUSTED_NATIVE_FINGERPRINTS[\"native-bash-execution:render\"],\n\t\t\tadapterId: \"bash-execution-box-v1\",\n\t\t\tstatus: \"certified\" as const,\n\t\t}),\n\t}),\n});\n\nexport interface CompatibilityDescriptorSnapshot {\n\treadonly kind: \"data\" | \"accessor\";\n\treadonly value?: unknown;\n\treadonly get?: unknown;\n\treadonly set?: unknown;\n\treadonly writable?: boolean;\n\treadonly enumerable: boolean;\n\treadonly configurable: boolean;\n}\n\nexport interface CompatibilityRecordSnapshot {\n\treadonly feature: CompatibilityRecord[\"feature\"];\n\treadonly subtype: CompatibilityRecord[\"subtype\"];\n\treadonly method: PropertyKey;\n\treadonly shape: string;\n\treadonly piVersion: string;\n\treadonly versionRange: string;\n\treadonly generation: number;\n\treadonly disposed: boolean;\n\treadonly diagnostic: string | undefined;\n}\n\nexport interface CompatibilityProbeReport {\n\tattemptedVersion: string;\n\tmatchedCertifiedVersion: string | undefined;\n\tcertificationTable: typeof CERTIFICATION_TABLE;\n\tpiVersion: string;\n\tversionRange: string;\n\tgeneration: number;\n\trecordSnapshots: readonly CompatibilityRecordSnapshot[];\n\tunsupported: ReadonlyArray<{ subtype: string; method: PropertyKey; reason: string }>;\n\tdelegationMarkers: readonly string[];\n\tcertification: readonly {\n\t\treadonly version: string;\n\t\treadonly attemptedVersion: string;\n\t\treadonly matchedCertifiedVersion: string | undefined;\n\t\treadonly expected: unknown;\n\t\treadonly actualPreinstall: CompatibilityDescriptorSnapshot | undefined;\n\t\treadonly feature: CompatibilityRecord[\"feature\"];\n\t\treadonly subtype: CompatibilityRecord[\"subtype\"];\n\t\treadonly target: object;\n\t\treadonly method: string;\n\t\treadonly descriptor: CompatibilityDescriptorSnapshot | undefined;\n\t\treadonly name: string | undefined;\n\t\treadonly arity: number | undefined;\n\t\treadonly fingerprint: string | undefined;\n\t\treadonly adapterId: string | undefined;\n\t\treadonly status: \"certified\" | \"native-fallback\";\n\t\treadonly fallbackReason?: string;\n\t}[];\n\tgetRuntimeDiagnostics: () => ReadonlyMap<string, number>;\n\tgetFinalDiagnostics: () => Readonly<import(\"../features/tools/index.js\").ToolDiagnosticArchive> | undefined;\n\tgetActiveToolRecordCount: () => number;\n\tdisposeOwner: () => void;\n}\n\nexport interface TargetSpec {\n\tfeature: CompatibilityRecord[\"feature\"];\n\tsubtype: CompatibilityRecord[\"subtype\"];\n\ttarget: object;\n\tmethod: string;\n\tadapterId: string | undefined;\n\tstatus: \"certified\" | \"native-fallback\";\n\tfallbackReason?: string;\n\t/** \"add-method\" installs a new own method; the class constructor fingerprint certifies the target. */\n\tkind?: \"method\" | \"add-method\";\n\t/** Function name to verify (defaults to `method`; additive patches verify the class constructor name). */\n\tidentityName?: string;\n\t/** Expected arity (defaults to the standard per-method rule; additive patches verify the constructor arity). */\n\tarity?: number;\n}\n\nexport function fingerprint(value: unknown): string | undefined {\n\tif (typeof value !== \"function\") return undefined;\n\tlet hash = 2166136261;\n\tfor (const character of Function.prototype.toString.call(value)) {\n\t\thash ^= character.charCodeAt(0);\n\t\thash = Math.imul(hash, 16777619) >>> 0;\n\t}\n\treturn hash.toString(16).padStart(8, \"0\");\n}\n\nfunction trustedNativeIdentity(spec: TargetSpec, piVersion: string | undefined): unknown {\n\tif (piVersion !== TRUSTED_PI_VERSION) return undefined;\n\tif (spec.kind === \"add-method\") {\n\t\t// Additive install: the prototype must not already own the method (it is\n\t\t// inherited), the class constructor identity must match the recorded build,\n\t\t// and the inherited method becomes the native fallback for the delegate.\n\t\tif (Object.getOwnPropertyDescriptor(spec.target, spec.method)) return undefined;\n\t\tconst ctor = Object.getOwnPropertyDescriptor(spec.target, \"constructor\")?.value;\n\t\tconst key = `${spec.subtype}:${spec.method}`;\n\t\tif (\n\t\t\ttypeof ctor !== \"function\" ||\n\t\t\tctor.name !== (spec.identityName ?? spec.method) ||\n\t\t\tctor.length !== (spec.arity ?? 0) ||\n\t\t\tfingerprint(ctor) !== TRUSTED_NATIVE_FINGERPRINTS[key]\n\t\t)\n\t\t\treturn undefined;\n\t\tconst inherited = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(spec.target), spec.method)?.value;\n\t\treturn typeof inherited === \"function\" ? inherited : undefined;\n\t}\n\tconst descriptor = Object.getOwnPropertyDescriptor(spec.target, spec.method);\n\tconst value = descriptor?.value;\n\tconst key = `${spec.subtype}:${spec.method}`;\n\tconst expectedArity = spec.arity ?? (spec.method === \"render\" || spec.method === \"updateContent\" ? 1 : 0);\n\tif (\n\t\tdescriptor?.writable !== true ||\n\t\tdescriptor.configurable !== true ||\n\t\ttypeof value !== \"function\" ||\n\t\tvalue.name !== (spec.identityName ?? spec.method) ||\n\t\tvalue.length !== expectedArity ||\n\t\tfingerprint(value) !== TRUSTED_NATIVE_FINGERPRINTS[key]\n\t)\n\t\treturn undefined;\n\treturn value;\n}\n\nexport const targetSpecs: readonly TargetSpec[] = [\n\t{\n\t\tfeature: \"messages\",\n\t\tsubtype: \"native-assistant-message\",\n\t\ttarget: AssistantMessageComponent.prototype,\n\t\tmethod: \"render\",\n\t\tadapterId: \"message-prefix-osc133-v1\",\n\t\tstatus: \"certified\",\n\t},\n\t{\n\t\tfeature: \"messages\",\n\t\tsubtype: \"native-assistant-message\",\n\t\ttarget: AssistantMessageComponent.prototype,\n\t\tmethod: \"updateContent\",\n\t\tadapterId: \"message-thinking-collapse-v1\",\n\t\tstatus: \"certified\",\n\t},\n\t{\n\t\tfeature: \"messages\",\n\t\tsubtype: \"native-compaction-message\",\n\t\ttarget: CompactionSummaryMessageComponent.prototype,\n\t\tmethod: \"updateDisplay\",\n\t\tadapterId: \"message-block-boxed-v1\",\n\t\tstatus: \"certified\",\n\t},\n\t{\n\t\tfeature: \"messages\",\n\t\tsubtype: \"native-branch-message\",\n\t\ttarget: BranchSummaryMessageComponent.prototype,\n\t\tmethod: \"updateDisplay\",\n\t\tadapterId: \"message-block-boxed-v1\",\n\t\tstatus: \"certified\",\n\t},\n\t{\n\t\tfeature: \"messages\",\n\t\tsubtype: \"native-skill-message\",\n\t\ttarget: SkillInvocationMessageComponent.prototype,\n\t\tmethod: \"updateDisplay\",\n\t\tadapterId: \"message-block-boxed-v1\",\n\t\tstatus: \"certified\",\n\t},\n\t{\n\t\tfeature: \"messages\",\n\t\tsubtype: \"native-custom-message\",\n\t\ttarget: CustomMessageComponent.prototype,\n\t\tmethod: \"rebuild\",\n\t\tadapterId: \"message-block-boxed-v1\",\n\t\tstatus: \"certified\",\n\t},\n\t{\n\t\tfeature: \"tools\",\n\t\tsubtype: \"tool-call-renderer\",\n\t\ttarget: ToolExecutionComponent.prototype,\n\t\tmethod: \"getCallRenderer\",\n\t\tadapterId: \"tool-renderer-component-v1\",\n\t\tstatus: \"certified\",\n\t},\n\t{\n\t\tfeature: \"tools\",\n\t\tsubtype: \"tool-result-renderer\",\n\t\ttarget: ToolExecutionComponent.prototype,\n\t\tmethod: \"getResultRenderer\",\n\t\tadapterId: \"tool-renderer-component-v1\",\n\t\tstatus: \"certified\",\n\t},\n\t{\n\t\tfeature: \"tools\",\n\t\tsubtype: \"native-bash-execution\",\n\t\ttarget: BashExecutionComponent.prototype,\n\t\tmethod: \"render\",\n\t\tkind: \"add-method\",\n\t\tidentityName: \"BashExecutionComponent\",\n\t\tarity: 2,\n\t\tadapterId: \"bash-execution-box-v1\",\n\t\tstatus: \"certified\",\n\t},\n];\n\nexport interface PiVersionResolution {\n\tresolvePackageEntry?: (packageName: string) => string;\n\treadFile?: (path: string) => string;\n}\n\nexport function detectPiVersion(resolution: PiVersionResolution = {}): {\n\tversion: string | undefined;\n\tdiagnostic?: string;\n} {\n\tconst resolvePackageEntry =\n\t\tresolution.resolvePackageEntry ??\n\t\t((name: string) => {\n\t\t\ttry {\n\t\t\t\treturn fileURLToPath(new URL(import.meta.resolve(name)));\n\t\t\t} catch (error) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`public package entry resolution failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\tconst readFile = resolution.readFile ?? ((path: string) => readFileSync(path, \"utf8\"));\n\ttry {\n\t\tconst entry = resolvePackageEntry(\"@earendil-works/pi-coding-agent\");\n\t\tlet directory = dirname(entry);\n\t\tfor (;;) {\n\t\t\tconst packagePath = join(directory, \"package.json\");\n\t\t\ttry {\n\t\t\t\tconst packageJson = JSON.parse(readFile(packagePath)) as { name?: string; version?: string };\n\t\t\t\tif (packageJson.name === \"@earendil-works/pi-coding-agent\" && typeof packageJson.version === \"string\")\n\t\t\t\t\treturn { version: packageJson.version };\n\t\t\t} catch {\n\t\t\t\t// Walk upward only; package exports may place the entry below the package root.\n\t\t\t}\n\t\t\tconst parent = dirname(directory);\n\t\t\tif (parent === directory) break;\n\t\t\tdirectory = parent;\n\t\t}\n\t\treturn { version: undefined, diagnostic: \"Pi package version was not found\" };\n\t} catch (error) {\n\t\treturn {\n\t\t\tversion: undefined,\n\t\t\tdiagnostic: `Pi package version detection failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t};\n\t}\n}\n\nfunction descriptorSnapshot(descriptor: PropertyDescriptor | undefined): CompatibilityDescriptorSnapshot | undefined {\n\tif (!descriptor) return undefined;\n\treturn Object.freeze(\n\t\t\"value\" in descriptor\n\t\t\t? {\n\t\t\t\t\tkind: \"data\",\n\t\t\t\t\tvalue: descriptor.value,\n\t\t\t\t\twritable: descriptor.writable === true,\n\t\t\t\t\tenumerable: descriptor.enumerable === true,\n\t\t\t\t\tconfigurable: descriptor.configurable === true,\n\t\t\t\t}\n\t\t\t: {\n\t\t\t\t\tkind: \"accessor\",\n\t\t\t\t\tget: descriptor.get,\n\t\t\t\t\tset: descriptor.set,\n\t\t\t\t\tenumerable: descriptor.enumerable === true,\n\t\t\t\t\tconfigurable: descriptor.configurable === true,\n\t\t\t\t},\n\t);\n}\n\nfunction certificationRecord(\n\tspec: TargetSpec,\n\tattemptedVersion: string | undefined,\n\tevidence = Object.getOwnPropertyDescriptor(spec.target, spec.method),\n) {\n\tconst descriptor = evidence;\n\tconst value = descriptor?.value;\n\treturn {\n\t\tversion: attemptedVersion ?? \"unknown\",\n\t\tattemptedVersion: attemptedVersion ?? \"unknown\",\n\t\tmatchedCertifiedVersion: attemptedVersion === TRUSTED_PI_VERSION ? TRUSTED_PI_VERSION : undefined,\n\t\texpected: undefined,\n\t\tactualPreinstall: descriptorSnapshot(descriptor),\n\t\tfeature: spec.feature,\n\t\tsubtype: spec.subtype,\n\t\ttarget: spec.target,\n\t\tmethod: spec.method,\n\t\tdescriptor: descriptorSnapshot(descriptor),\n\t\tname: typeof value === \"function\" ? value.name : undefined,\n\t\tarity: typeof value === \"function\" ? value.length : undefined,\n\t\tfingerprint: fingerprint(value),\n\t\tadapterId: spec.adapterId,\n\t\tstatus: spec.status,\n\t\t...(spec.fallbackReason ? { fallbackReason: spec.fallbackReason } : {}),\n\t};\n}\n\nfunction versionInRange(version: string | undefined): boolean {\n\treturn version === TRUSTED_PI_VERSION;\n}\n\nfunction shape(spec: TargetSpec): boolean {\n\tconst descriptor = Object.getOwnPropertyDescriptor(spec.target, spec.method);\n\t// Additive installs need an unowned slot (the method is inherited); every\n\t// other patch requires the native own writable/configurable method.\n\tif (spec.kind === \"add-method\") return descriptor === undefined;\n\treturn typeof descriptor?.value === \"function\" && descriptor.writable === true && descriptor.configurable === true;\n}\n\nexport interface CompatibilityProbeOptions {\n\tmarkers?: Set<string>;\n\tconfig?: Readonly<{\n\t\tmessages: { enabled: boolean; assistantPrefix: boolean; specialBlocks: boolean; hideThinkingLabel: boolean };\n\t\ttools: { enabled: boolean; style: string; maxCollapsedLines: number; maxExpandedLines: number; dimOutput: boolean };\n\t\tpreset: string;\n\t}>;\n\ttoolSnapshot?: Readonly<{ callMarker?: string; resultMarker?: string; style?: \"marker\" | \"compact-box\" }>;\n\tmessageSnapshot?: MessageDecorationSnapshot;\n}\n\nfunction isSpecialBlock(spec: TargetSpec): boolean {\n\treturn spec.feature === \"messages\" && spec.status === \"certified\" && spec.adapterId === \"message-block-boxed-v1\";\n}\n\nfunction createFallbackRecord(\n\tspec: TargetSpec,\n\tpiVersion: string | undefined,\n\tgeneration: number,\n\treason: string,\n): CompatibilityRecord {\n\treturn {\n\t\tfeature: spec.feature,\n\t\tsubtype: spec.subtype,\n\t\ttarget: spec.target,\n\t\towner: spec.target,\n\t\tmethod: spec.method,\n\t\toriginalIdentity: Reflect.get(spec.target, spec.method),\n\t\tpiVersion: piVersion ?? \"unknown\",\n\t\tversionRange: PI_VERSION_RANGE,\n\t\tshape: \"unsupported\",\n\t\tdiagnostic: reason,\n\t\tgeneration,\n\t\tdisposed: true,\n\t\tdisposer: () => {},\n\t};\n}\n\nfunction probeDiagnostic(spec: TargetSpec, piVersion: string | undefined, identity: unknown): string {\n\tif (!versionInRange(piVersion)) return \"Pi version is unknown or outside the recorded 0.83.0 support build\";\n\tif (!shape(spec)) return \"target method shape is not an own writable/configurable function\";\n\tif (identity === undefined) return \"recorded 0.83.0 native fingerprint, name, or arity did not match\";\n\treturn \"exact native identity verified; certified guarded decoration enabled\";\n}\n\nfunction surfaceDisabled(spec: TargetSpec, config: CompatibilityProbeOptions[\"config\"]): boolean {\n\tif (!config) return false;\n\tif (spec.feature === \"tools\") return !config.tools.enabled;\n\tif (!config.messages.enabled) return true;\n\tif (spec.subtype === \"native-assistant-message\" && spec.method === \"render\") return !config.messages.assistantPrefix;\n\tif (spec.subtype === \"native-assistant-message\" && spec.method === \"updateContent\")\n\t\treturn !config.messages.hideThinkingLabel;\n\tif (isSpecialBlock(spec)) return !config.messages.specialBlocks;\n\treturn true;\n}\n\nfunction probeSpec(options: {\n\tspec: TargetSpec;\n\tpiVersion: string | undefined;\n\tgeneration: number;\n\tmarkers: Set<string>;\n\tconfig?: CompatibilityProbeOptions[\"config\"];\n\tmessageSnapshot: MessageDecorationSnapshot | undefined;\n\ttoolOwner: ReturnType<typeof createToolDecorationOwner> | undefined;\n}) {\n\tconst { spec, piVersion, generation, markers, config, toolOwner, messageSnapshot } = options;\n\tconst identity = trustedNativeIdentity(spec, piVersion);\n\tconst diagnostic = probeDiagnostic(spec, piVersion, identity);\n\tconst disabled = surfaceDisabled(spec, config);\n\tif (disabled) {\n\t\tconst reason = \"native fallback: surface disabled by normalized configuration\";\n\t\treturn { record: createFallbackRecord(spec, piVersion, generation, reason), reason, fallback: true };\n\t}\n\tconst result = installDelegatingPatch({\n\t\tfeature: spec.feature,\n\t\tsubtype: spec.subtype,\n\t\ttarget: spec.target,\n\t\tmethod: spec.method,\n\t\tpiVersion: piVersion ?? \"unknown\",\n\t\tversionRange: PI_VERSION_RANGE,\n\t\tshape: identity !== undefined && versionInRange(piVersion) && shape(spec),\n\t\tgeneration,\n\t\texpectedIdentity: identity,\n\t\thasExpectedIdentity: true,\n\t\tdiagnostic,\n\t\t...(spec.kind ? { kind: spec.kind } : {}),\n\t\tdelegate: (original, target, args) => {\n\t\t\tmarkers.add(`${spec.subtype}:delegated`);\n\t\t\tif (spec.subtype === \"native-bash-execution\")\n\t\t\t\treturn (\n\t\t\t\t\trenderBashExecutionBox(target, args) ??\n\t\t\t\t\tReflect.apply(original as (...values: unknown[]) => unknown, target, args)\n\t\t\t\t);\n\t\t\tif (spec.feature === \"tools\")\n\t\t\t\treturn (\n\t\t\t\t\ttoolOwner?.decorateToolRendererSelection(\n\t\t\t\t\t\tspec.subtype as \"tool-call-renderer\" | \"tool-result-renderer\",\n\t\t\t\t\t\toriginal,\n\t\t\t\t\t\ttarget,\n\t\t\t\t\t\targs,\n\t\t\t\t\t) ?? Reflect.apply(original as (...values: unknown[]) => unknown, target, args)\n\t\t\t\t);\n\t\t\tif (spec.subtype === \"native-assistant-message\") {\n\t\t\t\tif (spec.method === \"updateContent\") return decorateMessageUpdate(original, target, args, messageSnapshot);\n\t\t\t\treturn decorateMessageRender(original, target, args, messageSnapshot);\n\t\t\t}\n\t\t\treturn renderSpecialMessageBlock(spec.subtype as SpecialBlockSubtype, original, target, args);\n\t\t},\n\t});\n\treturn {\n\t\trecord: result.record,\n\t\treason: result.reason ?? result.record.diagnostic ?? \"skipped\",\n\t\tfallback: result.status === \"skipped\",\n\t};\n}\n\nexport function probePiCompatibility(\n\tpiVersion: string | undefined,\n\toptions: Set<string> | CompatibilityProbeOptions = new Set(),\n): CompatibilityProbeReport {\n\tconst markers = options instanceof Set ? options : (options.markers ?? new Set<string>());\n\tconst generation = nextGeneration();\n\tconst toolSpecs = targetSpecs.filter((spec) => spec.feature === \"tools\");\n\tlet toolOwner: ReturnType<typeof createToolDecorationOwner> | undefined;\n\tif (\n\t\ttoolSpecs.some((spec) => trustedNativeIdentity(spec, piVersion) !== undefined) &&\n\t\t(options instanceof Set || options.config?.tools.enabled !== false)\n\t) {\n\t\ttoolOwner = createToolDecorationOwner(options instanceof Set ? {} : options.toolSnapshot);\n\t}\n\tconst evidence = Object.freeze(\n\t\ttargetSpecs.map((spec) =>\n\t\t\tObject.freeze({\n\t\t\t\tsubtype: spec.subtype,\n\t\t\t\tmethod: spec.method,\n\t\t\t\ttarget: spec.target,\n\t\t\t\tdescriptor: Object.getOwnPropertyDescriptor(spec.target, spec.method),\n\t\t\t\tvalue: Object.getOwnPropertyDescriptor(spec.target, spec.method)?.value,\n\t\t\t}),\n\t\t),\n\t);\n\tconst evidenceByKey = new Map(evidence.map((item) => [`${item.subtype}:${String(item.method)}`, item]));\n\tconst records: CompatibilityRecord[] = [];\n\tconst unsupported: Array<{ subtype: string; method: PropertyKey; reason: string }> = [];\n\tconst certification: NonNullable<CompatibilityProbeReport[\"certification\"]>[number][] = [];\n\tfor (const spec of targetSpecs) {\n\t\tconst captured = evidenceByKey.get(`${spec.subtype}:${String(spec.method)}`);\n\t\tconst preinstallDescriptor = captured?.descriptor;\n\t\tconst result = probeSpec({\n\t\t\tmessageSnapshot: options instanceof Set ? undefined : options.messageSnapshot,\n\t\t\tspec,\n\t\t\tpiVersion,\n\t\t\tgeneration,\n\t\t\tmarkers,\n\t\t\tconfig: options instanceof Set ? undefined : options.config,\n\t\t\ttoolOwner,\n\t\t});\n\t\trecords.push(result.record);\n\t\tconst certificate = certificationRecord(spec, piVersion, preinstallDescriptor);\n\t\tcertification.push({\n\t\t\t...certificate,\n\t\t\tattemptedVersion: piVersion ?? \"unknown\",\n\t\t\tmatchedCertifiedVersion: piVersion === TRUSTED_PI_VERSION ? TRUSTED_PI_VERSION : undefined,\n\t\t\texpected:\n\t\t\t\tCERTIFICATION_TABLE[TRUSTED_PI_VERSION][\n\t\t\t\t\t`${spec.subtype}:${spec.method}` as keyof (typeof CERTIFICATION_TABLE)[\"0.83.0\"]\n\t\t\t\t],\n\t\t\tactualPreinstall: descriptorSnapshot(preinstallDescriptor),\n\t\t\tstatus: result.fallback ? \"native-fallback\" : \"certified\",\n\t\t\t...(result.fallback ? { fallbackReason: result.reason } : {}),\n\t\t});\n\t\tif (result.fallback) unsupported.push({ subtype: spec.subtype, method: spec.method, reason: result.reason });\n\t}\n\tconst report: CompatibilityProbeReport = {\n\t\tattemptedVersion: piVersion ?? \"unknown\",\n\t\tmatchedCertifiedVersion: piVersion === TRUSTED_PI_VERSION ? TRUSTED_PI_VERSION : undefined,\n\t\tcertificationTable: CERTIFICATION_TABLE,\n\t\tpiVersion: piVersion ?? \"unknown\",\n\t\tversionRange: PI_VERSION_RANGE,\n\t\tgeneration: currentGeneration(),\n\t\trecordSnapshots: Object.freeze(\n\t\t\trecords.map((record) =>\n\t\t\t\tObject.freeze({\n\t\t\t\t\tfeature: record.feature,\n\t\t\t\t\tsubtype: record.subtype,\n\t\t\t\t\tmethod: record.method,\n\t\t\t\t\tshape: record.shape,\n\t\t\t\t\tpiVersion: record.piVersion,\n\t\t\t\t\tversionRange: record.versionRange,\n\t\t\t\t\tgeneration: record.generation,\n\t\t\t\t\tdisposed: record.disposed,\n\t\t\t\t\tdiagnostic: record.diagnostic,\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\t\tunsupported: Object.freeze(unsupported.map((item) => Object.freeze({ ...item }))),\n\t\tdelegationMarkers: Object.freeze([...markers]),\n\t\tcertification: Object.freeze(\n\t\t\tcertification.map((item) =>\n\t\t\t\tObject.freeze({\n\t\t\t\t\t...item,\n\t\t\t\t\tactualPreinstall: item.actualPreinstall,\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\t\tgetRuntimeDiagnostics: () => toolOwner?.getDiagnostics() ?? new Map(),\n\t\tgetFinalDiagnostics: () => toolOwner?.getFinalArchive(),\n\t\tgetActiveToolRecordCount: () => toolOwner?.getActiveRecordCount() ?? 0,\n\t\tdisposeOwner: () => {\n\t\t\ttoolOwner?.dispose();\n\t\t},\n\t};\n\tObject.freeze(report);\n\treportStates.set(report, { records, toolOwner });\n\treturn report;\n}\n\nexport type CompatibilityCleanupResult = Readonly<{\n\tcomplete: boolean;\n\tretryablePrototypeRecords: number;\n\tretryableToolRecords: number;\n\tfinalDiagnostics?: Readonly<import(\"../features/tools/index.js\").ToolDiagnosticArchive>;\n}>;\n\nexport function disposePiCompatibilityProbe(report: CompatibilityProbeReport): CompatibilityCleanupResult {\n\tconst state = reportStates.get(report);\n\tif (!state) return { complete: true, retryablePrototypeRecords: 0, retryableToolRecords: 0 };\n\tfor (const record of state.records) record.disposer();\n\treport.disposeOwner();\n\tconst retryablePrototypeRecords = state.records.filter((record) => !record.disposed).length;\n\tconst finalDiagnostics = report.getFinalDiagnostics();\n\tconst retryableToolRecords = report.getActiveToolRecordCount();\n\tconst toolOwnerWasCreated = report.recordSnapshots.some(\n\t\t(record) => record.feature === \"tools\" && record.shape === \"installed\",\n\t);\n\treturn {\n\t\tcomplete:\n\t\t\tretryablePrototypeRecords === 0 &&\n\t\t\tretryableToolRecords === 0 &&\n\t\t\t(!toolOwnerWasCreated || finalDiagnostics !== undefined),\n\t\tretryablePrototypeRecords,\n\t\tretryableToolRecords,\n\t\t...(finalDiagnostics ? { finalDiagnostics } : {}),\n\t};\n}\n","import { visibleWidth } from \"@earendil-works/pi-tui\";\n\nconst OSC133_ZONE_START = \"\\x1b]133;A\\x07\";\nconst OSC133_ZONE_END = \"\\x1b]133;B\\x07\";\nconst OSC133_ZONE_FINAL = \"\\x1b]133;C\\x07\";\ntype OscParts = { start: string; body: string; end: string };\n\nfunction extractOscEnvelope(line: string): OscParts | undefined {\n\tif (!line.startsWith(OSC133_ZONE_START)) return undefined;\n\tconst bodyEnd = line.indexOf(OSC133_ZONE_END, OSC133_ZONE_START.length);\n\tif (bodyEnd < 0 || !line.endsWith(OSC133_ZONE_FINAL)) return undefined;\n\treturn { start: OSC133_ZONE_START, body: line.slice(OSC133_ZONE_START.length, bodyEnd), end: line.slice(bodyEnd) };\n}\n\nconst BG_RESET = \"\\x1b[49m\";\n\n/** Leading zero-width OSC sequences (e.g. OSC133 markers) of a line. */\nfunction splitLeadingMarkers(line: string): { head: string; rest: string } {\n\tlet index = 0;\n\twhile (line.startsWith(\"\\x1b]\", index)) {\n\t\tconst bel = line.indexOf(\"\\x07\", index + 2);\n\t\tconst st = line.indexOf(\"\\x1b\\\\\", index + 2);\n\t\tconst end = bel === -1 ? st : st === -1 ? bel : Math.min(bel, st);\n\t\tif (end === -1) break;\n\t\tindex = end + 1;\n\t}\n\treturn { head: line.slice(0, index), rest: line.slice(index) };\n}\n\n/** Leading SGR escape sequence of a line (\"\" when none). */\nfunction leadingSgr(line: string): string {\n\tif (!line.startsWith(\"\\x1b[\")) return \"\";\n\tlet index = 2;\n\twhile (index < line.length) {\n\t\tconst code = line.charCodeAt(index);\n\t\tif (code >= 64 && code <= 126) return line.slice(0, index + 1);\n\t\tindex++;\n\t}\n\treturn \"\";\n}\n\n/** Whether an SGR sequence sets/resets the terminal background color. */\nfunction isBackgroundSgr(sequence: string): boolean {\n\tif (!sequence.startsWith(\"\\x1b[\") || !sequence.endsWith(\"m\")) return false;\n\tfor (const code of sequence.slice(2, -1).split(\";\")) {\n\t\tconst value = Number(code);\n\t\tif (value === 48 || value === 49) return true;\n\t\tif (value >= 40 && value <= 47) return true;\n\t\tif (value >= 100 && value <= 107) return true;\n\t}\n\treturn false;\n}\n\n/**\n * Rebuild a native line so `lead` (prompt prefix / continuation indent) and the\n * full target width are covered by the line's background.\n *\n * Native Box lines (user messages) are `bgAnsi + body + \\x1b[49m`; prepending the\n * prefix outside that wrap shifted the input row's background right by the\n * prefix width while keeping the full container width, producing a staircase\n * box (indented left, overflowing right). Rebuilding inside the wrap keeps the\n * background flush across every row; plain (unwrapped) lines are padded to the\n * target width instead so left/right edges stay aligned.\n */\nfunction rebuildAtWidth(line: string, width: number, lead: string): string {\n\tconst { head, rest } = splitLeadingMarkers(line);\n\tconst bgAnsi = leadingSgr(rest);\n\tif (bgAnsi && isBackgroundSgr(bgAnsi) && rest.endsWith(BG_RESET)) {\n\t\tconst body = rest.slice(bgAnsi.length, rest.length - BG_RESET.length);\n\t\tconst pad = \" \".repeat(Math.max(0, width - visibleWidth(lead) - visibleWidth(body)));\n\t\treturn `${head}${bgAnsi}${lead}${body}${pad}${BG_RESET}`;\n\t}\n\tconst padded = `${lead}${line}`;\n\treturn `${padded}${\" \".repeat(Math.max(0, width - visibleWidth(padded)))}`;\n}\n\nfunction decorateMessageLine(\n\tline: string,\n\tindex: number,\n\tlastIndex: number,\n\tcontentIndex: number,\n\twidth: number,\n\toptions: {\n\t\tfirstEnvelope: OscParts | undefined;\n\t\tfirstHasStart: boolean;\n\t\tmultilineEnvelope: boolean;\n\t\tprefix: string;\n\t},\n): string {\n\tconst { firstEnvelope, firstHasStart, multilineEnvelope, prefix } = options;\n\tconst prefixWidth = visibleWidth(prefix);\n\tconst lead = index === contentIndex ? prefix : index > contentIndex ? \" \".repeat(prefixWidth) : \"\";\n\tif (index === contentIndex && firstEnvelope)\n\t\treturn `${firstEnvelope.start}${rebuildAtWidth(firstEnvelope.body, width, prefix)}${firstEnvelope.end}`;\n\tif (index === contentIndex && firstHasStart)\n\t\treturn `${OSC133_ZONE_START}${rebuildAtWidth(line.slice(OSC133_ZONE_START.length), width, prefix)}`;\n\tif (index === lastIndex && multilineEnvelope && index !== contentIndex)\n\t\treturn `${OSC133_ZONE_END}${OSC133_ZONE_FINAL}${rebuildAtWidth(\n\t\t\tline.slice((OSC133_ZONE_END + OSC133_ZONE_FINAL).length),\n\t\t\twidth,\n\t\t\tlead,\n\t\t)}`;\n\tif (\n\t\tindex === contentIndex &&\n\t\tindex === lastIndex &&\n\t\tmultilineEnvelope &&\n\t\tline.startsWith(OSC133_ZONE_END + OSC133_ZONE_FINAL)\n\t)\n\t\treturn `${OSC133_ZONE_END}${OSC133_ZONE_FINAL}${rebuildAtWidth(\n\t\t\tline.slice((OSC133_ZONE_END + OSC133_ZONE_FINAL).length),\n\t\t\twidth,\n\t\t\tprefix,\n\t\t)}`;\n\treturn rebuildAtWidth(line, width, lead);\n}\n\nfunction contentText(line: string): string {\n\tlet output = \"\";\n\tfor (let index = 0; index < line.length; index++) {\n\t\tif (line.charCodeAt(index) !== 27) {\n\t\t\toutput += line[index];\n\t\t\tcontinue;\n\t\t}\n\t\tconst next = line[index + 1];\n\t\tif (next === \"]\") {\n\t\t\tindex += 2;\n\t\t\twhile (index < line.length && line.charCodeAt(index) !== 7) index++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (next === \"[\") {\n\t\t\tindex += 2;\n\t\t\twhile (index < line.length && (line.charCodeAt(index) < 64 || line.charCodeAt(index) > 126)) index++;\n\t\t}\n\t}\n\treturn output.replaceAll(OSC133_ZONE_START, \"\").replaceAll(OSC133_ZONE_END, \"\").replaceAll(OSC133_ZONE_FINAL, \"\");\n}\n\nfunction hasContent(line: string): boolean {\n\treturn [...contentText(line)].some((character) => !/\\s/u.test(character));\n}\n\nfunction prefixNative(lines: unknown, width: number, prefix: string): string[] | undefined {\n\tif (!Array.isArray(lines) || lines.length === 0 || !lines.every((line) => typeof line === \"string\")) return undefined;\n\tconst nativeLines = lines as string[];\n\tconst prefixWidth = visibleWidth(prefix);\n\tif (width <= prefixWidth) return undefined;\n\tconst bodyWidth = width - prefixWidth;\n\tconst first = nativeLines[0] ?? \"\";\n\tconst last = nativeLines.at(-1) ?? \"\";\n\tconst multilineEnvelope = nativeLines.length > 1 && last.startsWith(OSC133_ZONE_END + OSC133_ZONE_FINAL);\n\t// The last line is a content-start candidate only when the envelope is\n\t// single-line, or when no earlier line carries content. Assistant messages\n\t// with a single content line render as a multiline envelope whose only body\n\t// sits on the final line ([OSC133_A, OSC133_END+FINAL+body]); excluding it\n\t// would drop the prefix for every short assistant reply.\n\tconst firstContentIndex = nativeLines.findIndex((line, index) => {\n\t\tif (index !== nativeLines.length - 1 || !multilineEnvelope) return hasContent(line);\n\t\treturn !nativeLines.slice(0, index).some((earlier) => hasContent(earlier)) && hasContent(line);\n\t});\n\tif (firstContentIndex < 0) return nativeLines;\n\tconst firstEnvelope = firstContentIndex === 0 ? extractOscEnvelope(first) : undefined;\n\tconst firstHasStart = firstContentIndex === 0 && first.startsWith(OSC133_ZONE_START);\n\tconst decorated = nativeLines.map((line, index) =>\n\t\tdecorateMessageLine(line, index, nativeLines.length - 1, firstContentIndex, width, {\n\t\t\tfirstEnvelope,\n\t\t\tfirstHasStart,\n\t\t\tmultilineEnvelope,\n\t\t\tprefix,\n\t\t}),\n\t);\n\tif (!decorated.every((line) => visibleWidth(line) <= width)) return undefined;\n\tif (!nativeLines.every((line) => visibleWidth(line) <= bodyWidth)) return undefined;\n\treturn decorated;\n}\n\nexport type MessageDecorationSnapshot = Readonly<{\n\tassistantPrefix: string;\n\tassistantEnabled: boolean;\n\t/** Drop the hidden-thinking label row and its trailing spacer (zero-trace collapse). */\n\tcollapseHiddenThinking: boolean;\n}>;\n\nexport function decorateMessageRender(\n\toriginal: unknown,\n\tinstance: object,\n\targs: unknown[],\n\tsnapshot: MessageDecorationSnapshot = {\n\t\tassistantPrefix: \"│ \",\n\t\tassistantEnabled: true,\n\t\tcollapseHiddenThinking: false,\n\t},\n): unknown {\n\tif (typeof original !== \"function\") return undefined;\n\tconst width = typeof args[0] === \"number\" ? args[0] : 0;\n\tconst prefix = snapshot.assistantPrefix;\n\tif (!snapshot.assistantEnabled) return Reflect.apply(original, instance, args);\n\tif (width <= visibleWidth(prefix)) return Reflect.apply(original, instance, args);\n\t// Exactly one native invocation. If the reduced render cannot be certified, the\n\t// already-obtained result is the only safe fallback; retrying can mutate state.\n\tconst reducedWidth = width - visibleWidth(prefix);\n\tconst native = Reflect.apply(original, instance, [reducedWidth, ...args.slice(1)]);\n\treturn prefixNative(native, width, prefix) ?? native;\n}\n\n/** Spacer-like: renders empty lines and exposes only setLines among these surfaces. */\nfunction isSpacerChild(child: unknown): boolean {\n\treturn typeof (child as { setLines?: unknown } | undefined)?.setLines === \"function\";\n}\n\n/**\n * The hidden-thinking placeholder: a Text (setCustomBgFn) whose ANSI-stripped\n * rendered content is empty. Duck-typed on the public shape because\n * pi-coding-agent may resolve its own nested pi-tui copy, so `instanceof`\n * across that module boundary is unreliable.\n */\nfunction isBlankTextChild(child: unknown): boolean {\n\tconst candidate = child as { setCustomBgFn?: unknown; render?: (width: number) => string[] } | undefined;\n\tif (typeof candidate?.setCustomBgFn !== \"function\" || typeof candidate.render !== \"function\") return false;\n\treturn contentText(candidate.render(0).join(\"\\n\")).trim() === \"\";\n}\n\n/**\n * Collapse Pi's hidden-thinking placeholder row to zero trace.\n *\n * Native `AssistantMessageComponent.updateContent` renders the thinking block as\n * `Text(theme.italic(theme.fg(\"thinkingText\", label)), outputPad, 0)` plus a\n * trailing `Spacer(1)`. An empty label is still wrapped in ANSI SGR codes, so\n * `Text.render` cannot treat it as empty (its check is `text.trim() === \"\"`,\n * and trim does not strip escape sequences) and emits one full-width invisible\n * line. That invisible row plus the surrounding spacers is the \"gap\" left when\n * the label is hidden. This wrapper runs the native layout, then drops the\n * invisible label row and the spacer the native layout appends after the\n * thinking run, leaving the same single top padding as a text-only message.\n */\nexport function decorateMessageUpdate(\n\toriginal: unknown,\n\tinstance: object,\n\targs: unknown[],\n\tsnapshot: MessageDecorationSnapshot = {\n\t\tassistantPrefix: \"│ \",\n\t\tassistantEnabled: true,\n\t\tcollapseHiddenThinking: false,\n\t},\n): unknown {\n\tif (typeof original !== \"function\") return undefined;\n\tconst result = Reflect.apply(original, instance, args);\n\tif (!snapshot.collapseHiddenThinking) return result;\n\tconst target = instance as {\n\t\thideThinkingBlock?: boolean;\n\t\thiddenThinkingLabel?: string;\n\t\tcontentContainer?: { children?: unknown[] };\n\t};\n\t// Only meaningful when Pi renders the hidden-block label (hideThinkingBlock)\n\t// and the extension has blanked that label out (\"\" — the zero-trace mode).\n\tif (target.hideThinkingBlock !== true || target.hiddenThinkingLabel !== \"\") return result;\n\tconst children = target.contentContainer?.children;\n\tif (!children) return result;\n\tfor (let index = children.length - 1; index >= 0; index--) {\n\t\tif (!isBlankTextChild(children[index])) continue;\n\t\tchildren.splice(index, 1);\n\t\t// Drop the Spacer(1) the native layout appends after the thinking run when\n\t\t// another visible block follows; the message keeps only its shared top padding.\n\t\tif (isSpacerChild(children[index])) children.splice(index, 1);\n\t}\n\treturn result;\n}\n\n// Special private layouts are intentionally not installed; their prototypes remain native.\n","import { visibleWidth } from \"@earendil-works/pi-tui\";\nimport { EMPTY_BATCH_COMPONENT } from \"./boxed/batch.js\";\nimport { renderBoxedToolCall, renderBoxedToolResult } from \"./boxed/index.js\";\n\n/**\n * Batch members render zero lines. Pi's ToolExecutionComponent always adds a\n * built-in Spacer child (one blank line) and only sets hideComponent when\n * hasContent is false — but adding an empty renderer still marks hasContent\n * true. Mark the instance hidden so members contribute zero lines (no stray\n * blank margin after the batch panel). updateDisplay resets hideComponent on\n * every pass; the wrapper re-applies it on each dispatch.\n */\nfunction hideBatchMember(instance: object): void {\n\t(instance as { hideComponent?: boolean }).hideComponent = true;\n}\n\n/**\n * Neutralize the native ToolExecutionComponent status background for boxed\n * rendering: Pi's updateDisplay sets contentBox/selfRenderContainer bgFn to\n * toolPendingBg/toolErrorBg/toolSuccessBg before invoking the renderers. The\n * boxed renderers own their visual boundary (borders + ✓/✗ state marks), so the\n * container fill is removed (no background slab).\n * Runs on every boxed dispatch; updateDisplay re-applies the bgFn on the next\n * pass and this wrapper re-neutralizes it.\n */\nfunction neutralizeToolContainerBackground(instance: object): void {\n\tconst host = instance as {\n\t\tgetRenderShell?(): string;\n\t\tselfRenderContainer?: { setBgFn?(fn: (text: string) => string): void; paddingX?: number; paddingY?: number };\n\t\tcontentBox?: { setBgFn?(fn: (text: string) => string): void; paddingX?: number; paddingY?: number };\n\t};\n\tconst container =\n\t\ttypeof host.getRenderShell === \"function\" && host.getRenderShell() === \"self\"\n\t\t\t? host.selfRenderContainer\n\t\t\t: host.contentBox;\n\tif (!container) return;\n\tcontainer.paddingX = 0;\n\tcontainer.paddingY = 0;\n\tif (typeof container.setBgFn === \"function\") container.setBgFn((text) => text);\n}\n\ntype RenderFunction = (this: object, ...args: unknown[]) => unknown;\ntype RendererSubtype = \"tool-call-renderer\" | \"tool-result-renderer\";\ntype RendererKind = \"call\" | \"result\";\ntype TransactionState = \"never-written\" | \"installed-owned\" | \"owner-changed\" | \"rollback-restored\" | \"rollback-failed\";\ntype ToolRenderContext = {\n\targs: object;\n\ttoolCallId: string;\n\tinvalidate: () => void;\n\tlastComponent: object | undefined;\n\tstate: object;\n\tcwd: string;\n\texecutionStarted: boolean;\n\targsComplete: boolean;\n\tisPartial: boolean;\n\texpanded: boolean;\n\tshowImages: boolean;\n\tisError: boolean;\n};\ntype ToolDecorationSnapshot = Readonly<{\n\tcallMarker: string;\n\tresultMarker: string;\n\t/** marker = prefix lines; compact-box = boxed tool call/result rendering. */\n\tstyle?: \"marker\" | \"compact-box\";\n}>;\ntype DescriptorView = Readonly<{\n\tkind: \"data\" | \"accessor\";\n\tvalue?: unknown;\n\tget?: unknown;\n\tset?: unknown;\n\twritable?: boolean;\n\tenumerable: boolean;\n\tconfigurable: boolean;\n}>;\ntype FailureEntry = Readonly<{ reason: string; transaction: TransactionState }>;\nexport type ToolDiagnosticArchive = Readonly<{\n\towner: string;\n\tgeneration: number;\n\treasons: Readonly<Record<string, number>>;\n\trestored: number;\n\tfailed: number;\n\tlaterOwner: number;\n\tfailures: readonly FailureEntry[];\n}>;\ntype CleanupOutcome = \"restored\" | \"later-owner\" | \"retry\";\ntype DecorationRecord = {\n\tcomponent: object;\n\tnativeRender: RenderFunction;\n\twrappedRender: RenderFunction;\n\tattemptedDescriptor: PropertyDescriptor;\n\toriginalOwnDescriptor?: PropertyDescriptor;\n\tinheritedDescriptor?: PropertyDescriptor;\n\tcontext: ToolRenderContext;\n\ttransaction: TransactionState;\n\tlastFailureSignature?: string;\n};\ntype DecorationState = {\n\tsnapshot: ToolDecorationSnapshot;\n\tdecorated: WeakMap<object, DecorationRecord>;\n\tactive: Set<DecorationRecord>;\n\tdiagnostics: Map<string, number>;\n\tfailures: FailureEntry[];\n\tarchive?: ToolDiagnosticArchive;\n\trestored: number;\n\tfailed: number;\n\tlaterOwner: number;\n\tgeneration: number;\n};\nconst DEFAULT_SNAPSHOT: ToolDecorationSnapshot = Object.freeze({\n\tcallMarker: \"[tool] \",\n\tresultMarker: \"[tool:result] \",\n\tstyle: \"marker\",\n});\nlet ownerGeneration = 0;\nconst piStyleWrappers = new WeakSet<RenderFunction>();\nlet toolTestHooks: { defineProperty?: typeof Reflect.defineProperty; deleteProperty?: typeof Reflect.deleteProperty } =\n\t{};\nexport function __setToolDecorationTestHooks(hooks: typeof toolTestHooks): () => void {\n\tconst previous = toolTestHooks;\n\ttoolTestHooks = hooks;\n\treturn () => {\n\t\ttoolTestHooks = previous;\n\t};\n}\n\nfunction note(state: DecorationState, reason: string, transaction: TransactionState = \"never-written\"): void {\n\tstate.diagnostics.set(reason, (state.diagnostics.get(reason) ?? 0) + 1);\n\tif (state.failures.length < 32) state.failures.push(Object.freeze({ reason, transaction }));\n}\nfunction isObject(value: unknown): value is object {\n\treturn typeof value === \"object\" && value !== null;\n}\nfunction ownData(object: object, key: string): unknown {\n\tconst descriptor = Object.getOwnPropertyDescriptor(object, key);\n\treturn descriptor && \"value\" in descriptor ? descriptor.value : undefined;\n}\nfunction hasOwnData(object: object, key: string): boolean {\n\tconst descriptor = Object.getOwnPropertyDescriptor(object, key);\n\treturn descriptor !== undefined && \"value\" in descriptor;\n}\nfunction validContext(value: unknown): value is ToolRenderContext {\n\tif (!isObject(value)) return false;\n\tconst booleans = [\"isPartial\", \"expanded\", \"isError\", \"executionStarted\", \"argsComplete\", \"showImages\"] as const;\n\treturn (\n\t\tisObject(ownData(value, \"args\")) &&\n\t\ttypeof ownData(value, \"toolCallId\") === \"string\" &&\n\t\ttypeof ownData(value, \"invalidate\") === \"function\" &&\n\t\tisObject(ownData(value, \"state\")) &&\n\t\ttypeof ownData(value, \"cwd\") === \"string\" &&\n\t\tbooleans.every((key) => typeof ownData(value, key) === \"boolean\") &&\n\t\thasOwnData(value, \"lastComponent\") &&\n\t\t(ownData(value, \"lastComponent\") === undefined || isObject(ownData(value, \"lastComponent\")))\n\t);\n}\nfunction validCallArgs(args: unknown[]): args is [object, object, ToolRenderContext] {\n\treturn args.length === 3 && isObject(args[0]) && isObject(args[1]) && validContext(args[2]);\n}\nfunction validResultArgs(args: unknown[]): args is [object, object, object, ToolRenderContext] {\n\tconst [result, options, theme, context] = args;\n\treturn (\n\t\tisObject(result) &&\n\t\thasOwnData(result, \"content\") &&\n\t\tArray.isArray(ownData(result, \"content\")) &&\n\t\thasOwnData(result, \"details\") &&\n\t\tisObject(options) &&\n\t\ttypeof ownData(options, \"expanded\") === \"boolean\" &&\n\t\ttypeof ownData(options, \"isPartial\") === \"boolean\" &&\n\t\tisObject(theme) &&\n\t\tvalidContext(context)\n\t);\n}\nfunction descriptorView(descriptor: PropertyDescriptor | undefined): DescriptorView | undefined {\n\tif (!descriptor) return undefined;\n\tif (\"value\" in descriptor)\n\t\treturn Object.freeze({\n\t\t\tkind: \"data\",\n\t\t\tvalue: descriptor.value,\n\t\t\twritable: descriptor.writable === true,\n\t\t\tenumerable: descriptor.enumerable === true,\n\t\t\tconfigurable: descriptor.configurable === true,\n\t\t});\n\treturn Object.freeze({\n\t\tkind: \"accessor\",\n\t\tget: descriptor.get,\n\t\tset: descriptor.set,\n\t\tenumerable: descriptor.enumerable === true,\n\t\tconfigurable: descriptor.configurable === true,\n\t});\n}\nfunction descriptorEqual(actual: PropertyDescriptor | undefined, expected: PropertyDescriptor | undefined): boolean {\n\tconst a = descriptorView(actual),\n\t\te = descriptorView(expected);\n\treturn (\n\t\ta?.kind === e?.kind &&\n\t\ta?.value === e?.value &&\n\t\ta?.get === e?.get &&\n\t\ta?.set === e?.set &&\n\t\ta?.writable === e?.writable &&\n\t\ta?.enumerable === e?.enumerable &&\n\t\ta?.configurable === e?.configurable\n\t);\n}\nfunction renderDescriptor(\n\tcomponent: object,\n): { own?: PropertyDescriptor; inherited?: PropertyDescriptor; native?: RenderFunction } | false {\n\tconst own = Object.getOwnPropertyDescriptor(component, \"render\");\n\tif (own && !(\"value\" in own && typeof own.value === \"function\" && own.writable === true && own.configurable === true))\n\t\treturn false;\n\tlet cursor = Object.getPrototypeOf(component);\n\tlet inherited: PropertyDescriptor | undefined;\n\twhile (cursor && !inherited) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(cursor, \"render\");\n\t\tif (descriptor) inherited = descriptor;\n\t\tcursor = Object.getPrototypeOf(cursor);\n\t}\n\tif (!own && inherited && !(\"value\" in inherited && typeof inherited.value === \"function\")) return false;\n\tconst native = own?.value ?? (inherited && \"value\" in inherited ? inherited.value : undefined);\n\treturn typeof native === \"function\"\n\t\t? { ...(own ? { own } : {}), ...(inherited ? { inherited } : {}), native }\n\t\t: false;\n}\nfunction marker(state: DecorationState, context: ToolRenderContext, kind: RendererKind): string {\n\tif (context.isError) return \"[tool:error] \";\n\tif (context.isPartial) return context.executionStarted ? \"[tool:running] \" : \"[tool:pending] \";\n\treturn kind === \"call\" ? state.snapshot.callMarker : state.snapshot.resultMarker;\n}\nfunction decorateLines(state: DecorationState, value: unknown, width: unknown, prefix: string): unknown {\n\tif (!Array.isArray(value) || !value.every((line) => typeof line === \"string\")) {\n\t\tnote(state, \"malformed-render\");\n\t\treturn value;\n\t}\n\tif (typeof width !== \"number\" || !Number.isFinite(width) || width < 0) {\n\t\tnote(state, \"invalid-width\");\n\t\treturn value;\n\t}\n\tconst lines = value as string[],\n\t\tprefixWidth = visibleWidth(prefix),\n\t\tbodyWidth = width - prefixWidth;\n\tif (width <= prefixWidth || !lines.every((line) => visibleWidth(line) <= bodyWidth)) {\n\t\tnote(state, \"reduced-native-fallback\");\n\t\treturn value;\n\t}\n\tconst output =\n\t\tlines.length === 0 ? [prefix.trimEnd()] : lines.map((line, index) => (index === 0 ? `${prefix}${line}` : line));\n\tif (output.every((line) => visibleWidth(line) <= width)) return output;\n\tnote(state, \"overwide-decoration\");\n\treturn value;\n}\nfunction createRecord(\n\tstate: DecorationState,\n\tcomponent: object,\n\tnativeRender: RenderFunction,\n\tcontext: ToolRenderContext,\n\tkind: RendererKind,\n\tdescriptors: { own?: PropertyDescriptor; inherited?: PropertyDescriptor },\n): DecorationRecord {\n\tconst attemptedDescriptor = descriptors.own\n\t\t? { ...descriptors.own, value: undefined as unknown as RenderFunction }\n\t\t: { value: undefined as unknown as RenderFunction, writable: true, enumerable: false, configurable: true };\n\tconst record = {\n\t\tcomponent,\n\t\tnativeRender,\n\t\twrappedRender: undefined as unknown as RenderFunction,\n\t\tattemptedDescriptor,\n\t\t...(descriptors.own ? { originalOwnDescriptor: descriptors.own } : {}),\n\t\t...(descriptors.inherited ? { inheritedDescriptor: descriptors.inherited } : {}),\n\t\tcontext,\n\t\ttransaction: \"never-written\" as TransactionState,\n\t};\n\trecord.wrappedRender = function (this: object, ...renderArgs: unknown[]): unknown {\n\t\tconst width = renderArgs[0],\n\t\t\tprefix = marker(state, record.context, kind);\n\t\tconst nativeArgs =\n\t\t\ttypeof width === \"number\" && width > visibleWidth(prefix)\n\t\t\t\t? [width - visibleWidth(prefix), ...renderArgs.slice(1)]\n\t\t\t\t: renderArgs;\n\t\treturn decorateLines(state, Reflect.apply(record.nativeRender, this, nativeArgs), width, prefix);\n\t};\n\tpiStyleWrappers.add(record.wrappedRender);\n\treturn record;\n}\nfunction installDecoration(state: DecorationState, record: DecorationRecord): void {\n\trecord.attemptedDescriptor.value = record.wrappedRender;\n\tlet wrote = false;\n\ttry {\n\t\twrote = Reflect.defineProperty(record.component, \"render\", record.attemptedDescriptor);\n\t} catch (error) {\n\t\tnote(state, `render-install-threw: ${error instanceof Error ? error.message : String(error)}`, \"never-written\");\n\t\treturn;\n\t}\n\tif (!wrote) {\n\t\tnote(state, \"render-install-rejected\", \"never-written\");\n\t\treturn;\n\t}\n\tconst current = Object.getOwnPropertyDescriptor(record.component, \"render\");\n\tif (!descriptorEqual(current, record.attemptedDescriptor)) {\n\t\tif (current?.value === record.wrappedRender) {\n\t\t\tconst restored = record.originalOwnDescriptor\n\t\t\t\t? (toolTestHooks.defineProperty ?? Reflect.defineProperty)(\n\t\t\t\t\t\trecord.component,\n\t\t\t\t\t\t\"render\",\n\t\t\t\t\t\trecord.originalOwnDescriptor,\n\t\t\t\t\t)\n\t\t\t\t: (toolTestHooks.deleteProperty ?? Reflect.deleteProperty)(record.component, \"render\");\n\t\t\tconst after = Object.getOwnPropertyDescriptor(record.component, \"render\");\n\t\t\tif (\n\t\t\t\trestored &&\n\t\t\t\t(record.originalOwnDescriptor ? descriptorEqual(after, record.originalOwnDescriptor) : after === undefined)\n\t\t\t) {\n\t\t\t\trecord.transaction = \"rollback-restored\";\n\t\t\t\tnote(state, \"render-install-flags-mismatch-rolled-back\", record.transaction);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\trecord.transaction = \"rollback-failed\";\n\t\t\tstate.decorated.set(record.component, record);\n\t\t\tstate.active.add(record);\n\t\t\tnote(state, \"render-install-rollback-failed\", record.transaction);\n\t\t\treturn;\n\t\t}\n\t\trecord.transaction = \"owner-changed\";\n\t\tnote(state, \"render-owner-changed-during-install\", record.transaction);\n\t\treturn;\n\t}\n\trecord.transaction = \"installed-owned\";\n\tstate.decorated.set(record.component, record);\n\tstate.active.add(record);\n}\nfunction restoreDecoration(state: DecorationState, record: DecorationRecord): CleanupOutcome {\n\tconst current = Object.getOwnPropertyDescriptor(record.component, \"render\");\n\tif (!descriptorEqual(current, record.attemptedDescriptor)) {\n\t\trecord.transaction = \"owner-changed\";\n\t\tstate.laterOwner++;\n\t\tnote(state, \"render-owner-changed\", record.transaction);\n\t\treturn \"later-owner\";\n\t}\n\tconst restored = record.originalOwnDescriptor\n\t\t? (toolTestHooks.defineProperty ?? Reflect.defineProperty)(record.component, \"render\", record.originalOwnDescriptor)\n\t\t: (toolTestHooks.deleteProperty ?? Reflect.deleteProperty)(record.component, \"render\");\n\tconst after = Object.getOwnPropertyDescriptor(record.component, \"render\");\n\tconst ok = record.originalOwnDescriptor ? descriptorEqual(after, record.originalOwnDescriptor) : after === undefined;\n\tif (!restored || !ok) {\n\t\trecord.transaction = \"rollback-failed\";\n\t\tconst signature = JSON.stringify(descriptorView(after));\n\t\tif (record.lastFailureSignature !== signature) {\n\t\t\trecord.lastFailureSignature = signature;\n\t\t\tnote(state, \"render-restore-failed\", record.transaction);\n\t\t}\n\t\treturn \"retry\";\n\t}\n\trecord.transaction = \"rollback-restored\";\n\treturn \"restored\";\n}\nfunction finalize(state: DecorationState): ToolDiagnosticArchive {\n\tif (state.archive) return state.archive;\n\tconst reasons = Object.freeze(Object.fromEntries(state.diagnostics));\n\tstate.archive = Object.freeze({\n\t\towner: `tool-owner-${state.generation}`,\n\t\tgeneration: state.generation,\n\t\treasons,\n\t\trestored: state.restored,\n\t\tfailed: state.failed,\n\t\tlaterOwner: state.laterOwner,\n\t\tfailures: Object.freeze(state.failures.slice(0, 32)),\n\t});\n\treturn state.archive;\n}\nexport function createToolDecorationOwner(snapshot: Partial<ToolDecorationSnapshot> = {}) {\n\tconst state: DecorationState = {\n\t\tsnapshot: Object.freeze({ ...DEFAULT_SNAPSHOT, ...snapshot }),\n\t\tdecorated: new WeakMap(),\n\t\tactive: new Set(),\n\t\tdiagnostics: new Map(),\n\t\tfailures: [],\n\t\trestored: 0,\n\t\tfailed: 0,\n\t\tlaterOwner: 0,\n\t\tgeneration: ++ownerGeneration,\n\t};\n\tconst dispose = () => {\n\t\tif (state.archive)\n\t\t\treturn {\n\t\t\t\trestored: state.restored,\n\t\t\t\tfailed: state.failed,\n\t\t\t\tdiagnostics: new Map(state.diagnostics),\n\t\t\t\tarchive: state.archive,\n\t\t\t};\n\t\tfor (const record of [...state.active]) {\n\t\t\tconst outcome = restoreDecoration(state, record);\n\t\t\tif (outcome === \"restored\") {\n\t\t\t\tstate.restored++;\n\t\t\t\tstate.active.delete(record);\n\t\t\t} else if (outcome === \"later-owner\") state.active.delete(record);\n\t\t\telse state.failed++;\n\t\t}\n\t\tconst archive = state.active.size === 0 ? finalize(state) : undefined;\n\t\treturn { restored: state.restored, failed: state.failed, diagnostics: new Map(state.diagnostics), archive };\n\t};\n\treturn Object.freeze({\n\t\tdecorateToolRendererSelection(subtype: RendererSubtype, original: unknown, instance: object, args: unknown[]) {\n\t\t\tif (typeof original !== \"function\") return undefined;\n\t\t\tconst renderer = Reflect.apply(original, instance, args);\n\t\t\tif (state.snapshot.style === \"compact-box\") {\n\t\t\t\tconst toolName = (instance as { toolName?: unknown }).toolName;\n\t\t\t\t// Tools without a native renderCall/renderResult (e.g. extension tools\n\t\t\t\t// like TaskUpdate/TaskList) still get boxed presentation through a\n\t\t\t\t// fallback renderer, mirroring the generic boxed fallback used for\n\t\t\t\t// unknown tool names.\n\t\t\t\tif (typeof renderer !== \"function\") {\n\t\t\t\t\tneutralizeToolContainerBackground(instance);\n\t\t\t\t\tif (subtype === \"tool-call-renderer\")\n\t\t\t\t\t\treturn (callArgs: unknown, theme: unknown, context: unknown) =>\n\t\t\t\t\t\t\trenderBoxedToolCall(toolName, callArgs as Record<string, unknown>, theme as never, context as never);\n\t\t\t\t\treturn (result: unknown, options: unknown, theme: unknown, context: unknown) =>\n\t\t\t\t\t\trenderBoxedToolResult(\n\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\tresult as { content?: readonly unknown[]; details?: unknown },\n\t\t\t\t\t\t\toptions as { expanded: boolean; isPartial: boolean },\n\t\t\t\t\t\t\ttheme as never,\n\t\t\t\t\t\t\tcontext as never,\n\t\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn function (this: unknown, ...rendererArgs: unknown[]) {\n\t\t\t\t\tconst valid = subtype === \"tool-call-renderer\" ? validCallArgs(rendererArgs) : validResultArgs(rendererArgs);\n\t\t\t\t\tif (!valid) {\n\t\t\t\t\t\tnote(state, `${subtype}-malformed-context`);\n\t\t\t\t\t\treturn Reflect.apply(renderer, this, rendererArgs);\n\t\t\t\t\t}\n\t\t\t\t\tconst component =\n\t\t\t\t\t\tsubtype === \"tool-call-renderer\"\n\t\t\t\t\t\t\t? (() => {\n\t\t\t\t\t\t\t\t\tconst [args, theme, context] = rendererArgs as [object, object, ToolRenderContext];\n\t\t\t\t\t\t\t\t\treturn renderBoxedToolCall(\n\t\t\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\t\t\targs as Record<string, unknown>,\n\t\t\t\t\t\t\t\t\t\ttheme as never,\n\t\t\t\t\t\t\t\t\t\tcontext as never,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t})()\n\t\t\t\t\t\t\t: (() => {\n\t\t\t\t\t\t\t\t\tconst [result, options, theme, context] = rendererArgs as [object, object, object, ToolRenderContext];\n\t\t\t\t\t\t\t\t\treturn renderBoxedToolResult(\n\t\t\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\t\t\tresult as { content?: readonly unknown[]; details?: unknown },\n\t\t\t\t\t\t\t\t\t\toptions as { expanded: boolean; isPartial: boolean },\n\t\t\t\t\t\t\t\t\t\ttheme as never,\n\t\t\t\t\t\t\t\t\t\tcontext as never,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t})();\n\t\t\t\t\tneutralizeToolContainerBackground(instance);\n\t\t\t\t\tif (component === EMPTY_BATCH_COMPONENT) hideBatchMember(instance);\n\t\t\t\t\treturn component;\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (typeof renderer !== \"function\") return renderer;\n\t\t\treturn function (this: unknown, ...rendererArgs: unknown[]) {\n\t\t\t\tconst valid = subtype === \"tool-call-renderer\" ? validCallArgs(rendererArgs) : validResultArgs(rendererArgs);\n\t\t\t\tif (!valid) {\n\t\t\t\t\tnote(state, `${subtype}-malformed-context`);\n\t\t\t\t\treturn Reflect.apply(renderer, this, rendererArgs);\n\t\t\t\t}\n\t\t\t\tconst component = Reflect.apply(renderer, this, rendererArgs);\n\t\t\t\tif (!isObject(component)) return component;\n\t\t\t\tconst descriptors = renderDescriptor(component);\n\t\t\t\tif (descriptors !== false && descriptors.native && piStyleWrappers.has(descriptors.native)) {\n\t\t\t\t\tnote(state, `${subtype}-owner-conflict`);\n\t\t\t\t\treturn component;\n\t\t\t\t}\n\t\t\t\tif (!descriptors) {\n\t\t\t\t\tnote(state, `${subtype}-unsafe-render-descriptor`);\n\t\t\t\t\treturn component;\n\t\t\t\t}\n\t\t\t\tconst record = state.decorated.get(component);\n\t\t\t\tif (record) {\n\t\t\t\t\trecord.context = rendererArgs.at(-1) as ToolRenderContext;\n\t\t\t\t\treturn component;\n\t\t\t\t}\n\t\t\t\tconst next = createRecord(\n\t\t\t\t\tstate,\n\t\t\t\t\tcomponent,\n\t\t\t\t\tdescriptors.native as RenderFunction,\n\t\t\t\t\trendererArgs.at(-1) as ToolRenderContext,\n\t\t\t\t\tsubtype === \"tool-call-renderer\" ? \"call\" : \"result\",\n\t\t\t\t\tdescriptors,\n\t\t\t\t);\n\t\t\t\tinstallDecoration(state, next);\n\t\t\t\treturn component;\n\t\t\t};\n\t\t},\n\t\tgetDiagnostics: () => new Map(state.diagnostics),\n\t\tgetFinalArchive: () => state.archive,\n\t\tgetActiveRecordCount: () => state.active.size,\n\t\tdispose,\n\t});\n}\n","// Boxed edit tool renderer\n// (renderCall/renderResult only; no edit-core re-registration).\n\nimport { getLanguageFromPath } from \"@earendil-works/pi-coding-agent\";\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport { stripAnsi } from \"../../../shared/ansi.js\";\nimport {\n\ttype BoxTheme,\n\tformatBoxedRunningStatus,\n\tgetTextOutput,\n\trenderBoxedToolCall,\n\trenderBoxedToolResult,\n} from \"../../../shared/box.js\";\nimport { formatElapsedMs, getElapsedMs } from \"../../../shared/elapsed.js\";\nimport {\n\tAdaptiveDiffComponent,\n\tbuildSplitRows,\n\tcountDiffStats,\n\textractEditedPath,\n\tfirstText,\n} from \"../../../shared/split-diff.js\";\nimport { isResultSeen } from \"./session-config.js\";\nimport {\n\ttype BoxedToolContext,\n\ttype BoxedToolDefinition,\n\tdisplayPath,\n\tnoteBoxedCallState,\n\tnoteBoxedResultPhase,\n\tnoteExecutionStart,\n\tresultFooterLines,\n\tstateElapsedMs,\n} from \"./shared.js\";\n\nconst MAX_HIGHLIGHT_DIFF_CHARS = 12000;\nconst MAX_HIGHLIGHT_DIFF_ROWS = 120;\n\n/** First-partial-pass result: the pending/running call card stands alone. */\nconst EMPTY_EDIT_RESULT: Component = Object.freeze({\n\tinvalidate() {},\n\trender() {\n\t\treturn [];\n\t},\n});\n\ntype EditResultDetails = { diff?: string; path?: string } | undefined;\n\n/** `Diff · +3 -0` divider label. */\nfunction diffDividerLabel(theme: BoxTheme, stats: { additions: number; removals: number }): string {\n\tconst plus = stats.additions > 0 ? theme.fg(\"toolDiffAdded\", `+${stats.additions}`) : theme.fg(\"dim\", \"+0\");\n\tconst minus = stats.removals > 0 ? theme.fg(\"toolDiffRemoved\", `-${stats.removals}`) : theme.fg(\"dim\", \"-0\");\n\treturn `Diff · ${plus} ${minus}`;\n}\n\n/** Edit footer: `1 file · +3 -0`, prefixed with elapsed time when known. */\nfunction editDiffFooter(\n\ttheme: BoxTheme,\n\tresult: { content?: readonly unknown[]; details?: unknown },\n\tcontext: BoxedToolContext,\n\tstats: { additions: number; removals: number },\n): string {\n\tconst elapsedMs = getElapsedMs(result) ?? stateElapsedMs(context);\n\tconst parts: string[] = [];\n\tif (elapsedMs !== undefined) parts.push(theme.fg(\"text\", formatElapsedMs(elapsedMs)));\n\tconst plus = stats.additions > 0 ? theme.fg(\"toolDiffAdded\", `+${stats.additions}`) : theme.fg(\"dim\", \"+0\");\n\tconst minus = stats.removals > 0 ? theme.fg(\"toolDiffRemoved\", `-${stats.removals}`) : theme.fg(\"dim\", \"-0\");\n\tparts.push(theme.fg(\"dim\", \"1 file\"), `${plus} ${minus}`);\n\treturn parts.join(theme.fg(\"dim\", \" · \"));\n}\n\nexport const editTool: BoxedToolDefinition = {\n\tcall(args, theme, context) {\n\t\tnoteExecutionStart(context);\n\t\tnoteBoxedCallState(context);\n\t\tconst detail = displayPath(String(args?.path ?? args?.file_path ?? \"\"), context);\n\t\treturn renderBoxedToolCall(theme, \"Edit\", [], {\n\t\t\theaderDetail: detail,\n\t\t\tisError: Boolean(context.isError),\n\t\t\tisPartial: Boolean(context.isPartial),\n\t\t\tisPending: Boolean(context.isPartial),\n\t\t\trunning: Boolean(context.executionStarted),\n\t\t\tresultSeen: isResultSeen(context.state),\n\t\t});\n\t},\n\tresult(result, options, theme, context) {\n\t\t// Handle partial/streaming state: continue the open call box with the\n\t\t// applying hint (no Response divider until the tool settles).\n\t\tif (options.isPartial) {\n\t\t\tconst firstResultPass = noteBoxedResultPhase(context, options.isPartial);\n\t\t\tif (firstResultPass) return EMPTY_EDIT_RESULT;\n\t\t\treturn renderBoxedToolResult(theme, () => [`${theme.fg(\"dim\", \"↳\")} ${theme.fg(\"muted\", \"Applying edit...\")}`], {\n\t\t\t\tshowDivider: false,\n\t\t\t\tfooterLines: [formatBoxedRunningStatus(theme, stateElapsedMs(context))],\n\t\t\t\tisPartial: true,\n\t\t\t});\n\t\t}\n\n\t\t// Handle errors\n\t\tif (context.isError) {\n\t\t\tconst output = getTextOutput(result);\n\t\t\treturn renderBoxedToolResult(theme, () => [theme.fg(\"error\", stripAnsi(output).trim() || \"Error\")], {\n\t\t\t\tfooterLines: resultFooterLines(theme, result, context),\n\t\t\t\tisError: true,\n\t\t\t});\n\t\t}\n\n\t\t// Extract diff from result details\n\t\tconst details = result.details as EditResultDetails;\n\t\tconst diff = details?.diff as string | undefined;\n\n\t\tif (!diff) {\n\t\t\tconst output = stripAnsi(getTextOutput(result)).trim();\n\t\t\tconst fallback = `↳ ${output || \"Edit applied\"}`;\n\t\t\treturn renderBoxedToolResult(theme, () => [theme.fg(\"dim\", fallback)], {\n\t\t\t\tfooterLines: resultFooterLines(theme, result, context),\n\t\t\t});\n\t\t}\n\n\t\t// Resolve language for syntax highlighting\n\t\tconst message = firstText(result.content as Array<{ type: string; text?: string }>);\n\t\tconst argPath = String(context?.args?.path ?? context?.args?.file_path ?? \"\");\n\t\tconst sourcePath = details?.path ?? (argPath || extractEditedPath(message));\n\t\tconst language = sourcePath ? getLanguageFromPath(sourcePath) : undefined;\n\n\t\t// Build diff rows + adaptive layout\n\t\tconst rows = buildSplitRows(diff);\n\t\tconst expanded = options.expanded;\n\t\tconst shouldHighlight =\n\t\t\tBoolean(language) && diff.length <= MAX_HIGHLIGHT_DIFF_CHARS && rows.length <= MAX_HIGHLIGHT_DIFF_ROWS;\n\t\tconst stats = countDiffStats(diff);\n\n\t\t// Render adaptive diff (unified/split per width) with syntax colors for small outputs.\n\t\tconst maxRows = expanded ? 160 : 36;\n\t\tconst diffView = new AdaptiveDiffComponent(theme, rows, maxRows, shouldHighlight ? language : undefined);\n\t\tconst expandHint = !expanded && diffView.hasCollapsed() ? \"Ctrl+O more\" : undefined;\n\n\t\treturn renderBoxedToolResult(\n\t\t\ttheme,\n\t\t\t{\n\t\t\t\trender(width: number): string[] {\n\t\t\t\t\treturn diffView.render(width);\n\t\t\t\t},\n\t\t\t\tinvalidate(): void {\n\t\t\t\t\tdiffView.invalidate();\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tdividerLabel: diffDividerLabel(theme, stats),\n\t\t\t\t...(expandHint ? { dividerRightLabel: expandHint } : {}),\n\t\t\t\tfooterLines: [editDiffFooter(theme, result, context, stats)],\n\t\t\t},\n\t\t);\n\t},\n};\n\nexport type { BoxedToolContext };\n","// Boxed fallback for tools without a dedicated renderer.\n// (component side only; no ToolExecutionComponent prototype patching).\n\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport type { BoxTheme, MetricResultLike } from \"../../../shared/box.js\";\nimport {\n\tformatBoxedRunningStatus,\n\tformatBoxedWords,\n\tformatToolName,\n\tformatToolOutputLine,\n\tformatToolParamLines,\n\tgetTextOutput,\n\trenderBoxedToolCall,\n\trenderBoxedToolResult,\n\tselectRenderLines,\n} from \"../../../shared/box.js\";\nimport { getStateElapsedMs, getToolsRenderConfig, isResultSeen } from \"./session-config.js\";\nimport { type BoxedToolContext, noteBoxedCallState, noteBoxedResultPhase, noteExecutionStart } from \"./shared.js\";\n\nconst MAX_FALLBACK_PREVIEW_LINES = 10;\n\nexport function renderFallbackCall(\n\ttoolName: unknown,\n\targs: Record<string, unknown>,\n\ttheme: BoxTheme,\n\tcontext: BoxedToolContext,\n): Component {\n\tnoteExecutionStart(context);\n\tnoteBoxedCallState(context);\n\treturn renderBoxedToolCall(theme, formatToolName(String(toolName ?? \"Tool\")), formatToolParamLines(args, theme), {\n\t\tisError: Boolean(context.isError),\n\t\tisPartial: Boolean(context.isPartial),\n\t\tisPending: Boolean(context.isPartial),\n\t\trunning: Boolean(context.executionStarted),\n\t\tresultSeen: isResultSeen(context.state),\n\t});\n}\n\nexport function renderFallbackResult(\n\t_toolName: unknown,\n\tresult: MetricResultLike,\n\toptions: { expanded: boolean; isPartial: boolean },\n\ttheme: BoxTheme,\n\tcontext: BoxedToolContext,\n): Component {\n\tconst firstResultPass = noteBoxedResultPhase(context, options.isPartial);\n\tconst isError = Boolean(context.isError);\n\tconst expanded = Boolean(options.expanded);\n\tconst maxLines = expanded ? getToolsRenderConfig().maxExpandedLines : MAX_FALLBACK_PREVIEW_LINES;\n\tconst output = getTextOutput(result);\n\tconst elapsedMs = getStateElapsedMs(context.state);\n\tconst { lines, omitted } = selectRenderLines(output, maxLines);\n\n\tif (options.isPartial) {\n\t\t// Streaming continuation into the open call box: no Response divider and\n\t\t// no metrics footer until the tool settles. The first partial pass renders\n\t\t// nothing so the pending/running call card stands alone.\n\t\tif (firstResultPass) return EMPTY_FALLBACK_RESULT;\n\t\tconst hasOutput = output.trim().length > 0;\n\t\treturn renderBoxedToolResult(\n\t\t\ttheme,\n\t\t\t() => {\n\t\t\t\tconst body = lines.map((line) => formatToolOutputLine(theme, line, \"toolOutput\"));\n\t\t\t\tif (!hasOutput) body.push(theme.fg(\"dim\", \"No output received yet\"));\n\t\t\t\treturn body;\n\t\t\t},\n\t\t\t{\n\t\t\t\tdividerLabel: \"Output\",\n\t\t\t\tshowDivider: hasOutput,\n\t\t\t\tfooterLines: [formatBoxedRunningStatus(theme, elapsedMs)],\n\t\t\t\tisPartial: true,\n\t\t\t},\n\t\t);\n\t}\n\n\treturn renderBoxedToolResult(\n\t\ttheme,\n\t\t() => {\n\t\t\tconst body = lines.map((line) => formatToolOutputLine(theme, line, isError ? \"error\" : \"toolOutput\"));\n\t\t\tif (expanded && omitted > 0) {\n\t\t\t\tbody.push(theme.fg(\"muted\", `… ${omitted} more lines omitted by render budget`));\n\t\t\t}\n\t\t\treturn body;\n\t\t},\n\t\t{\n\t\t\tfooterLines: [formatBoxedFooterWithElapsed(theme, elapsedMs, output)],\n\t\t\trenderLineBudget: maxLines,\n\t\t\t...(expanded || omitted <= 0 ? {} : { expandHint: \"Ctrl+O for more\" }),\n\t\t\tisError,\n\t\t\tisPartial: Boolean(options.isPartial),\n\t\t},\n\t);\n}\n\n/** First-partial-pass result: the pending/running call card stands alone. */\nconst EMPTY_FALLBACK_RESULT: Component = Object.freeze({\n\tinvalidate() {},\n\trender() {\n\t\treturn [];\n\t},\n});\n\nfunction formatBoxedFooterWithElapsed(theme: BoxTheme, elapsedMs: number | undefined, output: string): string {\n\tconst elapsed = elapsedMs === undefined ? \"--\" : `${(elapsedMs / 1000).toFixed(2)}s`;\n\tconst words = output.trim() ? formatBoxedWords(output) : \"\";\n\tconst parts = [theme.fg(\"text\", elapsed)];\n\tif (words) parts.push(theme.fg(\"dim\", words));\n\treturn parts.join(theme.fg(\"dim\", \" · \"));\n}\n\n// Re-exported for callers that need the tool-name label normalization.\nexport { formatToolName };\n","// Boxed find tool renderer.\n//\n// find calls render as a boxless tree panel — a lone find shows its parsed\n// output as a flat `Find: <pattern> <N> files · in <path>` tree; consecutive\n// find calls group into one panel with per-member nested subtrees (see\n// batch.ts). Pending/failed calls without output fall back to a path row.\n\nimport { stripAnsi } from \"../../../shared/ansi.js\";\nimport { getTextOutput, shortenPath } from \"../../../shared/box.js\";\nimport {\n\ttype BatchToolMeta,\n\tEMPTY_BATCH_COMPONENT,\n\temptyBatchResult,\n\tregisterBatchCall,\n\tregisterBatchResult,\n\trenderBatchAwareCall,\n} from \"./batch.js\";\nimport { parseFindOutput } from \"./output-tree.js\";\nimport { type BoxedToolDefinition, noteExecutionStart } from \"./shared.js\";\n\nconst FIND_META: BatchToolMeta = Object.freeze({\n\ttoolName: \"find\",\n\tlabel: \"Find\",\n\theaderLabel: \"Find\",\n});\n\nfunction pathLabel(rawPath: string): string {\n\tconst displayPath = String(rawPath ?? \".\");\n\treturn displayPath === \".\" || displayPath === \"\" ? \"current directory\" : shortenPath(displayPath);\n}\n\nfunction queryDetail(pattern: string, rawPath: string): string {\n\tconst path = pathLabel(rawPath);\n\treturn pattern ? `${pattern} in ${path}` : path;\n}\n\nexport const findTool: BoxedToolDefinition = {\n\tcall(args, theme, context) {\n\t\tnoteExecutionStart(context);\n\t\tconst pattern = String(args?.pattern ?? \"\");\n\t\tconst rawPath = String(args?.path ?? \".\");\n\t\tconst detail = queryDetail(pattern, rawPath);\n\t\tconst { isLeader, batch } = registerBatchCall(FIND_META, detail, context, {\n\t\t\tpattern,\n\t\t\tpathLabel: pathLabel(rawPath),\n\t\t});\n\t\tif (!isLeader) return EMPTY_BATCH_COMPONENT;\n\t\treturn renderBatchAwareCall(theme, batch);\n\t},\n\tresult(result, options, _theme, context) {\n\t\tconst output = stripAnsi(getTextOutput(result)).trimEnd();\n\t\tconst entries = context.isError ? undefined : parseFindOutput(output);\n\t\tregisterBatchResult(\n\t\t\tFIND_META,\n\t\t\t{\n\t\t\t\tisPartial: Boolean(options.isPartial),\n\t\t\t\tisError: Boolean(context.isError),\n\t\t\t\terrorText: context.isError ? output || undefined : undefined,\n\t\t\t\t...(entries !== undefined ? { entries } : {}),\n\t\t\t},\n\t\t\tcontext,\n\t\t);\n\t\treturn emptyBatchResult();\n\t},\n};\n","// Boxed ls tool renderer.\n//\n// ls calls render as a boxless tree panel — a lone ls shows its parsed output as\n// a flat `List: <N> files · in <path>` tree; consecutive ls calls group into one\n// panel with per-member nested subtrees (see batch.ts). Pending/failed calls\n// without output fall back to a path row.\n\nimport { stripAnsi } from \"../../../shared/ansi.js\";\nimport { getTextOutput, shortenPath } from \"../../../shared/box.js\";\nimport {\n\ttype BatchToolMeta,\n\tEMPTY_BATCH_COMPONENT,\n\temptyBatchResult,\n\tregisterBatchCall,\n\tregisterBatchResult,\n\trenderBatchAwareCall,\n} from \"./batch.js\";\nimport { parseLsOutput } from \"./output-tree.js\";\nimport { type BoxedToolDefinition, noteExecutionStart } from \"./shared.js\";\n\nconst LIST_META: BatchToolMeta = Object.freeze({\n\ttoolName: \"ls\",\n\tlabel: \"List\",\n\theaderLabel: \"List\",\n});\n\nfunction displayPath(rawPath: string): string {\n\tconst path = String(rawPath ?? \".\");\n\tif (path === \".\" || path === \"\") return \"current directory\";\n\treturn shortenPath(path);\n}\n\nexport const lsTool: BoxedToolDefinition = {\n\tcall(args, theme, context) {\n\t\tnoteExecutionStart(context);\n\t\tconst rawPath = String(args?.path ?? \".\");\n\t\tconst detail = displayPath(rawPath);\n\t\tconst { isLeader, batch } = registerBatchCall(LIST_META, detail, context, { pathLabel: detail });\n\t\tif (!isLeader) return EMPTY_BATCH_COMPONENT;\n\t\treturn renderBatchAwareCall(theme, batch);\n\t},\n\tresult(result, options, _theme, context) {\n\t\tconst output = stripAnsi(getTextOutput(result)).trimEnd();\n\t\tconst entries = context.isError ? undefined : parseLsOutput(output);\n\t\tregisterBatchResult(\n\t\t\tLIST_META,\n\t\t\t{\n\t\t\t\tisPartial: Boolean(options.isPartial),\n\t\t\t\tisError: Boolean(context.isError),\n\t\t\t\terrorText: context.isError ? output || undefined : undefined,\n\t\t\t\t...(entries !== undefined ? { entries } : {}),\n\t\t\t},\n\t\t\tcontext,\n\t\t);\n\t\treturn emptyBatchResult();\n\t},\n};\n","// Boxed quick-edit / substitute-edit / target-edit renderer.\n\nimport { getLanguageFromPath } from \"@earendil-works/pi-coding-agent\";\nimport { stripAnsi } from \"../../../shared/ansi.js\";\nimport {\n\ttype BoxTheme,\n\tformatBoxedRunningStatus,\n\tgetTextOutput,\n\trenderBoxedToolCall,\n\trenderBoxedToolResult,\n} from \"../../../shared/box.js\";\nimport { formatElapsedMs, getElapsedMs } from \"../../../shared/elapsed.js\";\nimport { AdaptiveDiffComponent, buildSplitRows, countDiffStats } from \"../../../shared/split-diff.js\";\nimport { getStateElapsedMs, isResultSeen } from \"./session-config.js\";\nimport {\n\ttype BoxedToolContext,\n\ttype BoxedToolDefinition,\n\tdisplayPath,\n\tnoteBoxedCallState,\n\tnoteBoxedResultPhase,\n\tnoteExecutionStart,\n\tstateElapsedMs,\n} from \"./shared.js\";\n\nconst MAX_HIGHLIGHT_DIFF_CHARS = 12000;\nconst MAX_HIGHLIGHT_DIFF_ROWS = 120;\n\n/** First-partial-pass result: the pending/running call card stands alone. */\nconst EMPTY_QUICK_EDIT_RESULT = Object.freeze({\n\tinvalidate() {},\n\trender() {\n\t\treturn [];\n\t},\n});\n\ninterface QuickEditToolConfig {\n\ttoolLabel: string;\n\tapplyingLabel: string;\n\tfallbackLabel: string;\n}\n\nconst QUICK_EDIT_TOOLS: Readonly<Record<string, QuickEditToolConfig>> = {\n\tquick_edit: {\n\t\ttoolLabel: \"Quick Edit\",\n\t\tapplyingLabel: \"quick-edit\",\n\t\tfallbackLabel: \"Quick edit applied\",\n\t},\n\tsubstitute_edit: {\n\t\ttoolLabel: \"Substitute Edit\",\n\t\tapplyingLabel: \"substitute-edit\",\n\t\tfallbackLabel: \"Substitute edit applied\",\n\t},\n\ttarget_edit: {\n\t\ttoolLabel: \"Target Edit\",\n\t\tapplyingLabel: \"target-edit\",\n\t\tfallbackLabel: \"Target edit applied\",\n\t},\n};\n\nexport function getQuickEditToolConfig(toolName: unknown): QuickEditToolConfig | undefined {\n\treturn typeof toolName === \"string\" ? QUICK_EDIT_TOOLS[toolName] : undefined;\n}\n\nfunction extractQuickEditDiff(text: string): string | undefined {\n\tconst lines = stripAnsi(text).replace(/\\r/g, \"\").split(\"\\n\");\n\tconst start = lines.indexOf(\"── diff ──\");\n\tif (start < 0) return undefined;\n\n\tconst diffLines: string[] = [];\n\tlet cumulativeDelta = 0;\n\tlet oldLine: number | undefined;\n\tlet newLine: number | undefined;\n\tlet chunkAdditions = 0;\n\tlet chunkRemovals = 0;\n\n\tconst finishChunk = () => {\n\t\tcumulativeDelta += chunkAdditions - chunkRemovals;\n\t\toldLine = undefined;\n\t\tnewLine = undefined;\n\t\tchunkAdditions = 0;\n\t\tchunkRemovals = 0;\n\t};\n\n\tfor (const line of lines.slice(start + 1)) {\n\t\tif (line === \"\") {\n\t\t\tfinishChunk();\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst headerMatch = line.match(/^:(\\d+)(?:-\\d+)?$/);\n\t\tif (headerMatch) {\n\t\t\tfinishChunk();\n\t\t\tconst startLine = Number.parseInt(headerMatch[1] ?? \"\", 10);\n\t\t\toldLine = startLine;\n\t\t\tnewLine = startLine + cumulativeDelta;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst match = line.match(/^([+-]) (.*)$/);\n\t\tif (match) {\n\t\t\tconst [, sign, content = \"\"] = match;\n\t\t\tlet gutter = \"\";\n\t\t\tif (sign === \"-\" && oldLine !== undefined) gutter = String(oldLine++);\n\t\t\tif (sign === \"+\" && newLine !== undefined) gutter = String(newLine++);\n\t\t\tif (!gutter) continue;\n\t\t\tif (sign === \"-\") chunkRemovals++;\n\t\t\tif (sign === \"+\") chunkAdditions++;\n\t\t\tdiffLines.push(`${sign} ${gutter} ${content}`);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (line === \"---\") break;\n\t}\n\n\treturn diffLines.length > 0 ? diffLines.join(\"\\n\") : undefined;\n}\n\n/** `Diff · +3 -0` divider label. */\nfunction quickEditDividerLabel(theme: BoxTheme, stats: { additions: number; removals: number }): string {\n\tconst plus = stats.additions > 0 ? theme.fg(\"toolDiffAdded\", `+${stats.additions}`) : theme.fg(\"dim\", \"+0\");\n\tconst minus = stats.removals > 0 ? theme.fg(\"toolDiffRemoved\", `-${stats.removals}`) : theme.fg(\"dim\", \"-0\");\n\treturn `Diff · ${plus} ${minus}`;\n}\n\n/** Quick-edit footer: `1 file · +3 -0`, prefixed with elapsed time when known. */\nfunction quickEditDiffFooter(\n\ttheme: BoxTheme,\n\tresult: { content?: readonly unknown[]; details?: unknown },\n\tcontext: BoxedToolContext,\n\tstats: { additions: number; removals: number },\n): string {\n\tconst elapsedMs = getElapsedMs(result) ?? getStateElapsedMs(context.state);\n\tconst parts: string[] = [];\n\tif (elapsedMs !== undefined) parts.push(theme.fg(\"text\", formatElapsedMs(elapsedMs)));\n\tconst plus = stats.additions > 0 ? theme.fg(\"toolDiffAdded\", `+${stats.additions}`) : theme.fg(\"dim\", \"+0\");\n\tconst minus = stats.removals > 0 ? theme.fg(\"toolDiffRemoved\", `-${stats.removals}`) : theme.fg(\"dim\", \"-0\");\n\tparts.push(theme.fg(\"dim\", \"1 file\"), `${plus} ${minus}`);\n\treturn parts.join(theme.fg(\"dim\", \" · \"));\n}\n\nfunction renderQuickEditResult(\n\t_toolName: string,\n\tresult: { content?: readonly unknown[]; details?: unknown },\n\toptions: { expanded: boolean; isPartial: boolean },\n\ttheme: BoxTheme,\n\tcontext: BoxedToolContext,\n\tconfig: QuickEditToolConfig,\n) {\n\tif (options.isPartial) {\n\t\tconst firstResultPass = noteBoxedResultPhase(context, options.isPartial);\n\t\tif (firstResultPass) return EMPTY_QUICK_EDIT_RESULT;\n\t\treturn renderBoxedToolResult(\n\t\t\ttheme,\n\t\t\t() => [`${theme.fg(\"dim\", \"↳\")} ${theme.fg(\"muted\", `Applying ${config.applyingLabel}...`)}`],\n\t\t\t{ showDivider: false, footerLines: [formatBoxedRunningStatus(theme, stateElapsedMs(context))], isPartial: true },\n\t\t);\n\t}\n\n\tconst output = getTextOutput(result);\n\tif (context.isError) {\n\t\treturn renderBoxedToolResult(theme, () => [theme.fg(\"error\", stripAnsi(output).trim() || \"Error\")], {\n\t\t\tfooterLines: [quickEditFooter(theme, context)],\n\t\t\tisError: true,\n\t\t});\n\t}\n\n\tconst diff = extractQuickEditDiff(output);\n\tif (!diff) {\n\t\tconst fallback = stripAnsi(output).trim() || config.fallbackLabel;\n\t\treturn renderBoxedToolResult(theme, () => [`${theme.fg(\"dim\", \"↳\")} ${theme.fg(\"muted\", fallback)}`], {\n\t\t\tfooterLines: [quickEditFooter(theme, context)],\n\t\t});\n\t}\n\n\tconst rows = buildSplitRows(diff);\n\tconst expanded = options.expanded;\n\tconst argPath = String(context?.args?.path ?? \"\");\n\tconst language = argPath ? getLanguageFromPath(argPath) : undefined;\n\tconst shouldHighlight =\n\t\tBoolean(language) && diff.length <= MAX_HIGHLIGHT_DIFF_CHARS && rows.length <= MAX_HIGHLIGHT_DIFF_ROWS;\n\tconst stats = countDiffStats(diff);\n\n\tconst maxRows = expanded ? 160 : 36;\n\tconst diffView = new AdaptiveDiffComponent(theme, rows, maxRows, shouldHighlight ? language : undefined);\n\tconst expandHint = !expanded && diffView.hasCollapsed() ? \"Ctrl+O more\" : undefined;\n\n\treturn renderBoxedToolResult(\n\t\ttheme,\n\t\t{\n\t\t\trender(width: number): string[] {\n\t\t\t\treturn diffView.render(width);\n\t\t\t},\n\t\t\tinvalidate(): void {\n\t\t\t\tdiffView.invalidate();\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdividerLabel: quickEditDividerLabel(theme, stats),\n\t\t\t...(expandHint ? { dividerRightLabel: expandHint } : {}),\n\t\t\tfooterLines: [quickEditDiffFooter(theme, result, context, stats)],\n\t\t},\n\t);\n}\n\nfunction quickEditFooter(theme: BoxTheme, context: BoxedToolContext): string {\n\tconst elapsedMs = getStateElapsedMs(context.state);\n\tconst parts: string[] = [];\n\tif (elapsedMs !== undefined) parts.push(theme.fg(\"text\", formatElapsedMs(elapsedMs)));\n\tparts.push(theme.fg(\"dim\", \"1 file\"));\n\treturn parts.join(theme.fg(\"dim\", \" · \"));\n}\n\nexport function quickEditTool(config: QuickEditToolConfig): BoxedToolDefinition {\n\treturn {\n\t\tcall(args, theme, context) {\n\t\t\tnoteExecutionStart(context);\n\t\t\tnoteBoxedCallState(context);\n\t\t\tconst detail = displayPath(String(args?.path ?? \"\"), context);\n\t\t\treturn renderBoxedToolCall(theme, config.toolLabel, [], {\n\t\t\t\theaderDetail: detail,\n\t\t\t\tisError: Boolean(context.isError),\n\t\t\t\tisPartial: Boolean(context.isPartial),\n\t\t\t\tisPending: Boolean(context.isPartial),\n\t\t\t\trunning: Boolean(context.executionStarted),\n\t\t\t\tresultSeen: isResultSeen(context.state),\n\t\t\t});\n\t\t},\n\t\tresult(result, options, theme, context) {\n\t\t\treturn renderQuickEditResult(config.toolLabel, result, options, theme, context, config);\n\t\t},\n\t};\n}\n","// Boxed read tool renderer\n// (renderCall/renderResult only; no tool re-registration).\n//\n// Read calls render boxless: a lone read is a single inline line\n// (`➔ Read <path>`), consecutive reads group into one tree panel (see\n// batch.ts).\n\nimport { stripAnsi } from \"../../../shared/ansi.js\";\nimport { getTextOutput } from \"../../../shared/box.js\";\nimport {\n\ttype BatchToolMeta,\n\tEMPTY_BATCH_COMPONENT,\n\temptyBatchResult,\n\tregisterBatchCall,\n\tregisterBatchResult,\n\trenderBatchAwareCall,\n} from \"./batch.js\";\nimport { type BoxedToolDefinition, noteExecutionStart, pathRangeDetail } from \"./shared.js\";\n\nconst READ_META: BatchToolMeta = Object.freeze({\n\ttoolName: \"read\",\n\tlabel: \"Read\",\n});\n\nexport const readTool: BoxedToolDefinition = {\n\tcall(args, theme, context) {\n\t\tnoteExecutionStart(context);\n\t\tconst rawPath = String(args?.path ?? args?.file_path ?? \"\");\n\t\tconst detail = pathRangeDetail(rawPath, args?.offset, args?.limit, context);\n\t\tconst { isLeader, batch } = registerBatchCall(READ_META, detail, context);\n\t\tif (!isLeader) return EMPTY_BATCH_COMPONENT;\n\t\treturn renderBatchAwareCall(theme, batch);\n\t},\n\tresult(result, options, _theme, context) {\n\t\tconst output = stripAnsi(getTextOutput(result)).trimEnd();\n\t\tregisterBatchResult(\n\t\t\tREAD_META,\n\t\t\t{\n\t\t\t\tisPartial: Boolean(options.isPartial),\n\t\t\t\tisError: Boolean(context.isError),\n\t\t\t\terrorText: context.isError ? output || undefined : undefined,\n\t\t\t},\n\t\t\tcontext,\n\t\t);\n\t\treturn emptyBatchResult();\n\t},\n};\n","// Boxed write tool renderer\n// (renderCall/renderResult only).\n//\n// The write call renders a compact preview box: the file path in the top\n// border, the written content as numbered lines in the body (cat -n style),\n// and the metrics footer in the bottom border. The footer lives in the shared\n// renderer state — the result renderer stores it (elapsed + words), the call\n// component reads it at paint time and closes the box. The preview is capped\n// at the collapsed line budget with a `Ctrl+O for more` hint on the bottom\n// border when truncated; expanded shows the expanded budget. Errors keep the\n// plain open call box so the boxed error result never duplicates a box.\n\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport { stripAnsi } from \"../../../shared/ansi.js\";\nimport {\n\ttype BoxTheme,\n\tboxedToolWidthKey,\n\tdimLine,\n\tgetTextOutput,\n\trenderBoxedToolResult,\n\trenderCompactBoxedToolCall,\n\treplaceTabs,\n} from \"../../../shared/box.js\";\nimport { getToolsRenderConfig } from \"./session-config.js\";\nimport {\n\ttype BoxedToolDefinition,\n\tclearFooterState,\n\tcompactCall,\n\tcompactFooterWithState,\n\tdisplayPath,\n\tnoteExecutionStart,\n\tresultFooterLines,\n} from \"./shared.js\";\n\n/** Right-side bottom-border hint shown when the compact preview is truncated. */\nconst WRITE_EXPAND_HINT = \"Ctrl+O for more\";\n\n/** Partial-pass result: the compact call keeps its `◌ Running` card. */\nconst EMPTY_WRITE_RESULT: Component = Object.freeze({\n\tinvalidate() {},\n\trender() {\n\t\treturn [];\n\t},\n});\n\ntype NumberedLine = { number: string; content: string };\n\n/**\n * Numbered preview lines for the written content, `cat -n` style: every split\n * line keeps its number (including a trailing empty line produced by a final\n * newline), right-aligned to the widest line number.\n */\nfunction numberedPreviewLines(content: string): NumberedLine[] {\n\tconst normalized = replaceTabs(String(content ?? \"\")).replace(/\\r/g, \"\");\n\tif (!normalized) return [];\n\tconst lines = normalized.split(\"\\n\");\n\tconst gutterWidth = Math.max(1, String(lines.length).length);\n\treturn lines.map((line, index) => ({\n\t\tnumber: String(index + 1).padStart(gutterWidth),\n\t\tcontent: line,\n\t}));\n}\n\n/** One boxed preview row: dim gutter + toolOutput content. */\nfunction formatNumberedLine(theme: BoxTheme, line: NumberedLine): string {\n\treturn `${dimLine(`${line.number} `)}${theme.fg(\"toolOutput\", line.content)}`;\n}\n\n/** Compact write box: path header, numbered content preview, metrics footer. */\nfunction renderWritePreviewBox(\n\ttheme: BoxTheme,\n\tdetailLine: string,\n\tcontent: string,\n\toptions: {\n\t\tstate?: Record<string, unknown>;\n\t\tisError: boolean;\n\t\tisPending: boolean;\n\t\trunning?: boolean;\n\t\texpanded: boolean;\n\t},\n): Component {\n\tconst preview = numberedPreviewLines(content);\n\tconst config = getToolsRenderConfig();\n\tconst budget = options.expanded ? config.maxExpandedLines : config.maxCollapsedLines;\n\tconst truncated = preview.length > budget;\n\n\treturn renderCompactBoxedToolCall(theme, \"Write\", detailLine, {\n\t\t...(options.state ? { state: options.state } : {}),\n\t\tisError: options.isError,\n\t\tisPending: options.isPending,\n\t\trunning: Boolean(options.running),\n\t\tbodyLines: () => {\n\t\t\tif (preview.length === 0) return [];\n\t\t\tconst shown = preview.slice(0, budget).map((line) => formatNumberedLine(theme, line));\n\t\t\tif (!truncated) return shown;\n\t\t\tconst omitted = preview.length - budget;\n\t\t\tconst note = options.expanded ? `… ${omitted} more lines omitted by render budget` : `… ${omitted} more lines`;\n\t\t\treturn [...shown, theme.fg(\"muted\", note)];\n\t\t},\n\t\t...(options.expanded || options.isPending || !truncated ? {} : { bottomRightLabel: WRITE_EXPAND_HINT }),\n\t});\n}\n\nexport const writeTool: BoxedToolDefinition = {\n\tcall(args, theme, context) {\n\t\tnoteExecutionStart(context);\n\t\tconst detail = displayPath(String(args?.path ?? args?.file_path ?? \"\"), context);\n\t\tconst detailLine = `${theme.fg(\"dim\", \"Path: \")}${detail}`;\n\t\t// On error keep the plain open box: the result renderer continues it with\n\t\t// the boxed error body, so call and result never duplicate a box.\n\t\tif (context.isError) {\n\t\t\treturn compactCall(theme, \"Write\", detailLine, {\n\t\t\t\tdetailKey: detail,\n\t\t\t\tcontext,\n\t\t\t});\n\t\t}\n\t\treturn renderWritePreviewBox(theme, detailLine, String(args?.content ?? \"\"), {\n\t\t\tstate: context.state,\n\t\t\tisError: Boolean(context.isError),\n\t\t\tisPending: Boolean(context.isPartial),\n\t\t\trunning: Boolean(context.executionStarted),\n\t\t\texpanded: Boolean(context.expanded),\n\t\t});\n\t},\n\tresult(result, options, theme, context) {\n\t\tclearFooterState(context);\n\t\tconst output = getTextOutput(result);\n\t\tconst detail = displayPath(String(context?.args?.path ?? context?.args?.file_path ?? \"\"), context);\n\t\tconst widthKey = boxedToolWidthKey(\"Write\", detail);\n\n\t\tif (context.isError) {\n\t\t\treturn renderBoxedToolResult(theme, () => [theme.fg(\"error\", stripAnsi(output).trim() || \"Error\")], {\n\t\t\t\twidthKey,\n\t\t\t\tfooterLines: resultFooterLines(theme, result, context),\n\t\t\t\tisError: true,\n\t\t\t});\n\t\t}\n\n\t\t// While the result is still streaming, don't stamp a metrics footer into\n\t\t// the shared state: the compact call keeps its `◌ Running` card and only\n\t\t// closes with `elapsed · words` once the tool settles.\n\t\tif (options.isPartial) return EMPTY_WRITE_RESULT;\n\n\t\t// Success (compact and expanded): the preview box closes with the metrics\n\t\t// footer stored into the shared renderer state; the result adds nothing.\n\t\treturn compactFooterWithState(theme, result, context);\n\t},\n};\n","// Boxed tool renderer dispatcher.\n//\n// Maps Pi tool names to their boxed call/result renderers and falls back to a\n// boxed generic renderer for unknown tools. The dispatcher is invoked from the\n// tool decoration owner when tools.style === \"compact-box\".\n\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport type { BoxTheme } from \"../../../shared/box.js\";\nimport { bashTool } from \"./bash.js\";\nimport { closeActiveBatch, isBatchableTool } from \"./batch.js\";\nimport { editTool } from \"./edit.js\";\nimport { renderFallbackCall, renderFallbackResult } from \"./fallback.js\";\nimport { findTool } from \"./find.js\";\nimport { grepTool } from \"./grep.js\";\nimport { lsTool } from \"./ls.js\";\nimport { getQuickEditToolConfig, quickEditTool } from \"./quick-edit.js\";\nimport { readTool } from \"./read.js\";\nimport type { BoxedToolContext, BoxedToolDefinition } from \"./shared.js\";\nimport { writeTool } from \"./write.js\";\n\nfunction quickEditToolFor(toolName: string): BoxedToolDefinition {\n\tconst config = getQuickEditToolConfig(toolName);\n\tif (!config) throw new Error(`missing quick-edit config for ${toolName}`);\n\treturn quickEditTool(config);\n}\n\nconst REGISTRY: Readonly<Record<string, BoxedToolDefinition>> = {\n\tread: readTool,\n\twrite: writeTool,\n\tedit: editTool,\n\tbash: bashTool,\n\tls: lsTool,\n\tfind: findTool,\n\tgrep: grepTool,\n\tquick_edit: quickEditToolFor(\"quick_edit\"),\n\tsubstitute_edit: quickEditToolFor(\"substitute_edit\"),\n\ttarget_edit: quickEditToolFor(\"target_edit\"),\n};\n\nexport function hasBoxedRenderer(toolName: unknown): boolean {\n\treturn typeof toolName === \"string\" && Object.hasOwn(REGISTRY, toolName);\n}\n\nexport function renderBoxedToolCall(\n\ttoolName: unknown,\n\targs: Record<string, unknown>,\n\ttheme: BoxTheme,\n\tcontext: BoxedToolContext,\n): Component {\n\t// Any non-batchable tool call is a batch boundary: the next quiet call starts\n\t// a fresh batch instead of joining the previous one.\n\tif (!isBatchableTool(toolName)) closeActiveBatch();\n\tconst tool = typeof toolName === \"string\" ? REGISTRY[toolName] : undefined;\n\tif (tool) return tool.call(args, theme, context);\n\treturn renderFallbackCall(toolName, args, theme, context);\n}\n\nexport function renderBoxedToolResult(\n\ttoolName: unknown,\n\tresult: { content?: readonly unknown[]; details?: unknown },\n\toptions: { expanded: boolean; isPartial: boolean },\n\ttheme: BoxTheme,\n\tcontext: BoxedToolContext,\n): Component {\n\tconst tool = typeof toolName === \"string\" ? REGISTRY[toolName] : undefined;\n\tif (tool) return tool.result(result, options, theme, context);\n\treturn renderFallbackResult(toolName, result, options, theme, context);\n}\n","export type CompatibilitySubtype =\n\t| \"native-assistant-message\"\n\t| \"native-compaction-message\"\n\t| \"native-branch-message\"\n\t| \"native-skill-message\"\n\t| \"native-custom-message\"\n\t| \"tool-call-renderer\"\n\t| \"tool-result-renderer\"\n\t| \"native-bash-execution\";\n\ntype CompatibilityShape = \"supported\" | \"unsupported\" | \"conflict\" | \"installed\" | \"skipped\";\n\nexport interface CompatibilityRecord {\n\tfeature: \"messages\" | \"tools\";\n\tsubtype: CompatibilitySubtype;\n\ttarget: object;\n\towner: object;\n\tmethod: PropertyKey;\n\toriginalIdentity: unknown;\n\toriginalDescriptor?: PropertyDescriptor;\n\tinstalledIdentity?: unknown;\n\tpiVersion: string;\n\tversionRange: string;\n\tshape: CompatibilityShape;\n\tdiagnostic?: string | undefined;\n\tgeneration: number;\n\tdisposed: boolean;\n\tdisposer: () => void;\n}\n\nexport interface InstallResult {\n\tstatus: \"installed\" | \"already-installed\" | \"skipped\";\n\trecord: CompatibilityRecord;\n\treason?: string | undefined;\n}\n\nconst recordsByOwner = new WeakMap<object, Map<PropertyKey, CompatibilityRecord>>();\nlet generation = 0;\nlet registryTestHooks: {\n\tafterWrite?: () => void;\n\tdefineProperty?: (target: object, key: PropertyKey, descriptor: PropertyDescriptor) => boolean;\n} = {};\nexport function __setCompatibilityRegistryTestHooks(hooks: typeof registryTestHooks): () => void {\n\tconst previous = registryTestHooks;\n\tregistryTestHooks = hooks;\n\treturn () => {\n\t\tregistryTestHooks = previous;\n\t};\n}\n\nfunction ownerRecords(owner: object): Map<PropertyKey, CompatibilityRecord> {\n\tlet records = recordsByOwner.get(owner);\n\tif (!records) {\n\t\trecords = new Map();\n\t\trecordsByOwner.set(owner, records);\n\t}\n\treturn records;\n}\n\nexport function currentGeneration(): number {\n\treturn generation;\n}\nexport function nextGeneration(): number {\n\treturn ++generation;\n}\nexport function getCompatibilityRecords(owner: object): readonly CompatibilityRecord[] {\n\treturn [...(recordsByOwner.get(owner)?.values() ?? [])];\n}\n\nfunction safeRead(target: object, method: PropertyKey): unknown {\n\ttry {\n\t\treturn Reflect.get(target, method);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction skippedRecord(options: {\n\tfeature: CompatibilityRecord[\"feature\"];\n\tsubtype: CompatibilitySubtype;\n\ttarget: object;\n\tmethod: PropertyKey;\n\tpiVersion: string;\n\tversionRange: string;\n\tshape: CompatibilityShape;\n\tdiagnostic: string;\n\tgeneration: number;\n\toriginalIdentity?: unknown;\n}): CompatibilityRecord {\n\treturn {\n\t\t...options,\n\t\towner: options.target,\n\t\toriginalIdentity: Object.hasOwn(options, \"originalIdentity\")\n\t\t\t? options.originalIdentity\n\t\t\t: safeRead(options.target, options.method),\n\t\tdisposed: true,\n\t\tdisposer: () => {},\n\t};\n}\n\nfunction descriptorMatches(actual: PropertyDescriptor | undefined, expected: PropertyDescriptor | undefined): boolean {\n\tif (!actual || !expected) return actual === expected;\n\treturn (\n\t\tactual.value === expected.value &&\n\t\tactual.get === expected.get &&\n\t\tactual.set === expected.set &&\n\t\tactual.writable === expected.writable &&\n\t\tactual.enumerable === expected.enumerable &&\n\t\tactual.configurable === expected.configurable\n\t);\n}\n\nfunction restoreExact(record: CompatibilityRecord): { ok: boolean; diagnostic?: string } {\n\ttry {\n\t\tconst current = Object.getOwnPropertyDescriptor(record.target, record.method);\n\t\tconst installed = current?.value === record.installedIdentity;\n\t\tif (!installed) return { ok: false, diagnostic: \"current owner changed; native/later owner preserved\" };\n\t\tconst defineProperty = registryTestHooks.defineProperty ?? Reflect.defineProperty;\n\t\tconst wrote = record.originalDescriptor\n\t\t\t? defineProperty(record.target, record.method, record.originalDescriptor)\n\t\t\t: Reflect.deleteProperty(record.target, record.method);\n\t\tif (!wrote) return { ok: false, diagnostic: \"exact descriptor restoration was rejected\" };\n\t\tif (!descriptorMatches(Object.getOwnPropertyDescriptor(record.target, record.method), record.originalDescriptor))\n\t\t\treturn { ok: false, diagnostic: \"post-restore descriptor validation failed\" };\n\t\treturn { ok: true };\n\t} catch (error) {\n\t\treturn { ok: false, diagnostic: `restore failed: ${error instanceof Error ? error.message : String(error)}` };\n\t}\n}\n\nfunction inspectCurrent(\n\ttarget: object,\n\tmethod: PropertyKey,\n): { current?: unknown; descriptor?: PropertyDescriptor; error?: string } {\n\ttry {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(target, method);\n\t\treturn {\n\t\t\tcurrent: descriptor && \"value\" in descriptor ? descriptor.value : undefined,\n\t\t\t...(descriptor ? { descriptor } : {}),\n\t\t};\n\t} catch (error) {\n\t\treturn { error: `cannot inspect target: ${error instanceof Error ? error.message : String(error)}` };\n\t}\n}\n\nfunction skippedResult(\n\toptions: Parameters<typeof installDelegatingPatch>[0],\n\tshape: CompatibilityShape,\n\treason: string,\n\toriginalIdentity?: unknown,\n): InstallResult {\n\treturn {\n\t\tstatus: \"skipped\",\n\t\treason,\n\t\trecord: skippedRecord({ ...options, shape, diagnostic: reason, originalIdentity }),\n\t};\n}\n\nfunction expectedIdentityMatches(options: Parameters<typeof installDelegatingPatch>[0], current: unknown): boolean {\n\tconst expected =\n\t\toptions.hasExpectedIdentity === true ||\n\t\t(options.hasExpectedIdentity === undefined && options.expectedIdentity !== undefined);\n\treturn !expected || current === options.expectedIdentity;\n}\n\nfunction validateInstall(\n\toptions: Parameters<typeof installDelegatingPatch>[0],\n\tcurrent: unknown,\n\texisting: CompatibilityRecord | undefined,\n\townDescriptor: PropertyDescriptor | undefined,\n): InstallResult | undefined {\n\tif (!options.shape) return skippedResult(options, \"unsupported\", options.diagnostic ?? \"unsupported shape\", current);\n\tconst conflict = existing && activeConflict(existing, current, options.generation);\n\tif (conflict) return conflict;\n\tif (options.kind === \"add-method\") {\n\t\t// Additive install: the slot must be unowned (the method is inherited); the\n\t\t// delegate receives the inherited native function as its fallback identity.\n\t\tif (current !== undefined || ownDescriptor !== undefined)\n\t\t\treturn skippedResult(options, \"conflict\", \"target already owns the additive method\", current);\n\t\treturn undefined;\n\t}\n\tif (typeof current !== \"function\")\n\t\treturn skippedResult(\n\t\t\toptions,\n\t\t\townDescriptor ? \"unsupported\" : \"skipped\",\n\t\t\t\"target property is not callable\",\n\t\t\tcurrent,\n\t\t);\n\tif (!expectedIdentityMatches(options, current))\n\t\treturn skippedResult(options, \"conflict\", \"current owner is not the captured pristine native identity\", current);\n\treturn undefined;\n}\n\nfunction activeConflict(\n\texisting: CompatibilityRecord,\n\tcurrent: unknown,\n\tgeneration: number,\n): InstallResult | undefined {\n\tif (existing.disposed) return undefined;\n\tif (existing.installedIdentity === current && existing.generation === generation)\n\t\treturn { status: \"already-installed\", record: existing };\n\tconst reason =\n\t\texisting.installedIdentity === current\n\t\t\t? \"active wrapper belongs to a different generation\"\n\t\t\t: \"owner changed after pi-style installation\";\n\treturn {\n\t\tstatus: \"skipped\",\n\t\treason,\n\t\trecord: skippedRecord({\n\t\t\tfeature: existing.feature,\n\t\t\tsubtype: existing.subtype,\n\t\t\ttarget: existing.target,\n\t\t\tmethod: existing.method,\n\t\t\tpiVersion: existing.piVersion,\n\t\t\tversionRange: existing.versionRange,\n\t\t\tshape: \"conflict\",\n\t\t\tdiagnostic: reason,\n\t\t\tgeneration,\n\t\t\toriginalIdentity: current,\n\t\t}),\n\t};\n}\n\nexport function installDelegatingPatch(options: {\n\tfeature: CompatibilityRecord[\"feature\"];\n\tsubtype: CompatibilitySubtype;\n\ttarget: object;\n\tmethod: PropertyKey;\n\tpiVersion: string;\n\tversionRange: string;\n\tshape: boolean;\n\tgeneration: number;\n\texpectedIdentity?: unknown;\n\thasExpectedIdentity?: boolean;\n\tdiagnostic?: string | undefined;\n\t/** \"add-method\" installs a new own method on the prototype (nothing may already own the slot); the delegate receives the inherited native function as the fallback. */\n\tkind?: \"method\" | \"add-method\";\n\tdelegate: (original: unknown, thisArg: object, args: unknown[]) => unknown;\n}): InstallResult {\n\tconst { target, method } = options;\n\tconst inspection = inspectCurrent(target, method);\n\tif (inspection.error) return skippedResult(options, \"skipped\", inspection.error);\n\tconst current = inspection.current;\n\tconst records = ownerRecords(target);\n\tconst validation = validateInstall(options, current, records.get(method), inspection.descriptor);\n\tif (validation) return validation;\n\tconst originalDescriptor = Object.getOwnPropertyDescriptor(target, method);\n\t// Additive installs have no current owner; the captured inherited native\n\t// function (expectedIdentity) is both the fallback and the delegate's original.\n\tconst originalIdentity = options.kind === \"add-method\" ? options.expectedIdentity : current;\n\tlet active = true;\n\tconst installed = function (this: object, ...args: unknown[]): unknown {\n\t\tif (!active) return Reflect.apply(originalIdentity as (...values: unknown[]) => unknown, this, args);\n\t\treturn options.delegate(originalIdentity, this, args);\n\t};\n\tconst record: CompatibilityRecord = {\n\t\tfeature: options.feature,\n\t\tsubtype: options.subtype,\n\t\ttarget,\n\t\towner: target,\n\t\tmethod,\n\t\toriginalIdentity,\n\t\t...(originalDescriptor ? { originalDescriptor } : {}),\n\t\tinstalledIdentity: installed,\n\t\tpiVersion: options.piVersion,\n\t\tversionRange: options.versionRange,\n\t\tshape: \"installed\",\n\t\tdiagnostic: options.diagnostic,\n\t\tgeneration: options.generation,\n\t\tdisposed: false,\n\t\tdisposer: () => {},\n\t};\n\ttry {\n\t\tObject.defineProperty(installed, \"__piStyleCompatibilityRecord\", { value: record, configurable: false });\n\t\t// Additive installs have no original descriptor; write a fresh writable,\n\t\t// configurable, non-enumerable own method so the slot stays reversible.\n\t\tconst descriptor = originalDescriptor\n\t\t\t? { ...originalDescriptor, value: installed }\n\t\t\t: { value: installed, writable: true, enumerable: false, configurable: true };\n\t\tconst wrote = Reflect.defineProperty(target, method, descriptor);\n\t\tregistryTestHooks.afterWrite?.();\n\t\tconst currentDescriptor = Object.getOwnPropertyDescriptor(target, method);\n\t\tif (!wrote) return skippedResult(options, \"skipped\", \"installation write was rejected\");\n\t\tif (!descriptorMatches(currentDescriptor, descriptor)) {\n\t\t\tif (currentDescriptor?.value === installed) {\n\t\t\t\tconst rollback = restoreExact({ ...record, installedIdentity: installed });\n\t\t\t\tif (!rollback.ok) {\n\t\t\t\t\trecord.diagnostic = rollback.diagnostic;\n\t\t\t\t\trecords.set(method, record);\n\t\t\t\t\treturn { status: \"skipped\", reason: rollback.diagnostic, record };\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst reason =\n\t\t\t\tcurrentDescriptor?.value === installed\n\t\t\t\t\t? \"wrapper-owned descriptor mismatch rolled back\"\n\t\t\t\t\t: \"later owner preserved after post-write mismatch\";\n\t\t\treturn {\n\t\t\t\tstatus: \"skipped\",\n\t\t\t\treason,\n\t\t\t\trecord: skippedRecord({\n\t\t\t\t\t...options,\n\t\t\t\t\tshape: \"conflict\",\n\t\t\t\t\tdiagnostic: reason,\n\t\t\t\t\toriginalIdentity: currentDescriptor?.value,\n\t\t\t\t}),\n\t\t\t};\n\t\t}\n\t\trecords.set(method, record);\n\t\trecord.disposer = () => {\n\t\t\tif (record.disposed) return;\n\t\t\tconst restored = restoreExact(record);\n\t\t\tif (!restored.ok) {\n\t\t\t\trecord.diagnostic = restored.diagnostic;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tactive = false;\n\t\t\trecord.disposed = true;\n\t\t\trecords.delete(method);\n\t\t};\n\t\treturn { status: \"installed\", record };\n\t} catch (error) {\n\t\tconst currentDescriptor = Object.getOwnPropertyDescriptor(target, method);\n\t\tconst rollback =\n\t\t\tcurrentDescriptor?.value === installed ? restoreExact({ ...record, installedIdentity: installed }) : { ok: true };\n\t\tconst reason = `installation rolled back (${rollback.diagnostic ?? \"ok\"}): ${error instanceof Error ? error.message : String(error)}`;\n\t\tif (currentDescriptor?.value === installed && !rollback.ok) {\n\t\t\trecord.diagnostic = reason;\n\t\t\trecords.set(method, record);\n\t\t\trecord.disposer = () => {\n\t\t\t\tif (record.disposed) return;\n\t\t\t\tconst retry = restoreExact(record);\n\t\t\t\tif (!retry.ok) {\n\t\t\t\t\trecord.diagnostic = retry.diagnostic;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tactive = false;\n\t\t\t\trecord.disposed = true;\n\t\t\t\trecords.delete(method);\n\t\t\t};\n\t\t\treturn { status: \"installed\", reason, record };\n\t\t}\n\t\treturn { status: \"skipped\", reason, record: skippedRecord({ ...options, shape: \"skipped\", diagnostic: reason }) };\n\t}\n}\n","import { isTierCAuthorized } from \"../domain/config-authorization.js\";\nimport type { NormalizedPiStyleConfig } from \"../domain/config-types.js\";\nimport {\n\ttype CompatibilityCleanupResult,\n\ttype CompatibilityProbeReport,\n\tdetectPiVersion,\n\tdisposePiCompatibilityProbe,\n\tprobePiCompatibility,\n} from \"./compatibility-probe.js\";\n\nexport interface CompatibilityCoordinator {\n\tcaptureAuthorization(\n\t\tcoreFlag: boolean,\n\t\tassistantFlag: boolean,\n\t\tspecialBlocksFlag: boolean,\n\t\ttoolsFlag: boolean,\n\t\tasciiFlag: boolean,\n\t): void;\n\tstate(config: NormalizedPiStyleConfig): Readonly<Record<string, unknown>>;\n\tinstall(\n\t\tconfig: NormalizedPiStyleConfig,\n\t\ttui: boolean,\n\t\tproductGate?: \"omitted\" | \"allow\" | \"deny\",\n\t): CompatibilityProbeReport | undefined;\n\tdispose(): CompatibilityCleanupResult;\n\treadonly report: CompatibilityProbeReport | undefined;\n}\n\nexport function createCompatibilityCoordinator(dispose = disposePiCompatibilityProbe): CompatibilityCoordinator {\n\tlet report: CompatibilityProbeReport | undefined;\n\tlet cleanupPending = false;\n\tlet authorization:\n\t\t| {\n\t\t\t\tcore: boolean;\n\t\t\t\tassistant: boolean;\n\t\t\t\tspecialBlocks: boolean;\n\t\t\t\ttools: boolean;\n\t\t\t\tascii: boolean;\n\t\t }\n\t\t| undefined;\n\treturn {\n\t\tget report() {\n\t\t\treturn report;\n\t\t},\n\t\tcaptureAuthorization(core, assistant, specialBlocks, tools, ascii) {\n\t\t\tauthorization = { core, assistant, specialBlocks, tools, ascii };\n\t\t},\n\t\tstate(config) {\n\t\t\tconst version = detectPiVersion();\n\t\t\tconst messagesConfigured =\n\t\t\t\tconfig.enabled && config.messages.enabled && (config.messages.assistantPrefix || config.messages.specialBlocks);\n\t\t\tconst toolsConfigured = config.enabled && config.tools.enabled;\n\t\t\tconst surface = (\n\t\t\t\tfeature: \"messages\" | \"tools\",\n\t\t\t\tconfigured: boolean,\n\t\t\t\tsurfaceAuthorized: boolean,\n\t\t\t\tsubtype?: string,\n\t\t\t) => {\n\t\t\t\tconst records =\n\t\t\t\t\treport?.unsupported.filter((item) =>\n\t\t\t\t\t\tfeature === \"messages\" ? item.subtype.includes(\"message\") : item.subtype.includes(\"tool\"),\n\t\t\t\t\t) ?? [];\n\t\t\t\tconst failed = records.some((item) => /identity|failed|unsupported shape/i.test(item.reason));\n\t\t\t\tconst fallback = records.some((item) => /fallback|authorization|disabled/i.test(item.reason));\n\t\t\t\tconst authorized = Boolean(authorization?.core && surfaceAuthorized);\n\t\t\t\tconst installedRecord = report?.recordSnapshots.some(\n\t\t\t\t\t(item) => item.feature === feature && !item.disposed && (subtype === undefined || item.subtype === subtype),\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tconfigured,\n\t\t\t\t\tauthorized,\n\t\t\t\t\tinstalled: Boolean(installedRecord && !failed && authorized && configured),\n\t\t\t\t\tconflicted: records.some((item) => item.reason.includes(\"owner\")),\n\t\t\t\t\tfailed,\n\t\t\t\t\tcleanupPending,\n\t\t\t\t\tnativeFallback: fallback,\n\t\t\t\t\t...(authorized ? {} : { awaitingAuthorization: true }),\n\t\t\t\t};\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tconfigured: messagesConfigured || toolsConfigured,\n\t\t\t\tauthorized: authorization?.core ?? false,\n\t\t\t\tinstalled: report !== undefined,\n\t\t\t\tconflicted: report?.unsupported.some((item) => item.reason.includes(\"identity\")) ?? false,\n\t\t\t\tfailed: report?.unsupported.some((item) => item.reason.includes(\"failed\")) ?? false,\n\t\t\t\tcleanupPending,\n\t\t\t\tnativeFallbacks: report?.unsupported.filter((item) => item.reason.includes(\"fallback\")).length ?? 0,\n\t\t\t\tpiVersion: version.version ?? report?.piVersion ?? \"unknown\",\n\t\t\t\tversionRange: report?.versionRange ?? \">=0.83.0 <0.84.0\",\n\t\t\t\tassistantMessage: surface(\n\t\t\t\t\t\"messages\",\n\t\t\t\t\tconfig.enabled && config.messages.enabled && config.messages.assistantPrefix,\n\t\t\t\t\tBoolean(authorization?.assistant),\n\t\t\t\t\t\"native-assistant-message\",\n\t\t\t\t),\n\t\t\t\ttools: surface(\"tools\", config.enabled && config.tools.enabled, Boolean(authorization?.tools)),\n\t\t\t\tspecialBlocks: surface(\n\t\t\t\t\t\"messages\",\n\t\t\t\t\tconfig.enabled && config.messages.enabled && config.messages.specialBlocks,\n\t\t\t\t\tBoolean(authorization?.core),\n\t\t\t\t),\n\t\t\t};\n\t\t},\n\t\tinstall(config, tui, productGate = \"omitted\") {\n\t\t\tconst productDenied = productGate === \"deny\";\n\t\t\tif (cleanupPending && !report) cleanupPending = false;\n\t\t\tif (cleanupPending || !tui || !config.enabled || !authorization?.core || productDenied) return undefined;\n\t\t\tconst certifiedHost = detectPiVersion().version === \"0.83.0\";\n\t\t\tconst assistantEnabled =\n\t\t\t\tauthorization.assistant &&\n\t\t\t\tisTierCAuthorized({\n\t\t\t\t\tcertifiedHost,\n\t\t\t\t\tcoreFlag: authorization.core,\n\t\t\t\t\tsurfaceFlag: true,\n\t\t\t\t\tsurface: \"assistantMessage\",\n\t\t\t\t\tconfig,\n\t\t\t\t});\n\t\t\tconst specialBlocksEnabled =\n\t\t\t\tauthorization.specialBlocks &&\n\t\t\t\tisTierCAuthorized({\n\t\t\t\t\tcertifiedHost,\n\t\t\t\t\tcoreFlag: authorization.core,\n\t\t\t\t\tsurfaceFlag: true,\n\t\t\t\t\tsurface: \"specialBlocks\",\n\t\t\t\t\tconfig,\n\t\t\t\t});\n\t\t\tconst messagesEnabled = (assistantEnabled || specialBlocksEnabled) && config.messages.enabled;\n\t\t\t// The hidden-thinking collapse is an assistant-message surface patch: it needs\n\t\t\t// the assistant flag and `messages.hideThinkingLabel`, independent of the\n\t\t\t// assistant prefix feature.\n\t\t\tconst thinkingCollapseEnabled = Boolean(\n\t\t\t\tauthorization.assistant &&\n\t\t\t\t\tconfig.messages.enabled &&\n\t\t\t\t\tconfig.messages.hideThinkingLabel &&\n\t\t\t\t\tisTierCAuthorized({\n\t\t\t\t\t\tcertifiedHost,\n\t\t\t\t\t\tcoreFlag: authorization.core,\n\t\t\t\t\t\tsurfaceFlag: true,\n\t\t\t\t\t\tsurface: \"messages\",\n\t\t\t\t\t\tconfig,\n\t\t\t\t\t}),\n\t\t\t);\n\t\t\tconst toolsEnabled =\n\t\t\t\tauthorization.tools &&\n\t\t\t\tisTierCAuthorized({ certifiedHost, coreFlag: authorization.core, surfaceFlag: true, surface: \"tools\", config });\n\t\t\tif (!messagesEnabled && !toolsEnabled) return undefined;\n\t\t\tconst detected = detectPiVersion();\n\t\t\treport = probePiCompatibility(detected.version, {\n\t\t\t\tconfig: {\n\t\t\t\t\t...config,\n\t\t\t\t\tmessages: {\n\t\t\t\t\t\t...config.messages,\n\t\t\t\t\t\tenabled: messagesEnabled,\n\t\t\t\t\t\tassistantPrefix: assistantEnabled,\n\t\t\t\t\t\thideThinkingLabel: thinkingCollapseEnabled,\n\t\t\t\t\t\tspecialBlocks: messagesEnabled && config.messages.specialBlocks && specialBlocksEnabled,\n\t\t\t\t\t},\n\t\t\t\t\ttools: {\n\t\t\t\t\t\t...config.tools,\n\t\t\t\t\t\tenabled: toolsEnabled,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tmessageSnapshot: {\n\t\t\t\t\tassistantPrefix: authorization.ascii ? \"[assistant] \" : \"│ \",\n\t\t\t\t\tassistantEnabled,\n\t\t\t\t\tcollapseHiddenThinking: thinkingCollapseEnabled,\n\t\t\t\t},\n\t\t\t\ttoolSnapshot: {\n\t\t\t\t\tcallMarker: authorization.ascii ? \"[tool] \" : \"[tool] \",\n\t\t\t\t\tresultMarker: authorization.ascii ? \"[result] \" : \"[tool:result] \",\n\t\t\t\t\tstyle: config.tools.style === \"compact-box\" ? \"compact-box\" : \"marker\",\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn report;\n\t\t},\n\t\tdispose() {\n\t\t\tif (!report) {\n\t\t\t\tcleanupPending = false;\n\t\t\t\treturn { complete: true, retryablePrototypeRecords: 0, retryableToolRecords: 0 };\n\t\t\t}\n\t\t\tconst result = dispose(report);\n\t\t\tcleanupPending = !result.complete;\n\t\t\tif (result.complete) {\n\t\t\t\treport = undefined;\n\t\t\t\tcleanupPending = false;\n\t\t\t}\n\t\t\treturn result;\n\t\t},\n\t};\n}\n","import type { ConfigFilePort } from \"../app/config-storage.js\";\nimport { readScopedConfig } from \"../app/config-storage.js\";\nimport type { ConfigDiagnostic } from \"../domain/config-diagnostics.js\";\nimport { resolveConfigDetailed } from \"../domain/config-normalization.js\";\n\nexport interface SessionFlagReader {\n\tgetFlag(name: string): unknown;\n}\nexport interface SessionAuthorization {\n\tcore: boolean;\n\tassistant: boolean;\n\tspecialBlocks: boolean;\n\ttools: boolean;\n\tascii: boolean;\n}\nexport interface ProductPolicy {\n\treadonly corePatchGate: \"omitted\" | \"allow\" | \"deny\";\n}\nexport interface ConfigSourceAdapter {\n\tsetSession(cwd: string, trusted: boolean): void;\n\tload(): Promise<{\n\t\tconfig: unknown;\n\t\tdiagnostics: readonly ConfigDiagnostic[];\n\t\tsources: Readonly<Record<string, string>>;\n\t\trawSources?: {\n\t\t\tdefaults?: unknown;\n\t\t\tglobal?: unknown;\n\t\t\tproject?: unknown;\n\t\t\tenvironment?: Record<string, string | undefined>;\n\t\t};\n\t\tproductPolicy?: ProductPolicy;\n\t}>;\n}\n\nfunction sessionOverrides(_pi: SessionFlagReader): Record<string, unknown> {\n\treturn {};\n}\n\n/** Product policy is deny-only: any explicit false wins; true never grants Tier C. */\nexport function resolveProductGate(\n\tglobal: unknown,\n\tproject: unknown,\n\tsession: unknown,\n\tprojectTrusted: boolean,\n): ProductPolicy {\n\tconst values = [global, projectTrusted ? project : undefined, session];\n\tfor (const value of values) {\n\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) continue;\n\t\tconst compatibility = (value as Record<string, unknown>).compatibility;\n\t\tif (!compatibility || typeof compatibility !== \"object\" || Array.isArray(compatibility)) continue;\n\t\tif (!Object.hasOwn(compatibility, \"allowCorePatches\")) continue;\n\t\tconst leaf = (compatibility as Record<string, unknown>).allowCorePatches;\n\t\tif (leaf === false) return { corePatchGate: \"deny\" };\n\t}\n\treturn { corePatchGate: \"omitted\" };\n}\n\nexport function readSessionAuthorization(pi: SessionFlagReader): SessionAuthorization {\n\treturn {\n\t\tcore: pi.getFlag(\"pi-style-core-patches\") === true,\n\t\tassistant: pi.getFlag(\"pi-style-message-assistant\") === true,\n\t\tspecialBlocks: pi.getFlag(\"pi-style-message-special-blocks\") === true,\n\t\ttools: pi.getFlag(\"pi-style-tools\") === true,\n\t\tascii: pi.getFlag(\"pi-style-ascii\") === true,\n\t};\n}\n\nexport function createConfigSourceAdapter(\n\tpi: SessionFlagReader,\n\tport: ConfigFilePort,\n\tpaths: (cwd: string) => { globalPath: string; projectPath: string },\n): ConfigSourceAdapter {\n\tlet trusted = true;\n\tlet currentCwd = process.cwd();\n\treturn {\n\t\tsetSession(nextCwd, nextTrusted) {\n\t\t\tcurrentCwd = nextCwd;\n\t\t\ttrusted = nextTrusted;\n\t\t},\n\t\tasync load() {\n\t\t\tconst storage = paths(currentCwd);\n\t\t\tconst global = await readScopedConfig(port, storage.globalPath);\n\t\t\tconst project = trusted ? await readScopedConfig(port, storage.projectPath) : undefined;\n\t\t\tconst resolved = resolveConfigDetailed({\n\t\t\t\tglobal: global.value,\n\t\t\t\tproject: project?.value,\n\t\t\t\tprojectTrusted: trusted,\n\t\t\t\tenvironment: process.env,\n\t\t\t\tsession: sessionOverrides(pi),\n\t\t\t});\n\t\t\tconst productPolicy = resolveProductGate(global.value, project?.value, sessionOverrides(pi), trusted);\n\t\t\treturn {\n\t\t\t\tconfig: resolved.config,\n\t\t\t\tdiagnostics: [...global.diagnostics, ...(project?.diagnostics ?? []), ...resolved.diagnostics],\n\t\t\t\tsources: resolved.sources,\n\t\t\t\trawSources: { global: global.value, project: project?.value, environment: process.env },\n\t\t\t\tproductPolicy,\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport { sessionOverrides };\n","import type { RuntimeInstallationState } from \"../app/runtime.js\";\nimport type { NormalizedPiStyleConfig } from \"../domain/config-types.js\";\nimport type { CompatibilityCoordinator } from \"./compatibility-coordinator.js\";\n\nexport function buildOperationalState(\n\tconfig: NormalizedPiStyleConfig,\n\tauthorization: { core: boolean; productCorePatchGate?: string },\n\tcompatibility: CompatibilityCoordinator,\n\tinstallationState?: RuntimeInstallationState,\n\tproductCorePatchGate?: string,\n): Readonly<Record<string, unknown>> {\n\treturn {\n\t\tcompatibility: {\n\t\t\t...compatibility.state(config),\n\t\t\tconfiguredByProduct: config.messages.enabled || config.tools.enabled,\n\t\t},\n\t\tinstallations: installationState ?? {\n\t\t\tstatus: config.enabled && config.statusLine.enabled ? \"active\" : \"disabled\",\n\t\t\teditor: config.enabled && config.editor.enabled ? \"active\" : \"disabled\",\n\t\t\tstartup: config.enabled && config.startup.mode !== \"off\" ? \"active\" : \"disabled\",\n\t\t},\n\t\tprovider: { status: \"unavailable\", recovery: \"inject a capability-safe provider\" },\n\t\tauthorization: {\n\t\t\tcore: authorization.core,\n\t\t\t...(authorization.productCorePatchGate ? { productCorePatchGate: authorization.productCorePatchGate } : {}),\n\t\t\t...(productCorePatchGate ? { productCorePatchGate } : {}),\n\t\t},\n\t};\n}\n","import type { SourceInfo, ToolInfo } from \"@earendil-works/pi-coding-agent\";\n\n/**\n * Startup resource collection for the pi/ adapter layer. Runs once at session\n * start, outside any render path, and produces the bounded tool details that\n * the startup surface renders.\n */\n\nconst CORE_TOOL_SOURCE_LABEL = \"core\";\n\nfunction stripKnownExtension(name: string): string {\n\treturn name.replace(/\\.(?:mjs|cjs|js|jsx|ts|tsx)$/i, \"\");\n}\n\nfunction compactSourcePathLabel(path: string): string {\n\tconst trimmed = path.trim();\n\tif (!trimmed) return \"\";\n\tconst synthetic = /^<([^:>]+)(?::[^>]*)?>$/.exec(trimmed);\n\tif (synthetic?.[1]) return synthetic[1];\n\tconst segments = trimmed\n\t\t.replace(/\\\\/g, \"/\")\n\t\t.split(\"/\")\n\t\t.filter((segment) => segment.length > 0 && segment !== \".\" && segment !== \"~\");\n\tconst last = segments.at(-1) ?? trimmed;\n\tif (/^index\\.(?:mjs|cjs|js|jsx|ts|tsx)$/i.test(last) && segments.length > 1) {\n\t\treturn segments[segments.length - 2] ?? last;\n\t}\n\treturn stripKnownExtension(last);\n}\n\nfunction compactPackageSourceLabel(source: string): string {\n\tif (source.startsWith(\"npm:\")) return source.slice(\"npm:\".length) || source;\n\tif (source.startsWith(\"git:\")) return compactSourcePathLabel(source.replace(/\\.git(?:#.*)?$/i, \"\")) || source;\n\treturn source;\n}\n\n/** Compact display label for a tool's source. */\nexport function toolSourceLabel(sourceInfo: SourceInfo | undefined): string {\n\tif (!sourceInfo || typeof sourceInfo !== \"object\") return CORE_TOOL_SOURCE_LABEL;\n\tconst source = typeof sourceInfo.source === \"string\" ? sourceInfo.source : \"\";\n\tif (source === \"builtin\") return CORE_TOOL_SOURCE_LABEL;\n\tif (source === \"sdk\") return \"sdk\";\n\tif (source.startsWith(\"npm:\") || source.startsWith(\"git:\")) return compactPackageSourceLabel(source);\n\tconst baseDir = typeof sourceInfo.baseDir === \"string\" ? sourceInfo.baseDir : \"\";\n\tif (baseDir) return compactSourcePathLabel(baseDir) || source || \"extension\";\n\tconst path = typeof sourceInfo.path === \"string\" ? sourceInfo.path : \"\";\n\tif (path) return compactSourcePathLabel(path) || source || \"extension\";\n\treturn source || \"extension\";\n}\n\n/**\n * Map registered tools to the bounded `{ source, name }` shape used by the\n * startup tools panel. When Pi reports active tool names, only those are kept;\n * an empty/absent active list keeps all registered tools so the panel is not\n * silently empty. Returns undefined when there is nothing to show.\n */\nexport function collectToolDetails(\n\tactiveNames: readonly string[] | undefined,\n\ttools: readonly ToolInfo[] | undefined,\n): { source: string; name: string }[] | undefined {\n\tif (!tools || tools.length === 0) return undefined;\n\tconst activeSet = activeNames && activeNames.length > 0 ? new Set(activeNames) : undefined;\n\tconst details: { source: string; name: string }[] = [];\n\tfor (const tool of tools) {\n\t\tif (typeof tool?.name !== \"string\" || tool.name.trim().length === 0) continue;\n\t\tif (activeSet && !activeSet.has(tool.name)) continue;\n\t\tdetails.push({ source: toolSourceLabel(tool.sourceInfo), name: tool.name.trim() });\n\t}\n\treturn details.length > 0 ? details : undefined;\n}\n","import type { SessionEntry } from \"@earendil-works/pi-coding-agent\";\nimport type { UsageSnapshot } from \"../domain/status.js\";\n\n/**\n * Minimal structural view of Pi's session manager: only the entry iteration\n * needed to aggregate cumulative usage. `ExtensionContext.sessionManager`\n * satisfies this shape.\n */\nexport interface SessionUsageSource {\n\tgetEntries(): readonly SessionEntry[];\n}\n\ninterface UsageTotals {\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\tcost: number;\n}\n\n/**\n * Aggregate cumulative token/cost usage from all session entries, mirroring\n * Pi's native footer: assistant messages always carry usage, tool results and\n * compaction/branch summaries carry it when available.\n */\nexport function usageFromSession(session: SessionUsageSource): UsageSnapshot | undefined {\n\tconst totals: UsageTotals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };\n\tlet sawUsage = false;\n\tfor (const entry of session.getEntries()) {\n\t\tif (entry.type === \"message\") {\n\t\t\tif (entry.message.role !== \"assistant\" && entry.message.role !== \"toolResult\") continue;\n\t\t\tconst usage = \"usage\" in entry.message ? entry.message.usage : undefined;\n\t\t\tif (!usage) continue;\n\t\t\taddUsage(totals, usage);\n\t\t\tsawUsage = true;\n\t\t} else if ((entry.type === \"branch_summary\" || entry.type === \"compaction\") && entry.usage) {\n\t\t\taddUsage(totals, entry.usage);\n\t\t\tsawUsage = true;\n\t\t}\n\t}\n\tif (!sawUsage) return undefined;\n\treturn {\n\t\tinputTokens: totals.input,\n\t\toutputTokens: totals.output,\n\t\tcacheReadTokens: totals.cacheRead,\n\t\tcacheWriteTokens: totals.cacheWrite,\n\t\tcost: totals.cost,\n\t\tsubscriptionMode: \"unknown\",\n\t\tstreaming: false,\n\t};\n}\n\nfunction addUsage(\n\ttotals: UsageTotals,\n\tusage: { input: number; output: number; cacheRead: number; cacheWrite: number; cost: { total: number } },\n): void {\n\ttotals.input += usage.input;\n\ttotals.output += usage.output;\n\ttotals.cacheRead += usage.cacheRead;\n\ttotals.cacheWrite += usage.cacheWrite;\n\ttotals.cost += usage.cost.total;\n}\n","import type { ExtensionAPI, ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport type { StatusSnapshot } from \"../domain/status.js\";\nimport { closeActiveBatch } from \"../features/tools/boxed/batch.js\";\nimport { registerPiStyleCommand } from \"./commands.js\";\nimport { type CompatibilityTestHooks, createPiStyleSessionCoordinator } from \"./session-coordinator.js\";\nimport { usageFromSession } from \"./session-usage.js\";\n\n/** Usage patch that omits the key when no session usage exists (exact optional types). */\nfunction usagePatch(ctx: ExtensionContext): StatusSnapshot {\n\tconst usage = usageFromSession(ctx.sessionManager);\n\treturn usage ? { usage } : {};\n}\n\n/**\n * Add Pi's read-only tools (grep/find/ls) to the active tool set if they are\n * registered. Preserves any other active tools (e.g. extension tools).\n * Only calls setActiveTools when something actually changed.\n */\nfunction activateReadOnlyTools(pi: ExtensionAPI): void {\n\tconst available = new Set(pi.getAllTools().map((tool) => tool.name));\n\tconst active = new Set(pi.getActiveTools());\n\tlet changed = false;\n\tfor (const name of [\"grep\", \"find\", \"ls\"] as const) {\n\t\tif (available.has(name) && !active.has(name)) {\n\t\t\tactive.add(name);\n\t\t\tchanged = true;\n\t\t}\n\t}\n\tif (changed) pi.setActiveTools([...active]);\n}\n\nlet compatibilityTestHooks: CompatibilityTestHooks = {};\nexport function __setCompatibilityTestHooks(hooks: CompatibilityTestHooks): () => void {\n\tconst previous = compatibilityTestHooks;\n\tcompatibilityTestHooks = hooks;\n\treturn () => {\n\t\tcompatibilityTestHooks = previous;\n\t};\n}\n\n/** Thin Pi adapter: register flags, commands, and forward lifecycle events. */\nexport default function piStyleExtension(pi: ExtensionAPI): void {\n\t// The core/message/tool surfaces are default-on (safe: fingerprint-certified against\n\t// exact Pi 0.83.0, fail-closed elsewhere, conflict-preserving). The OFF switch is the\n\t// product gate `compatibility.allowCorePatches: false` (or `enabled: false`) in config.\n\tfor (const [name, description] of [\n\t\t[\"pi-style-core-patches\", \"Enable pi-style message/tool core patches\"],\n\t\t[\"pi-style-message-assistant\", \"Enable pi-style assistant message prefix\"],\n\t\t[\"pi-style-message-special-blocks\", \"Enable pi-style boxed compaction/skill/branch/custom message blocks\"],\n\t\t[\"pi-style-tools\", \"Enable pi-style tool renderer decoration\"],\n\t\t[\"pi-style-readonly-tools\", \"Enable grep/find/ls read-only tools in the active tool set\"],\n\t] as const)\n\t\tpi.registerFlag(name, { type: \"boolean\", description, default: true });\n\t// ASCII markers stay opt-in; unicode markers are the default.\n\tpi.registerFlag(\"pi-style-ascii\", { type: \"boolean\", description: \"Use ASCII pi-style markers\" });\n\tconst coordinator = createPiStyleSessionCoordinator(pi, compatibilityTestHooks);\n\tregisterPiStyleCommand(pi, coordinator.app);\n\tpi.on(\"session_start\", async (event, ctx) => {\n\t\t// Pi only activates read/bash/edit/write by default; grep/find/ls are\n\t\t// registered but inactive (kept out of the model's tool list to keep the\n\t\t// core small). Activate them so the TUI shows them and the model can call\n\t\t// them directly, mirroring Claude Code's glob/grep/read tool set.\n\t\tif (pi.getFlag(\"pi-style-readonly-tools\") === true) {\n\t\t\tactivateReadOnlyTools(pi);\n\t\t}\n\t\tawait coordinator.start(event, ctx);\n\t});\n\tpi.on(\"agent_start\", () => coordinator.app.runtime.current?.dismissStartup());\n\tpi.on(\"input\", (event, _ctx) => {\n\t\tcoordinator.app.runtime.current?.dismissStartup();\n\t\t// Bare `!`/`!!` submit guard: Pi treats `!`-prefixed input as a direct bash\n\t\t// command but falls through to normal message submission when the bang has\n\t\t// no command after it — sending a literal `!` to the agent. Drop those\n\t\t// accidental submits instead; Pi's submit path already cleared the editor\n\t\t// (onChange(\"\") resets isBashMode), so the input returns to the normal\n\t\t// prompt without sending anything. Only the interactive input box is\n\t\t// guarded; rpc/extension sources keep sending text verbatim.\n\t\tif (event.source === \"interactive\") {\n\t\t\tconst trimmed = event.text.trimStart();\n\t\t\tif (trimmed.startsWith(\"!\")) {\n\t\t\t\tconst bangLength = trimmed.startsWith(\"!!\") ? 2 : 1;\n\t\t\t\tif (trimmed.slice(bangLength).trim() === \"\") return { action: \"handled\" };\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t});\n\tpi.on(\"tool_execution_start\", () => coordinator.app.runtime.current?.dismissStartup());\n\tpi.on(\"model_select\", (event) =>\n\t\tcoordinator.app.update(\n\t\t\t{\n\t\t\t\tmodel: event.model.name || event.model.id,\n\t\t\t\t...(event.model.provider ? { provider: event.model.provider } : {}),\n\t\t\t\t...(event.model.reasoning !== undefined ? { reasoning: event.model.reasoning } : {}),\n\t\t\t},\n\t\t\t\"immediate\",\n\t\t),\n\t);\n\tpi.on(\"thinking_level_select\", (event) => coordinator.app.update({ thinkingLevel: event.level }, \"immediate\"));\n\tpi.on(\"session_info_changed\", (event) => coordinator.app.update({ sessionName: event.name }, \"coalesced\"));\n\tpi.on(\"message_start\", () => {\n\t\t// A new message is a batch boundary: quiet-tool (read/ls/find) calls of the\n\t\t// new message start a fresh batch instead of joining the previous one.\n\t\tcloseActiveBatch();\n\t\t// grep/bash tree panels are NOT cleared here: historical panels must keep\n\t\t// their state so Pi re-renders of previous messages (scroll/resume) stay\n\t\t// intact. Only session boundaries reset them (session-coordinator).\n\t});\n\tpi.on(\"message_update\", () => coordinator.app.update({}, \"coalesced\"));\n\t// Usage (tokens + cost) is aggregated from finalized session entries at\n\t// message/turn boundaries, mirroring Pi's native footer; per-chunk updates\n\t// stay usage-free to keep streaming cheap.\n\tpi.on(\"message_end\", (_event, ctx) => coordinator.app.update({ ...usagePatch(ctx) }, \"coalesced\"));\n\tpi.on(\"turn_end\", (_event, ctx) => coordinator.app.update({ ...usagePatch(ctx) }, \"deferred\"));\n\tpi.on(\"agent_settled\", (_event, ctx) => coordinator.app.update({ ...usagePatch(ctx) }, \"coalesced\"));\n\tpi.on(\"session_tree\", (_event, ctx) => coordinator.app.update({ ...usagePatch(ctx) }, \"deferred\"));\n\tpi.on(\"session_compact\", (_event, ctx) => coordinator.app.update({ ...usagePatch(ctx) }, \"deferred\"));\n\tpi.on(\"tool_result\", (event, ctx) => {\n\t\tif ([\"write\", \"edit\", \"bash\"].includes(event.toolName)) {\n\t\t\tcoordinator.app.runtime.current?.invalidateGit();\n\t\t\tcoordinator.app.update({ ...usagePatch(ctx) }, \"delayed-retry\");\n\t\t}\n\t});\n\tpi.on(\"user_bash\", (_event, ctx) => {\n\t\tcoordinator.app.runtime.current?.invalidateGit();\n\t\tcoordinator.app.update({ ...usagePatch(ctx) }, \"delayed-retry\");\n\t});\n\tpi.on(\"session_shutdown\", () => coordinator.shutdown());\n}\n"],"mappings":";AAAA,SAAS,QAAQ,MAAuB;AACvC,SAAO,QAAQ,OAAO,QAAQ;AAC/B;AAEA,IAAM,aAAa,CAAC,GAAG,IAAI,KAAK,KAAK,KAAK,GAAG;AAE7C,SAAS,cAAc,OAAgE;AACtF,MAAI,SAAS,KAAK,QAAQ,IAAI;AAE7B,UAAM,OAAO;AAAA,MACZ,CAAC,GAAG,GAAG,CAAC;AAAA,MACR,CAAC,KAAK,GAAG,CAAC;AAAA,MACV,CAAC,GAAG,KAAK,CAAC;AAAA,MACV,CAAC,KAAK,KAAK,CAAC;AAAA,MACZ,CAAC,GAAG,GAAG,GAAG;AAAA,MACV,CAAC,KAAK,GAAG,GAAG;AAAA,MACZ,CAAC,GAAG,KAAK,GAAG;AAAA,MACZ,CAAC,KAAK,KAAK,GAAG;AAAA,MACd,CAAC,KAAK,KAAK,GAAG;AAAA,MACd,CAAC,KAAK,GAAG,CAAC;AAAA,MACV,CAAC,GAAG,KAAK,CAAC;AAAA,MACV,CAAC,KAAK,KAAK,CAAC;AAAA,MACZ,CAAC,GAAG,GAAG,GAAG;AAAA,MACV,CAAC,KA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,GAAG,gBAAgB,CAAC,QAAQ,QAAQ,YAAY,IAAI,OAAO,EAAE,GAAG,WAAW,GAAG,EAAE,GAAG,UAAU,CAAC;AACjG,KAAG,GAAG,mBAAmB,CAAC,QAAQ,QAAQ,YAAY,IAAI,OAAO,EAAE,GAAG,WAAW,GAAG,EAAE,GAAG,UAAU,CAAC;AACpG,KAAG,GAAG,eAAe,CAAC,OAAO,QAAQ;AACpC,QAAI,CAAC,SAAS,QAAQ,MAAM,EAAE,SAAS,MAAM,QAAQ,GAAG;AACvD,kBAAY,IAAI,QAAQ,SAAS,cAAc;AAC/C,kBAAY,IAAI,OAAO,EAAE,GAAG,WAAW,GAAG,EAAE,GAAG,eAAe;AAAA,IAC/D;AAAA,EACD,CAAC;AACD,KAAG,GAAG,aAAa,CAAC,QAAQ,QAAQ;AACnC,gBAAY,IAAI,QAAQ,SAAS,cAAc;AAC/C,gBAAY,IAAI,OAAO,EAAE,GAAG,WAAW,GAAG,EAAE,GAAG,eAAe;AAAA,EAC/D,CAAC;AACD,KAAG,GAAG,oBAAoB,MAAM,YAAY,SAAS,CAAC;AACvD;","names":["r","g","b","homedir","resolve","visibleWidth","truncated","record","homedir","resolve","fill","member","header","record","value","patch","dirname","join","formatElapsed","visibleWidth","visibleWidth","prompt","padding","promptWidth","prefix","continuation","body","kind","renderWidth","bashHidden","renderedBody","marker","widthOf","segment","ownerMap","owners","snapshot","generation","generation","generation","generation","countWords","mergePatch","block","cachedTheme","bold","highlightCode","shape","ESC","oldNum","newNum","segment","marker","shape","parseGitStatus","commits","displayPath","marker","expandHint","ESC","BG_ANSI_PATTERN","highlightCode","preview","pathLabel","shape","displayPath","bold","renderErrorLines","readFileSync","dirname","join","fileURLToPath","visibleWidth","visibleWidth","getLanguageFromPath","diffDividerLabel","getLanguageFromPath","expandHint","pathLabel","displayPath","displayPath","getLanguageFromPath","MAX_HIGHLIGHT_DIFF_CHARS","MAX_HIGHLIGHT_DIFF_ROWS","getLanguageFromPath","expandHint","note","renderBoxedToolCall","renderBoxedToolResult","visibleWidth","record","renderBoxedToolCall","renderBoxedToolResult","args","record","shape","generation","key","fileURLToPath","readFile","readFileSync","dirname","join","generation","record","segment"]}