@litfamily/litclaude 1.0.63 → 1.0.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.0.65 - 2026-11-25
4
+
5
+ - The README cover is a new loop: a terminal in the sunset look with the LIT card, a pixel LITFAMILY wordmark and a striped half-sunk sun, in place of the seven robot panels. The still for reduced motion is its first frame; both files are smaller.
6
+ - The README demo is a new silent loop of one request (the hook, the sunset LIT card with its map, three lanes, the failing then passing test, COMPLETE), with a Korean copy for the Korean page; the Claude Code chat around the card is redrawn.
7
+ - The installer's cards are round where the terminal can draw it: step pills, highlighted rows, buttons, swatches and
8
+ the status-line previews, with one blank row between blocks and every value in one column. Other terminals get the
9
+ same rows square; pipes, CI, `--yes` and `TERM=dumb` are unchanged.
10
+ - The status line, the LIT card and the installer decide round or square by one rule: `LITCLAUDE_HUD_GLYPHS` or the
11
+ `glyphs` option, then the terminal (Windows Terminal, VS Code, WezTerm, Ghostty, kitty), square over SSH, then any
12
+ installed Nerd Font by file name. The card's context gauge is round too, in the same five cells.
13
+ - The Claude desktop and mobile apps wear the sunset too. The LIT card is drawn with a half-sunk sun, its reflection,
14
+ a layered sea, stars and a neon border, only where no words are; rows, words and size stay as they were. `subtle`
15
+ and an idle card hold the sunset still.
16
+ - The Ignition look is a synthwave sunset: a starry sky, a slit sun that rises when a run starts and sinks when it
17
+ ends, hills, a neon floor and a neon frame. Every state, the fuse, the embers, the finish, light mode and
18
+ `look still|off` work as before, and the conversation column stays calm.
19
+
20
+ ## 1.0.64 - 2026-11-25
21
+
22
+ - The installer asks its questions on cards in a real terminal: the step, a title, one sentence on what the answer
23
+ does, the choices and the keys. Lists take arrows, `j`/`k`, numbers and Enter, with the status-line preview on every
24
+ colour row; yes or no is two buttons with the default lit and named. An answered card folds to one line, the five
25
+ install steps tick on one card, and the last card says what was installed, the settings and what to do next.
26
+ - The questions, their order, defaults and stored results are the same, and Ctrl+C still stops with exit code 1. The
27
+ Enter people press after `y` or `n`, and keys typed while files are copied, no longer answer the next question.
28
+ - Pipes, `CI`, `--yes`, `TERM=dumb`, small windows and the `LITCLAUDE_*_PROMPT` hooks print exactly what they did.
29
+ `NO_COLOR` draws the cards without colour, and a terminal without UTF-8 gets ASCII borders.
30
+ - The READMEs and the guide name all five questions, and the guide shows the new screens.
31
+
3
32
  ## 1.0.63 - 2026-11-25
4
33
 
5
34
  - The LIT card wears a sunset in the terminal: a half-sunk sun whose light ripples, a sea that runs outward from it,
package/README.md CHANGED
@@ -1,14 +1,14 @@
1
- <p align="center"><picture><source media="(prefers-reduced-motion: reduce)" srcset="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.63/docs/assets/cover-motion-still.webp" /><img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.63/docs/assets/cover-motion.webp" width="100%" alt="LitFamily motion cover: seven armored robots power on one by one, the LitClaude robot wakes with glowing eyes and a lit frame, then LITFAMILY and KEEP THE WORK LIT. light up." /></picture></p>
1
+ <p align="center"><picture><source media="(prefers-reduced-motion: reduce)" srcset="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.65/docs/assets/cover-motion-still.webp" /><img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.65/docs/assets/cover-motion.webp" width="100%" alt="LitFamily motion cover: a terminal in a sunset look. LitClaude's round-cornered LIT card frames the screen with its stage map, task gauge, skill pills, lanes and context gauge, a pixel LITFAMILY wordmark and a striped half-sunk sun fill the middle, the row of seven product names lights LITCLAUDE, and a Claude Code prompt types a request at the bottom." /></picture></p>
2
2
 
3
3
  <h1 align="center">LitClaude</h1>
4
4
  <p align="center"><strong>Keep the work lit.</strong></p>
5
5
  <p align="center">LitClaude is an add-on for Claude Code. It makes Claude check its own work before it says "done", and leaves a note so the next session starts where this one stopped.</p>
6
6
  <p align="center">
7
- <img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.63/docs/assets/readme/badge-version.svg" alt="1.0.63" />
8
- <a href="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.63/LICENSE"><img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.63/docs/assets/readme/badge-license.svg" alt="MIT license" /></a>
7
+ <img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.65/docs/assets/readme/badge-version.svg" alt="1.0.65" />
8
+ <a href="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.65/LICENSE"><img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.65/docs/assets/readme/badge-license.svg" alt="MIT license" /></a>
9
9
  </p>
10
10
  <p align="center">
11
- <a href="https://github.com/wjgoarxiv/litclaude#readme">Full guide and skills gallery on GitHub</a> · <a href="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.63/README_ko-KR.md">한국어</a>
11
+ <a href="https://github.com/wjgoarxiv/litclaude#readme">Full guide and skills gallery on GitHub</a> · <a href="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.65/README_ko-KR.md">한국어</a>
12
12
  </p>
13
13
 
14
14
  You ask Claude for a feature. It writes the code and says it is finished, and a day later you find the tests
@@ -53,7 +53,9 @@ npx @litfamily/litclaude@latest install
53
53
  ```
54
54
 
55
55
  On the first run npx asks whether to install the package; answer `y`. The installer registers
56
- the plugin, adds the LitClaude status line and asks for its colour and an optional output style.
56
+ the plugin, adds the LitClaude status line and asks up to five short questions on cards (its colour,
57
+ an output style, the icon font, the Co-Authored-By line and the `CLAUDE.md` block); Enter takes the
58
+ marked default.
57
59
  A new install uses the `safe` permission mode, which adds no permission rules, and leaves your
58
60
  other Claude settings as they are. It also fetches the video skill's rendering engine and
59
61
  fonts up front. Start Claude Code again afterwards so the plugin loads.
@@ -90,7 +92,7 @@ Then open the file and try the three actions yourself. That is how you find out
90
92
  | `lit adhd` (or `lit rewind`), then `go` | A six-line card with the one thing to do now, then that step |
91
93
 
92
94
  In the Claude desktop and mobile apps (Claude Code 2.1.325 or later), LitClaude also dresses the app in the
93
- Ignition look: LitFamily colours and a moving backdrop that rests, burns, signals and bursts with the LIT state.
95
+ Ignition look: LitFamily colours and a synthwave sunset backdrop that rests, burns, signals and bursts with the LIT state.
94
96
  `npx @litfamily/litclaude@latest config look still` keeps it without motion; `look off` gives the app its own look back.
95
97
 
96
98
  ## Check, update and remove
@@ -117,7 +119,7 @@ the lock folder the message names.
117
119
  ## More
118
120
 
119
121
  - [Full guide and skills gallery on GitHub](https://github.com/wjgoarxiv/litclaude#readme)
120
- - [Privacy and network behavior](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.63/docs/privacy.md)
121
- - [Migration and ownership conflicts](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.63/docs/migration.md)
122
- - [Release history](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.63/CHANGELOG.md)
123
- - [MIT license](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.63/LICENSE)
122
+ - [Privacy and network behavior](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.65/docs/privacy.md)
123
+ - [Migration and ownership conflicts](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.65/docs/migration.md)
124
+ - [Release history](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.65/CHANGELOG.md)
125
+ - [MIT license](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.65/LICENSE)
package/README_ko-KR.md CHANGED
@@ -1,14 +1,14 @@
1
- <p align="center"><picture><source media="(prefers-reduced-motion: reduce)" srcset="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.63/docs/assets/cover-motion-still.webp" /><img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.63/docs/assets/cover-motion.webp" width="100%" alt="LitFamily 모션 커버: 일곱 로봇 패널이 차례로 켜지고, LitClaude 로봇의 눈과 테두리가 빛난 뒤 LITFAMILY와 KEEP THE WORK LIT. 문구가 밝아지는 영상" /></picture></p>
1
+ <p align="center"><picture><source media="(prefers-reduced-motion: reduce)" srcset="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.65/docs/assets/cover-motion-still.webp" /><img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.65/docs/assets/cover-motion.webp" width="100%" alt="LitFamily 모션 커버: 노을빛 터미널 화면입니다. LitClaude의 모서리가 둥근 LIT 카드가 단계 지도, 작업 게이지, 스킬 알약, 레인, 컨텍스트 게이지와 함께 화면을 두르고, 가운데는 픽셀 글자 LITFAMILY와 줄무늬 해가 채우며, 일곱 제품 이름 줄에서 LITCLAUDE가 켜지고, 아래에서는 Claude Code 프롬프트에 요청이 입력됩니다." /></picture></p>
2
2
 
3
3
  <h1 align="center">LitClaude</h1>
4
4
  <p align="center"><strong>Keep the work lit.</strong></p>
5
5
  <p align="center">LitClaude는 Claude Code에 붙이는 추가 기능입니다. Claude가 "다 됐어요"라고 말하기 전에 자기 작업을 직접 확인하게 하고, 다음 세션이 이어서 시작할 수 있도록 기록을 남기게 합니다.</p>
6
6
  <p align="center">
7
- <img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.63/docs/assets/readme/badge-version.svg" alt="1.0.63" />
8
- <a href="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.63/LICENSE"><img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.63/docs/assets/readme/badge-license.svg" alt="MIT license" /></a>
7
+ <img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.65/docs/assets/readme/badge-version.svg" alt="1.0.65" />
8
+ <a href="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.65/LICENSE"><img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.65/docs/assets/readme/badge-license.svg" alt="MIT license" /></a>
9
9
  </p>
10
10
  <p align="center">
11
- <a href="https://github.com/wjgoarxiv/litclaude/blob/main/README_ko-KR.md">전체 안내와 스킬 갤러리는 GitHub에서</a> · <a href="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.63/README.md">English</a>
11
+ <a href="https://github.com/wjgoarxiv/litclaude/blob/main/README_ko-KR.md">전체 안내와 스킬 갤러리는 GitHub에서</a> · <a href="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.65/README.md">English</a>
12
12
  </p>
13
13
 
14
14
  Claude에게 기능을 하나 부탁하면 코드를 쓰고 끝났다고 말합니다. 그런데 다음 날 보니 테스트는 한 번도 돌지 않았습니다. 새 세션을 열면 프로젝트 설명을 처음부터 다시 해야 합니다.
@@ -48,7 +48,8 @@ npx @litfamily/litclaude@latest install
48
48
  ```
49
49
 
50
50
  처음 실행하면 npx가 패키지를 설치할지 묻는데, `y`로 답하면 됩니다. 설치 프로그램은 플러그인을
51
- 등록하고 LitClaude 상태 줄을 붙인 뒤, 상태 줄 색상과 쓰고 싶은 출력 스타일을 묻습니다. 새로
51
+ 등록하고 LitClaude 상태 줄을 붙인 뒤, 짧은 질문을 최대 다섯 개까지 카드로 묻습니다(상태 줄 색상, 출력
52
+ 스타일, 아이콘 글꼴, Co-Authored-By 줄, `CLAUDE.md` 구역). Enter는 표시된 기본값을 고릅니다. 새로
52
53
  설치하면 권한 규칙을 더하지 않는 `safe` 권한 모드로 시작하고 나머지 Claude 설정은 그대로 둡니다.
53
54
  영상 스킬에 필요한 렌더링 엔진과 글꼴도 미리 받아 둡니다. 설치가 끝나면 플러그인이 로드되도록
54
55
  Claude Code를 다시 시작하세요.
@@ -84,7 +85,7 @@ Claude Code를 다시 시작하세요.
84
85
  | `lit adhd`(또는 `lit rewind`), 이어서 `go` | 지금 할 한 가지를 담은 여섯 줄 카드, 그리고 그 일 |
85
86
 
86
87
  Claude 데스크톱 앱과 모바일 앱(Claude Code 2.1.325 이상)에서는 LitClaude가 앱에 Ignition 룩도 입힙니다. LitFamily 색과
87
- LIT 상태를 따라 쉬고, 타오르고, 신호를 보내고, 터지는 배경입니다. `npx @litfamily/litclaude@latest config look still`은
88
+ LIT 상태를 따라 쉬고, 타오르고, 신호를 보내고, 터지는 신스웨이브 노을 배경입니다. `npx @litfamily/litclaude@latest config look still`은
88
89
  움직임만 끄고, `look off`는 앱 본래의 모습으로 되돌립니다.
89
90
 
90
91
  ## 확인, 업데이트, 제거
@@ -108,7 +109,7 @@ npx @litfamily/litclaude@latest uninstall
108
109
  ## 더 보기
109
110
 
110
111
  - [전체 안내와 스킬 갤러리 (GitHub)](https://github.com/wjgoarxiv/litclaude/blob/main/README_ko-KR.md)
111
- - [개인정보와 네트워크 동작](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.63/docs/privacy.md)
112
- - [이전과 소유권 충돌](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.63/docs/migration.md)
113
- - [변경 이력](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.63/CHANGELOG.md)
114
- - [MIT 라이선스](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.63/LICENSE)
112
+ - [개인정보와 네트워크 동작](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.65/docs/privacy.md)
113
+ - [이전과 소유권 충돌](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.65/docs/migration.md)
114
+ - [변경 이력](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.65/CHANGELOG.md)
115
+ - [MIT 라이선스](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.65/LICENSE)
@@ -0,0 +1,505 @@
1
+ // The installer's cards for a person at a real terminal: choose one, yes or no, live progress and the
2
+ // closing summary. Nothing here runs unless richTerminal() says so; every other run keeps the plain
3
+ // prompts and machine lines in litclaude-ai.js. Cards are drawn in place, never wider than the window
4
+ // or taller than it, and fold to one line once answered.
5
+
6
+ import { emitKeypressEvents } from "node:readline";
7
+ import { ansi16CodeForAccent, hudColorDepth, themeForAccent } from "../plugins/litclaude/lib/hud-accent-palette.mjs";
8
+ import { textWidth } from "../plugins/litclaude/lib/mod/layout.mjs";
9
+
10
+ const MIN_COLS = 40;
11
+ const MIN_ROWS = 12;
12
+ const MAX_WIDTH = 100;
13
+ // `y` and then Enter is a habit: the letter already answered, so an Enter this soon after it belongs to it.
14
+ const LETTER_ENTER_MS = 400;
15
+ const SETTLE_MS = 30;
16
+ const CAP_LEFT = "\ue0b6";
17
+ const CAP_RIGHT = "\ue0b4";
18
+ // A folded answer, a step and a closing-card row all put their value in this column of the window.
19
+ const VALUE_COL = 24;
20
+
21
+ const asciiLocale = (env) => {
22
+ const locale = env.LC_ALL || env.LC_CTYPE || env.LANG || "";
23
+ return locale !== "" && !/utf-?8/iu.test(locale);
24
+ };
25
+
26
+ /** Cards need a person at a terminal: two TTYs, raw mode, room to draw, no CI, no prompt hook in the environment. */
27
+ export const richTerminal = ({ stdin, stdout, env }) => Boolean(
28
+ stdin.isTTY && stdout.isTTY && typeof stdin.setRawMode === "function"
29
+ && !Object.hasOwn(env, "CI") && !/^dumb$/iu.test(env.TERM ?? "")
30
+ && !Object.keys(env).some((name) => /^LITCLAUDE_\w+_PROMPT$/u.test(name))
31
+ && (stdout.columns || 80) >= MIN_COLS && (stdout.rows || 24) >= MIN_ROWS,
32
+ );
33
+
34
+ // ---- colour ----------------------------------------------------------------------------------
35
+ const token = (hex, ansi16) => ({ hex, ansi16 });
36
+ const PINK = token("#ff2d95", 95);
37
+ const VIOLET = token("#b48cff", 94);
38
+ const ORANGE = token("#ff8f3c", 93);
39
+ const INK = token("#0b0e14", 30);
40
+ const IVORY = token("#f2efdf", 97);
41
+ const BAR = token("#34205c", 45);
42
+ const GREEN = token("#50e68c", 92);
43
+ const AMBER = token("#ffb02e", 93);
44
+ const RED = token("#ff5577", 91);
45
+ const CUBE = [0, 95, 135, 175, 215, 255];
46
+ const rgb = (hex) => [1, 3, 5].map((i) => Number.parseInt(hex.slice(i, i + 2), 16));
47
+ const toHex = (parts) => `#${parts.map((v) => Math.round(v).toString(16).padStart(2, "0")).join("")}`;
48
+ const accentToken = (name) => {
49
+ const code = themeForAccent(name).code - 16;
50
+ return token(toHex([Math.floor(code / 36), Math.floor(code / 6) % 6, code % 6].map((v) => CUBE[v])), ansi16CodeForAccent(name) + 60);
51
+ };
52
+ const mix = (stops, t) => {
53
+ const at = Math.max(0, Math.min(1, t)) * (stops.length - 1);
54
+ const i = Math.min(stops.length - 2, Math.floor(at));
55
+ const [a, b] = [rgb(stops[i].hex), rgb(stops[i + 1].hex)];
56
+ return token(toHex(a.map((v, k) => v + (b[k] - v) * (at - i))), stops[Math.round(at)].ansi16);
57
+ };
58
+ const nearest = (v) => CUBE.reduce((best, level, i) => (Math.abs(level - v) < Math.abs(CUBE[best] - v) ? i : best), 0);
59
+ const sgr = ({ hex, ansi16 }, back, depth) => {
60
+ if (depth === "16") return String(ansi16 + (back ? 10 : 0));
61
+ if (depth === "truecolor") return `${back ? 48 : 38};2;${rgb(hex).join(";")}`;
62
+ const [r, g, b] = rgb(hex).map(nearest);
63
+ return `${back ? 48 : 38};5;${16 + 36 * r + 6 * g + b}`;
64
+ };
65
+
66
+ // ---- text ------------------------------------------------------------------------------------
67
+ const strip = (text) => text.replace(/\x1b\[[0-9;]*m/gu, "");
68
+ const cells = (text) => textWidth(strip(text));
69
+ const pad = (text, width) => text + " ".repeat(Math.max(0, width - cells(text)));
70
+
71
+ /** Word wrap in terminal cells; a word longer than the line (a path) is cut across lines, never shortened. */
72
+ export const wrap = (text, width) => {
73
+ const lines = [];
74
+ let line = "";
75
+ for (const word of String(text).split(/\s+/u).filter(Boolean)) {
76
+ if (line && cells(line) + 1 + cells(word) <= width) { line += ` ${word}`; continue; }
77
+ if (line) lines.push(line);
78
+ line = "";
79
+ for (const ch of word) {
80
+ if (cells(line + ch) > width) { lines.push(line); line = ""; }
81
+ line += ch;
82
+ }
83
+ }
84
+ return line || lines.length === 0 ? [...lines, line] : lines;
85
+ };
86
+
87
+ const UNICODE = {
88
+ tl: "╭", tr: "╮", bl: "╰", br: "╯", h: "─", v: "│", pointer: "❯", done: "✓", fail: "✗", warn: "!", dot: "·",
89
+ up: "↑", down: "↓", keys: "↑ ↓", sides: "← →", bar: "▌", spin: ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"],
90
+ on: ["╔", "═", "╗", "║", "╚", "╝"], off: ["╭", "─", "╮", "│", "╰", "╯"],
91
+ };
92
+ const ASCII = {
93
+ tl: "+", tr: "+", bl: "+", br: "+", h: "-", v: "|", pointer: ">", done: "ok", fail: "x", warn: "!", dot: "-",
94
+ up: "^", down: "v", keys: "Up Down", sides: "Left Right", bar: "|", spin: ["-", "\\", "|", "/"],
95
+ on: ["#", "=", "#", "#", "#", "#"], off: ["+", "-", "+", "|", "+", "+"],
96
+ };
97
+ const ASCII_TEXT = { "—": "-", "·": "-", "…": "...", "→": "->", "한국어": "Korean" };
98
+
99
+ // ---- the cards ---------------------------------------------------------------------------------
100
+ export const createInstallUi = ({ stdin, stdout, env, round: wantsRound = false, animate = true, settleMs = SETTLE_MS, now = Date.now, proc = process }) => {
101
+ const depth = hudColorDepth(env);
102
+ const ascii = asciiLocale(env);
103
+ const glyph = ascii ? ASCII : UNICODE;
104
+ // One form for the whole run: round needs truecolor, like the status line's own round gauges.
105
+ const round = wantsRound && depth === "truecolor" && !ascii;
106
+ let accent = "cyan";
107
+ let letterAnsweredAt = -Infinity;
108
+
109
+ const plainText = (text) => (ascii ? String(text).replace(/[—·…→]|한국어/gu, (found) => ASCII_TEXT[found]).replace(/[^\x1b\x20-\x7e]/gu, "?") : String(text));
110
+ const paint = (text, { fg, bg, bold, dim } = {}) => {
111
+ if (depth === "plain" || !text) return text;
112
+ const codes = [bold && "1", dim && "2", fg && sgr(fg, false, depth), bg && sgr(bg, true, depth)].filter(Boolean);
113
+ return codes.length > 0 ? `\x1b[${codes.join(";")}m${text}\x1b[0m` : text;
114
+ };
115
+ // Cells along a gradient; neighbours that round to the same step share one escape.
116
+ const ramp = (text, stops, style, from = 0, span = [...text].length) => {
117
+ if (depth === "plain") return text;
118
+ const runs = [];
119
+ [...text].forEach((ch, i) => {
120
+ const step = Math.round(((from + i) / Math.max(1, span - 1)) * 24);
121
+ if (runs.at(-1)?.step === step) runs.at(-1).text += ch;
122
+ else runs.push({ step, text: ch });
123
+ });
124
+ return runs.map((run) => paint(run.text, style(mix(stops, run.step / 24)))).join("");
125
+ };
126
+ const size = () => ({ cols: stdout.columns || 80, rows: stdout.rows || 24 });
127
+ const cardWidth = () => Math.min(size().cols - 2, MAX_WIDTH);
128
+ const heading = (text) => paint(plainText(text), { bold: true });
129
+ const quiet = (text) => paint(plainText(text), { dim: true });
130
+
131
+ // A filled chip: one padding cell at each end, which the round form gives to its caps.
132
+ const chip = (text, stops) => {
133
+ const fill = (part, from) => ramp(part, stops, (bg) => ({ fg: INK, bg, bold: true }), from, cells(text) + 2);
134
+ return round ? paint(CAP_LEFT, { fg: stops[0] }) + fill(text, 1) + paint(CAP_RIGHT, { fg: stops.at(-1) }) : fill(` ${text} `, 0);
135
+ };
136
+ const pill = (text) => (depth === "plain" ? `[${text}]` : chip(text, [ORANGE, PINK]));
137
+ const frame = ({ tag = "LIT", title, body, tone }) => {
138
+ const width = cardWidth();
139
+ const inner = width - 4;
140
+ const stops = tone === "bad" ? [RED, RED] : [PINK, VIOLET, accentToken(accent)];
141
+ const line = (text, from) => ramp(text, stops, (fg) => ({ fg }), from, width);
142
+ const badge = pill(tag);
143
+ const inEdge = cells(badge) + cells(plainText(title)) + 9 <= width;
144
+ const used = 4 + cells(badge) + (inEdge ? cells(plainText(title)) + 3 : 0);
145
+ const top = `${line(glyph.tl + glyph.h, 0)} ${badge}${inEdge ? ` ${quiet(glyph.dot)} ${heading(title)}` : ""} ` + line(glyph.h.repeat(width - used - 1) + glyph.tr, used);
146
+ const rows = [...(inEdge ? [] : wrap(plainText(title), inner).map((text) => paint(text, { bold: true }))), ...body];
147
+ return [
148
+ top,
149
+ ...rows.map((row) => `${line(glyph.v, 0)} ${pad(row, inner)} ${line(glyph.v, width - 1)}`),
150
+ line(glyph.bl + glyph.h.repeat(width - 2) + glyph.br, 0),
151
+ ].map((row) => ` ${row}`);
152
+ };
153
+
154
+ // ---- drawing in place ----
155
+ let drawn = [];
156
+ const lift = (count) => (count > 0 ? `\x1b[${count}A` : "");
157
+ const draw = (rows) => {
158
+ const shown = rows.slice(-Math.max(1, size().rows - 1));
159
+ let out = lift(drawn.length);
160
+ if (drawn.length !== shown.length) out += "\r\x1b[J";
161
+ shown.forEach((row, i) => { out += drawn.length === shown.length && drawn[i] === row ? "\r\n" : `\r${row}\x1b[K\r\n`; });
162
+ drawn = shown;
163
+ stdout.write(out);
164
+ };
165
+ // After a resize the old rows may have wrapped: step over what they take up now, then draw afresh.
166
+ const redraw = (rows) => {
167
+ const { cols, rows: height } = size();
168
+ const taken = drawn.reduce((sum, row) => sum + Math.max(1, Math.ceil(cells(row) / cols)), 0);
169
+ stdout.write(`${lift(Math.min(taken, height - 1))}\r\x1b[J`);
170
+ drawn = [];
171
+ draw(rows);
172
+ };
173
+ let folded = false;
174
+ const replaceWith = (row) => {
175
+ stdout.write(`${lift(drawn.length)}\r\x1b[J${folded ? "" : "\r\n"}${row}\r\n`);
176
+ folded = true;
177
+ drawn = [];
178
+ };
179
+
180
+ // ---- the terminal's own state ----
181
+ let active = false;
182
+ const restore = () => {
183
+ if (!active) return;
184
+ active = false;
185
+ stdout.write("\x1b[?25h");
186
+ stdin.setRawMode(false);
187
+ stdin.pause();
188
+ };
189
+ const onSignal = (signal) => { release(); proc.kill(proc.pid, signal); };
190
+ const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
191
+ const acquire = () => {
192
+ active = true;
193
+ stdin.setRawMode(true);
194
+ stdin.resume();
195
+ stdout.write("\x1b[?25l");
196
+ proc.on("exit", restore);
197
+ for (const signal of SIGNALS) proc.on(signal, onSignal);
198
+ };
199
+ const release = () => {
200
+ restore();
201
+ proc.removeListener("exit", restore);
202
+ for (const signal of SIGNALS) proc.removeListener(signal, onSignal);
203
+ };
204
+ const aborted = (key) => new Error(`Aborted with Ctrl+${key}`);
205
+
206
+ // Keys typed before a card is on screen were never meant for it.
207
+ const settle = () => new Promise((resolve, reject) => {
208
+ const onData = (chunk) => { if (String(chunk).includes("\x03")) finish(aborted("C")); };
209
+ const finish = (error) => {
210
+ clearTimeout(timer);
211
+ stdin.removeListener("data", onData);
212
+ if (error) reject(error);
213
+ else resolve();
214
+ };
215
+ const timer = setTimeout(finish, settleMs);
216
+ stdin.on("data", onData);
217
+ });
218
+
219
+ // Draws `view()`, feeds it keys until `onKey` returns { value }, then folds it to `fold(value)`.
220
+ const ask = async ({ view, onKey, fold, stopped }) => {
221
+ acquire();
222
+ let onKeypress;
223
+ let onResize;
224
+ let onEnd;
225
+ try {
226
+ await settle();
227
+ draw(view());
228
+ const value = await new Promise((resolve, reject) => {
229
+ let finished = false;
230
+ onKeypress = (text, key = {}) => {
231
+ if (finished) return;
232
+ if (key.ctrl && (key.name === "c" || key.name === "d")) { finished = true; reject(aborted(key.name.toUpperCase())); return; }
233
+ if (key.ctrl && key.name === "z" && proc.platform !== "win32") {
234
+ // stdin stays open: with nothing left to wait for, the process would end on its return.
235
+ stdout.write("\x1b[?25h");
236
+ stdin.setRawMode(false);
237
+ proc.once("SIGCONT", () => {
238
+ if (finished) return;
239
+ stdin.setRawMode(true);
240
+ stdout.write("\x1b[?25l");
241
+ drawn = [];
242
+ draw(view());
243
+ });
244
+ // The whole job, as the terminal would: a launcher such as npx left running would keep the shell waiting.
245
+ proc.kill(0, "SIGTSTP");
246
+ return;
247
+ }
248
+ if (key.ctrl || key.meta || key.name === "escape") return;
249
+ const enter = key.name === "return" || key.name === "enter";
250
+ if (enter && now() - letterAnsweredAt < LETTER_ENTER_MS) return;
251
+ const answer = onKey({ text, name: key.name, enter });
252
+ if (answer) { finished = true; resolve(answer.value); } else draw(view());
253
+ };
254
+ onResize = () => { if (!finished) redraw(view()); };
255
+ onEnd = () => { if (!finished) { finished = true; reject(new Error("Aborted: the terminal closed")); } };
256
+ emitKeypressEvents(stdin);
257
+ stdin.on("keypress", onKeypress);
258
+ stdout.on("resize", onResize);
259
+ stdin.once("end", onEnd);
260
+ });
261
+ replaceWith(fold(value));
262
+ return value;
263
+ } catch (error) {
264
+ replaceWith(stopped);
265
+ throw error;
266
+ } finally {
267
+ if (onKeypress) stdin.removeListener("keypress", onKeypress);
268
+ if (onResize) stdout.removeListener("resize", onResize);
269
+ if (onEnd) stdin.removeListener("end", onEnd);
270
+ release();
271
+ }
272
+ };
273
+
274
+ const foldRow = (mark, color, title, value) => {
275
+ const room = size().cols;
276
+ const label = cells(title) + cells(value) + 8 + cells(mark) > room ? `${plainText(title)} ` : pad(plainText(title), Math.min(28, Math.max(VALUE_COL - 4, cells(title))));
277
+ return ` ${paint(mark, { fg: color, bold: true })} ${label} ${value}`;
278
+ };
279
+ const answered = (title, value) => foldRow(glyph.done, GREEN, title, paint(plainText(value), { bold: true }));
280
+ const stoppedRow = (title) => foldRow(glyph.fail, RED, title, "stopped");
281
+ // Key hints, as many to a line as fit; a hint is never split.
282
+ const hints = (parts, width) => parts.reduce((lines, part) => {
283
+ const joined = `${lines.at(-1)} ${part}`;
284
+ return lines.length > 0 && cells(joined) <= width ? [...lines.slice(0, -1), joined] : [...lines, part];
285
+ }, []).map(quiet);
286
+
287
+ // A card that fits the window: roomy when it can be, then without its blank rows.
288
+ const fit = (card, variants) => {
289
+ const budget = size().rows - 1;
290
+ for (const body of variants) {
291
+ const rows = frame({ ...card, body: body.rows });
292
+ const lead = body.tight ? rows : ["", ...rows];
293
+ if (lead.length <= budget || body === variants.at(-1)) return { rows: lead, over: lead.length - budget };
294
+ }
295
+ };
296
+
297
+ /**
298
+ * One choice from a list. `choices` are { id, label, key, views?, detail?, color? }: `views` are the
299
+ * same preview drawn at falling widths, of which the widest that fits every row is shown; `color` is
300
+ * an accent name, shown as a swatch.
301
+ */
302
+ const choose = async ({ tag, title, note, choices, initial, initialTag = "default", onHighlight = () => {} }) => {
303
+ const first = Math.max(0, choices.findIndex(({ id }) => id === initial));
304
+ let at = first;
305
+ const render = () => {
306
+ const inner = cardWidth() - 4;
307
+ const swatch = ({ color }) => (color && depth !== "plain" ? `${paint(ascii ? "##" : round ? CAP_LEFT + CAP_RIGHT : "██", { fg: accentToken(color) })} ` : "");
308
+ const labels = choices.map((choice) => swatch(choice) + plainText(choice.label));
309
+ const labelWidth = Math.max(...labels.map(cells));
310
+ const tagText = [depth === "plain" ? `(${initialTag})` : initialTag, "*"].find((t, i) => i === 1 || 8 + labelWidth + cells(t) <= inner);
311
+ const tagWidth = cells(tagText) + 2;
312
+ const room = inner - 6 - labelWidth - 2 - tagWidth;
313
+ const views = choices[0].views ?? [];
314
+ const shown = views.findIndex((_, i) => choices.every((choice) => cells(choice.views[i]) <= room));
315
+ const details = !views.length && choices.every(({ detail = "" }) => cells(plainText(detail)) <= room);
316
+ const viewWidth = shown < 0 ? 0 : Math.max(...choices.map((choice) => cells(choice.views[shown])));
317
+ const list = choices.map((choice, i) => {
318
+ const on = i === at;
319
+ const extra = shown >= 0 ? pad(choice.views[shown], viewWidth) : details ? (on ? plainText(choice.detail ?? "") : quiet(choice.detail ?? "")) : "";
320
+ const mark = i === first ? paint(tagText, on ? { bold: true } : { fg: PINK, bold: true }) : "";
321
+ const row = `${on ? glyph.pointer : " "} ${choice.key} ${pad(labels[i], labelWidth)}${extra ? ` ${extra}` : ""}${mark ? ` ${mark}` : ""}`;
322
+ if (!on || depth === "plain") return ` ${row}`;
323
+ const bar = `\x1b[${sgr(IVORY, false, depth)};${sgr(BAR, true, depth)}m`;
324
+ const filled = (text) => `${bar}${text.replace(/\x1b\[(?:0|39)m/gu, (reset) => reset + bar)}\x1b[0m`;
325
+ const body = pad(row, inner - 2);
326
+ return round ? paint(CAP_LEFT, { fg: BAR }) + filled(body) + paint(CAP_RIGHT, { fg: BAR }) : filled(` ${body} `);
327
+ });
328
+ const noteRows = wrap(plainText(note), inner);
329
+ const last = choices.at(-1).key;
330
+ const hintRows = hints([`${glyph.keys} move`, `${choices[0].key}-${choices.length > 9 ? "9, 0" : last} jump`, "Enter choose", "Ctrl+C stop"], inner);
331
+ const card = { tag, title };
332
+ const roomy = fit(card, [{ rows: ["", ...noteRows, "", ...list, "", ...hintRows] }, { rows: [...noteRows, "", ...list, "", ...hintRows] }, { rows: [...noteRows, ...list, ...hintRows], tight: true }]);
333
+ if (roomy.over <= 0) return roomy.rows;
334
+ // Too short for the whole list: a window on it that follows the highlight, the arrows saying there is more.
335
+ const shortHint = (more) => hints([more, "Enter choose", "Ctrl+C stop"], inner);
336
+ const spare = size().rows - 1 - frame({ ...card, body: [...noteRows, ...shortHint(`${list.length}/${list.length} ${glyph.up} ${glyph.down}`)] }).length;
337
+ const count = Math.max(1, Math.min(list.length, spare));
338
+ const start = Math.max(0, Math.min(at - Math.floor(count / 2), list.length - count));
339
+ const more = `${at + 1}/${list.length}${start > 0 ? ` ${glyph.up}` : ""}${start + count < list.length ? ` ${glyph.down}` : ""}`;
340
+ return frame({ ...card, body: [...noteRows, ...list.slice(start, start + count), ...shortHint(more)] });
341
+ };
342
+ const move = (to) => { at = (to + choices.length) % choices.length; onHighlight(choices[at].id); };
343
+ const id = await ask({
344
+ view: render,
345
+ stopped: stoppedRow(title),
346
+ fold: (value) => answered(title, choices.find((choice) => choice.id === value).label),
347
+ onKey: ({ text, name, enter }) => {
348
+ if (enter) return { value: choices[at].id };
349
+ if (name === "up" || name === "k") move(at - 1);
350
+ else if (name === "down" || name === "j") move(at + 1);
351
+ else if (name === "home") move(0);
352
+ else if (name === "end") move(choices.length - 1);
353
+ else {
354
+ const jump = choices.findIndex(({ key }) => key === text);
355
+ if (jump >= 0) move(jump);
356
+ }
357
+ return null;
358
+ },
359
+ });
360
+ return id;
361
+ };
362
+
363
+ /** Yes or no, with the default highlighted and named on its button. */
364
+ const confirm = async ({ tag, title, note, initial, foldYes = "yes", foldNo = "no" }) => {
365
+ let yes = initial;
366
+ const buttons = (small) => {
367
+ const inner = cardWidth() - 4;
368
+ const each = [[true, "Yes"], [false, "No"]].map(([value, word]) => {
369
+ const on = value === yes;
370
+ const label = `${on ? glyph.pointer : " "} ${word}${value === initial ? (inner >= 44 ? " (default)" : " default") : ""}`;
371
+ const width = Math.max(...["Yes", "No"].map((w) => w.length)) + (inner >= 44 ? 10 : 8) + 2;
372
+ const text = pad(label, width);
373
+ const set = on ? glyph.on : glyph.off;
374
+ const filled = on && depth !== "plain";
375
+ if (small) return [filled ? chip(text, [PINK, VIOLET]) : on ? `[${text}]` : ` ${paint(text, { dim: true })} `];
376
+ if (filled && !ascii) {
377
+ // A neon outline with the filled chip inside it.
378
+ const edge = (part, from = 0) => ramp(part, [PINK, VIOLET], (fg) => ({ fg }), from, width + 6);
379
+ const rule = glyph.h.repeat(width + 4);
380
+ return [edge(glyph.tl + rule + glyph.tr), `${edge(glyph.v)} ${chip(text, [PINK, VIOLET])} ${edge(glyph.v, width + 5)}`, edge(glyph.bl + rule + glyph.br)];
381
+ }
382
+ const style = on ? (t) => paint(t, { fg: PINK, bold: true }) : quiet;
383
+ const rule = set[1].repeat(width + 4);
384
+ return [style(set[0] + rule + set[2]), `${style(set[3])} ${on ? paint(text, { bold: true }) : text} ${style(set[3])}`, style(set[4] + rule + set[5])];
385
+ });
386
+ return each[0].map((left, i) => `${left} ${each[1][i]}`).filter((row) => cells(row) <= inner || small);
387
+ };
388
+ const render = () => {
389
+ const inner = cardWidth() - 4;
390
+ const noteRows = wrap(plainText(note), inner);
391
+ const hintRows = hints(["y / n answer", `${glyph.sides} switch`, `Enter = ${yes ? "Yes" : "No"}`, "Ctrl+C stop"], inner);
392
+ const big = buttons(false);
393
+ const small = buttons(true);
394
+ const pair = big.length === 3 ? big : small;
395
+ return fit({ tag, title: `${title} ${initial ? "[Y/n]" : "[y/N]"}` }, [
396
+ { rows: ["", ...noteRows, "", ...pair, "", ...hintRows] },
397
+ { rows: [...noteRows, "", ...pair, "", ...hintRows] },
398
+ { rows: [...noteRows, ...pair, ...hintRows], tight: true },
399
+ { rows: [...noteRows, ...small, ...hintRows], tight: true },
400
+ { rows: [...noteRows, ...small, ...hints(["y / n", `Enter = ${yes ? "Yes" : "No"}`, "Ctrl+C stop"], inner)], tight: true },
401
+ ]).rows;
402
+ };
403
+ return ask({
404
+ view: render,
405
+ stopped: stoppedRow(title),
406
+ fold: (value) => answered(title, value ? foldYes : foldNo),
407
+ onKey: ({ text, name, enter }) => {
408
+ if (enter) return { value: yes };
409
+ if (/^[yn]$/iu.test(text ?? "")) {
410
+ letterAnsweredAt = now();
411
+ return { value: /y/iu.test(text) };
412
+ }
413
+ if (["left", "right", "tab"].includes(name)) yes = !yes;
414
+ return null;
415
+ },
416
+ });
417
+ };
418
+
419
+ // ---- work in progress ----
420
+ // Keys pressed while work runs are dropped (echoed, they would push the card about); Ctrl+C still ends the process.
421
+ const hold = () => {
422
+ acquire();
423
+ const onData = (chunk) => { if (String(chunk).includes("\x03")) onSignal("SIGINT"); };
424
+ stdin.on("data", onData);
425
+ return () => { stdin.removeListener("data", onData); release(); };
426
+ };
427
+
428
+ /** A card of named steps. `run(i, work)` spins on step i; `finish` folds the card to one line. */
429
+ const progress = ({ tag, title, steps }) => {
430
+ const state = steps.map(() => "wait");
431
+ let spin = 0;
432
+ const letGo = hold();
433
+ const render = () => {
434
+ const inner = cardWidth() - 4;
435
+ const longest = Math.max(...steps.map(({ name }) => name.length));
436
+ const column = VALUE_COL - 7;
437
+ const nameWidth = steps.every(({ text }) => column + cells(text) + cells(glyph.done) + 3 <= inner) ? Math.max(column, longest) : longest;
438
+ const body = steps.map(({ name, text }, i) => {
439
+ const mark = { wait: quiet(glyph.dot), run: paint(glyph.spin[spin % glyph.spin.length], { fg: accentToken(accent), bold: true }), done: paint(glyph.done, { fg: GREEN, bold: true }), fail: paint(glyph.fail, { fg: RED, bold: true }) }[state[i]];
440
+ const label = pad(name, nameWidth);
441
+ const row = `${pad(mark, cells(glyph.done))} ${state[i] === "run" ? paint(label, { bold: true }) : state[i] === "wait" ? quiet(label) : label}`;
442
+ return cells(row) + 2 + cells(text) <= inner ? `${row} ${quiet(text)}` : row;
443
+ });
444
+ return ["", ...frame({ tag, title, body: ["", ...body], tone: state.includes("fail") ? "bad" : undefined })];
445
+ };
446
+ const onResize = () => redraw(render());
447
+ stdout.on("resize", onResize);
448
+ draw(render());
449
+ const stop = () => { stdout.removeListener("resize", onResize); letGo(); };
450
+ return {
451
+ async run(i, work) {
452
+ state[i] = "run";
453
+ draw(render());
454
+ const timer = animate ? setInterval(() => { spin += 1; draw(render()); }, 80) : undefined;
455
+ try {
456
+ const result = await work();
457
+ state[i] = "done";
458
+ return result;
459
+ } catch (error) {
460
+ state[i] = "fail";
461
+ throw error;
462
+ } finally {
463
+ clearInterval(timer);
464
+ draw(render());
465
+ if (state[i] === "fail") { drawn = []; stop(); }
466
+ }
467
+ },
468
+ finish(label, value, ok = true) { stop(); replaceWith(ok ? answered(label, value) : foldRow(glyph.warn, AMBER, label, plainText(value))); },
469
+ };
470
+ };
471
+
472
+ /** A finished card: sections of marked rows. A value is wrapped, never cut short. */
473
+ const panel = ({ tag, title, sections, tone }) => {
474
+ const inner = cardWidth() - 4;
475
+ const marks = { done: [glyph.done, GREEN], warn: [glyph.warn, AMBER], fail: [glyph.fail, RED], note: [glyph.dot, VIOLET] };
476
+ const labelWidth = Math.max(VALUE_COL - 5, ...sections.flatMap(({ rows }) => rows.map(({ label = "" }) => cells(label) + 2)));
477
+ const stacked = inner < 56;
478
+ const markWidth = cells(glyph.done) + 1;
479
+ const body = sections.flatMap(({ head, rows }) => [
480
+ "",
481
+ ...(head ? [paint(head, { fg: PINK, bold: true })] : []),
482
+ ...rows.flatMap(({ mark = "done", label = "", value }) => {
483
+ const [sign, color] = marks[mark];
484
+ const lead = `${pad(paint(sign, { fg: color, bold: true }), markWidth)}`;
485
+ const style = mark === "warn" || mark === "fail" ? (t) => paint(t, { bold: true }) : (t) => t;
486
+ if (!label || stacked) {
487
+ const lines = wrap(plainText(value), inner - markWidth);
488
+ const rest = lines.map((text) => " ".repeat(markWidth) + style(text));
489
+ return label ? [lead + heading(label), ...rest] : [lead + style(lines[0]), ...rest.slice(1)];
490
+ }
491
+ return wrap(plainText(value), inner - markWidth - labelWidth).map((text, i) => (i === 0
492
+ ? lead + pad(heading(label), labelWidth) + style(text)
493
+ : " ".repeat(markWidth + labelWidth) + style(text)));
494
+ }),
495
+ ]);
496
+ stdout.write(`\n${frame({ tag, title, body, tone }).join("\n")}\n\n`);
497
+ };
498
+
499
+ return {
500
+ depth, ascii, round, choose, confirm, progress, panel, paint, plainText, heading,
501
+ setAccent: (name) => { accent = name; },
502
+ cols: () => size().cols,
503
+ cardWidth,
504
+ };
505
+ };