pi-chassis 0.0.0-stage → 0.7.1

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 (169) hide show
  1. package/CHANGELOG.md +118 -0
  2. package/LICENSE +21 -0
  3. package/README.md +51 -2
  4. package/THIRD_PARTY_NOTICES +30 -0
  5. package/dist/chassis/alert.d.ts +50 -0
  6. package/dist/chassis/alert.js +107 -0
  7. package/dist/chassis/api.d.ts +411 -0
  8. package/dist/chassis/api.js +676 -0
  9. package/dist/chassis/bash-output.d.ts +89 -0
  10. package/dist/chassis/bash-output.js +157 -0
  11. package/dist/chassis/brand.d.ts +99 -0
  12. package/dist/chassis/brand.js +79 -0
  13. package/dist/chassis/client.d.ts +87 -0
  14. package/dist/chassis/client.js +271 -0
  15. package/dist/chassis/commands.d.ts +60 -0
  16. package/dist/chassis/commands.js +211 -0
  17. package/dist/chassis/editor.d.ts +70 -0
  18. package/dist/chassis/editor.js +213 -0
  19. package/dist/chassis/footer.d.ts +14 -0
  20. package/dist/chassis/footer.js +136 -0
  21. package/dist/chassis/header.d.ts +12 -0
  22. package/dist/chassis/header.js +38 -0
  23. package/dist/chassis/home.d.ts +48 -0
  24. package/dist/chassis/home.js +184 -0
  25. package/dist/chassis/icons.d.ts +203 -0
  26. package/dist/chassis/icons.js +190 -0
  27. package/dist/chassis/index.d.ts +21 -0
  28. package/dist/chassis/index.js +582 -0
  29. package/dist/chassis/layout.d.ts +40 -0
  30. package/dist/chassis/layout.js +264 -0
  31. package/dist/chassis/message-modes.d.ts +21 -0
  32. package/dist/chassis/message-modes.js +49 -0
  33. package/dist/chassis/messages.d.ts +75 -0
  34. package/dist/chassis/messages.js +392 -0
  35. package/dist/chassis/modes.d.ts +21 -0
  36. package/dist/chassis/modes.js +99 -0
  37. package/dist/chassis/palette.d.ts +84 -0
  38. package/dist/chassis/palette.js +235 -0
  39. package/dist/chassis/peek.d.ts +61 -0
  40. package/dist/chassis/peek.js +156 -0
  41. package/dist/chassis/prompt-row.d.ts +42 -0
  42. package/dist/chassis/prompt-row.js +68 -0
  43. package/dist/chassis/provider-view.d.ts +34 -0
  44. package/dist/chassis/provider-view.js +107 -0
  45. package/dist/chassis/provider.d.ts +69 -0
  46. package/dist/chassis/provider.js +73 -0
  47. package/dist/chassis/readonly-command.d.ts +19 -0
  48. package/dist/chassis/readonly-command.js +454 -0
  49. package/dist/chassis/sanitize.d.ts +42 -0
  50. package/dist/chassis/sanitize.js +103 -0
  51. package/dist/chassis/session-info.d.ts +39 -0
  52. package/dist/chassis/session-info.js +107 -0
  53. package/dist/chassis/sidebar.d.ts +48 -0
  54. package/dist/chassis/sidebar.js +273 -0
  55. package/dist/chassis/state.d.ts +38 -0
  56. package/dist/chassis/state.js +19 -0
  57. package/dist/chassis/telemetry.d.ts +60 -0
  58. package/dist/chassis/telemetry.js +191 -0
  59. package/dist/chassis/tools.d.ts +112 -0
  60. package/dist/chassis/tools.js +588 -0
  61. package/dist/chassis/version.d.ts +2 -0
  62. package/dist/chassis/version.js +20 -0
  63. package/dist/diff/git-diff.d.ts +71 -0
  64. package/dist/diff/git-diff.js +325 -0
  65. package/dist/diff/host.d.ts +34 -0
  66. package/dist/diff/host.js +50 -0
  67. package/dist/diff/index.d.ts +13 -0
  68. package/dist/diff/index.js +86 -0
  69. package/dist/diff/render.d.ts +67 -0
  70. package/dist/diff/render.js +196 -0
  71. package/dist/diff/types.d.ts +60 -0
  72. package/dist/diff/types.js +4 -0
  73. package/dist/diff/view.d.ts +118 -0
  74. package/dist/diff/view.js +528 -0
  75. package/dist/git/flows.d.ts +92 -0
  76. package/dist/git/flows.js +415 -0
  77. package/dist/git/forge.d.ts +26 -0
  78. package/dist/git/forge.js +41 -0
  79. package/dist/git/index.d.ts +20 -0
  80. package/dist/git/index.js +121 -0
  81. package/dist/git/repo.d.ts +64 -0
  82. package/dist/git/repo.js +186 -0
  83. package/dist/git/run.d.ts +38 -0
  84. package/dist/git/run.js +127 -0
  85. package/dist/git/settings.d.ts +8 -0
  86. package/dist/git/settings.js +38 -0
  87. package/dist/git/text.d.ts +51 -0
  88. package/dist/git/text.js +109 -0
  89. package/dist/widgets/container/detect.d.ts +23 -0
  90. package/dist/widgets/container/detect.js +67 -0
  91. package/dist/widgets/container/index.d.ts +9 -0
  92. package/dist/widgets/container/index.js +26 -0
  93. package/dist/widgets/mcp/index.d.ts +13 -0
  94. package/dist/widgets/mcp/index.js +50 -0
  95. package/dist/widgets/mcp/status.d.ts +50 -0
  96. package/dist/widgets/mcp/status.js +70 -0
  97. package/dist/widgets/session-todos/index.d.ts +12 -0
  98. package/dist/widgets/session-todos/index.js +52 -0
  99. package/dist/widgets/subagents/index.d.ts +16 -0
  100. package/dist/widgets/subagents/index.js +173 -0
  101. package/dist/widgets/subagents/status.d.ts +61 -0
  102. package/dist/widgets/subagents/status.js +198 -0
  103. package/dist/widgets/todo/index.d.ts +13 -0
  104. package/dist/widgets/todo/index.js +65 -0
  105. package/dist/widgets/todo/parse.d.ts +29 -0
  106. package/dist/widgets/todo/parse.js +122 -0
  107. package/docs/branding.md +25 -0
  108. package/docs/development.md +22 -0
  109. package/docs/diff-api.md +18 -0
  110. package/docs/git.md +23 -0
  111. package/docs/internals.md +13 -0
  112. package/docs/provider-status.md +23 -0
  113. package/docs/status-widgets.md +157 -0
  114. package/docs/tool-rows.md +50 -0
  115. package/docs/usage.md +62 -0
  116. package/docs/widgets.md +113 -0
  117. package/extensions/chassis/alert.ts +127 -0
  118. package/extensions/chassis/api.ts +967 -0
  119. package/extensions/chassis/bash-output.ts +186 -0
  120. package/extensions/chassis/brand.ts +151 -0
  121. package/extensions/chassis/client.ts +284 -0
  122. package/extensions/chassis/commands.ts +244 -0
  123. package/extensions/chassis/editor.ts +253 -0
  124. package/extensions/chassis/footer.ts +131 -0
  125. package/extensions/chassis/header.ts +43 -0
  126. package/extensions/chassis/home.ts +186 -0
  127. package/extensions/chassis/icons.ts +220 -0
  128. package/extensions/chassis/index.ts +605 -0
  129. package/extensions/chassis/layout.ts +298 -0
  130. package/extensions/chassis/message-modes.ts +48 -0
  131. package/extensions/chassis/messages.ts +403 -0
  132. package/extensions/chassis/modes.ts +108 -0
  133. package/extensions/chassis/palette.ts +258 -0
  134. package/extensions/chassis/peek.ts +167 -0
  135. package/extensions/chassis/prompt-row.ts +86 -0
  136. package/extensions/chassis/provider-view.ts +118 -0
  137. package/extensions/chassis/provider.ts +115 -0
  138. package/extensions/chassis/readonly-command.ts +440 -0
  139. package/extensions/chassis/sanitize.ts +108 -0
  140. package/extensions/chassis/session-info.ts +127 -0
  141. package/extensions/chassis/sidebar.ts +285 -0
  142. package/extensions/chassis/state.ts +50 -0
  143. package/extensions/chassis/telemetry.ts +222 -0
  144. package/extensions/chassis/tools.ts +618 -0
  145. package/extensions/chassis/version.ts +20 -0
  146. package/extensions/diff/git-diff.ts +365 -0
  147. package/extensions/diff/host.ts +58 -0
  148. package/extensions/diff/index.ts +101 -0
  149. package/extensions/diff/render.ts +217 -0
  150. package/extensions/diff/types.ts +67 -0
  151. package/extensions/diff/view.ts +523 -0
  152. package/extensions/git/flows.ts +485 -0
  153. package/extensions/git/forge.ts +54 -0
  154. package/extensions/git/index.ts +117 -0
  155. package/extensions/git/repo.ts +200 -0
  156. package/extensions/git/run.ts +143 -0
  157. package/extensions/git/settings.ts +38 -0
  158. package/extensions/git/text.ts +133 -0
  159. package/extensions/widgets/container/detect.ts +81 -0
  160. package/extensions/widgets/container/index.ts +29 -0
  161. package/extensions/widgets/mcp/index.ts +53 -0
  162. package/extensions/widgets/mcp/status.ts +94 -0
  163. package/extensions/widgets/session-todos/index.ts +55 -0
  164. package/extensions/widgets/subagents/index.ts +170 -0
  165. package/extensions/widgets/subagents/status.ts +237 -0
  166. package/extensions/widgets/todo/index.ts +66 -0
  167. package/extensions/widgets/todo/parse.ts +119 -0
  168. package/package.json +91 -4
  169. package/scripts/link-pi.mjs +76 -0
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Home screen, OpenCode style (packages/tui/src/routes/home.tsx): before the session has a
3
+ * message, the transcript and sidebar give way to pi's own logo, the prompt (max 75 columns), a
4
+ * tip, and a bottom bar with the directory, MCP count and version. layout.ts composes these with
5
+ * pi's own prompt; this file renders the pieces.
6
+ *
7
+ * (pi logo, coral/blue/yellow)
8
+ *
9
+ * ┃ Ask anything… "Fix a TODO in the codebase"
10
+ * ┃ 󰚩 BUILD Opus 5.5 Anthropic medium
11
+ * ╹▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
12
+ * tab agents ctrl+p commands
13
+ *
14
+ * ● Tip Press tab to cycle between Build and Plan agents
15
+ *
16
+ * ● Acme pi 1.1.0 · chassis 0.1.0 ~/git/pi-chassis main ● 6 MCP ⟲ "chassis" 2h ago ctrl+x r
17
+ */
18
+
19
+ import type { Theme } from "@earendil-works/pi-coding-agent";
20
+ import { type Color, backgroundAnsi, foregroundAnsi, rgbColor, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
21
+ import { widgetsFor } from "./api.ts";
22
+ import { brandLine, fmtAgo, homeRelative, sanitize } from "./palette.ts";
23
+ import { icon, leadIcon } from "./icons.ts";
24
+ import { branchGlyph, worktreeTag } from "./sidebar.ts";
25
+ import type { UiState } from "./state.ts";
26
+ import { chassisVersion } from "./version.ts";
27
+
28
+ /** OpenCode's prompt width on the home screen (tui.prompt.max_width default). */
29
+ export const HOME_PROMPT_WIDTH = 75;
30
+
31
+ /** OpenCode's home placeholders, shown as `Ask anything… "<one of these>"`. */
32
+ export const PLACEHOLDERS = ["Fix a TODO in the codebase", "What is the tech stack of this project?", "Fix broken tests"];
33
+
34
+ const center = (s: string, w: number) => {
35
+ const pad = Math.max(0, Math.floor((w - visibleWidth(s)) / 2));
36
+ return truncateToWidth(" ".repeat(pad) + s, w, "");
37
+ };
38
+
39
+ /** The pi logo's pixels (pi's own components/pi-logo-animation.js): c coral, b blue, y yellow. */
40
+ export const PI_PIXELS = ["ccc.", "b.c.", "bb.y", "b..y"];
41
+ const PI_COLORS: Record<string, Color> = {
42
+ c: rgbColor(228, 138, 122),
43
+ b: rgbColor(79, 142, 179),
44
+ y: rgbColor(234, 182, 93),
45
+ };
46
+
47
+ /**
48
+ * The pi logo scaled up: each logo pixel becomes `scale` columns by `scale` half-rows, drawn with
49
+ * half blocks, so scale 3 gives 12 columns by 6 rows (a 12 by 6 cell logo).
50
+ */
51
+ export function piLogoRows(theme: Theme, scale = 3): string[] {
52
+ const mode = theme.getColorMode();
53
+ const grid: (string | undefined)[][] = [];
54
+ for (const row of PI_PIXELS) {
55
+ const cells = [...row].flatMap((p) => Array<string | undefined>(scale).fill(PI_COLORS[p] ? p : undefined));
56
+ for (let k = 0; k < scale; k++) grid.push(cells);
57
+ }
58
+ const fg = (p: string) => foregroundAnsi(PI_COLORS[p]!, mode);
59
+ const bg = (p: string) => backgroundAnsi(PI_COLORS[p]!, mode);
60
+ const lines: string[] = [];
61
+ for (let y = 0; y < grid.length; y += 2) {
62
+ const top = grid[y]!;
63
+ const bottom = grid[y + 1] ?? [];
64
+ let line = "";
65
+ for (let x = 0; x < top.length; x++) {
66
+ const t = top[x];
67
+ const b = bottom[x];
68
+ if (!t && !b) line += " ";
69
+ else if (t && b && t === b) line += `${fg(t)}█\x1b[39m`;
70
+ else if (t && b) line += `${fg(t)}${bg(b)}▀\x1b[39;49m`;
71
+ else if (t) line += `${fg(t)}▀\x1b[39m`;
72
+ else line += `${fg(b!)}▄\x1b[39m`;
73
+ }
74
+ lines.push(line);
75
+ }
76
+ return lines;
77
+ }
78
+
79
+ /** The logo, centred: pi's own logo (falls back to a plain "pi" when too narrow). */
80
+ export function renderLogo(theme: Theme, width: number): string[] {
81
+ const pi = piLogoRows(theme);
82
+ if (width < 12) return [center(theme.bold(theme.fg("text", "pi")), width)];
83
+ return pi.map((l) => center(l, width));
84
+ }
85
+
86
+ /** Tips, `{x}` marks the highlighted part (OpenCode: {highlight}…{/highlight}). */
87
+ export const TIPS = [
88
+ "Press {tab} to cycle between Build and Plan agents",
89
+ "Press {ctrl+p} to see all available actions and commands",
90
+ "The leader key is {ctrl+x}; combine with other keys for quick actions",
91
+ "Press {ctrl+x ?} to list the leader key actions",
92
+ "Press {ctrl+x b} in a session to show or hide the sidebar panel",
93
+ "Use {/new} or {ctrl+x n} to start a fresh conversation session",
94
+ "Use {/resume} or {ctrl+x l} to continue an earlier session",
95
+ "Use {/model} or {ctrl+l} to switch between available AI models",
96
+ "Use {/tree} to jump back to any earlier point in the session",
97
+ "Use {/fork} to branch a new session from an earlier message",
98
+ "Use {/compact} to summarize older history and free up context",
99
+ "Use {/export} to save the session as HTML or JSONL",
100
+ "Use {/copy} or {ctrl+x y} to copy the assistant's last message",
101
+ "Use {/name} to give this session a recognizable name",
102
+ "Press {ctrl+o} to collapse or expand tool output",
103
+ "Press {ctrl+t} to collapse or expand thinking blocks",
104
+ "Press {shift+enter} to add newlines in your prompt",
105
+ "Press {ctrl+g} to compose messages in your external editor",
106
+ "Press {escape} to stop the AI mid-response",
107
+ "Type {@} to search for a file and add it to your prompt",
108
+ "Start your prompt with {!} to run a shell command",
109
+ "Use {/hotkeys} to show all keyboard shortcuts",
110
+ "Use {/reload} to reload extensions, themes and keybindings",
111
+ ];
112
+
113
+ /** Splits a tip into plain and highlighted parts. */
114
+ export function parseTip(tip: string): { text: string; highlight: boolean }[] {
115
+ const parts: { text: string; highlight: boolean }[] = [];
116
+ const re = /\{([^}]*)\}/g;
117
+ let at = 0;
118
+ for (const m of tip.matchAll(re)) {
119
+ if (m.index > at) parts.push({ text: tip.slice(at, m.index), highlight: false });
120
+ parts.push({ text: m[1]!, highlight: true });
121
+ at = m.index + m[0].length;
122
+ }
123
+ if (at < tip.length) parts.push({ text: tip.slice(at), highlight: false });
124
+ return parts;
125
+ }
126
+
127
+ /** "● Tip …" (OpenCode: warning-coloured label, highlights in text, the rest muted), centred. */
128
+ export function renderTip(theme: Theme, width: number, index: number): string[] {
129
+ const tip = TIPS[((index % TIPS.length) + TIPS.length) % TIPS.length]!;
130
+ const body = parseTip(tip)
131
+ .map((p) => theme.fg(p.highlight ? "text" : "muted", p.text))
132
+ .join("");
133
+ const label = theme.fg("warning", "● Tip ");
134
+ const max = Math.min(width, HOME_PROMPT_WIDTH);
135
+ const lines = wrapTextWithAnsi(body, Math.max(10, max - 6));
136
+ const out = lines.map((l, i) => `${i === 0 ? label : " "}${l}`);
137
+ // One left edge for every line, so wrapped lines stay aligned under the first.
138
+ const w = Math.max(...out.map((l) => visibleWidth(l)));
139
+ const pad = " ".repeat(Math.max(0, Math.floor((width - w) / 2)));
140
+ return out.map((l) => truncateToWidth(pad + l, width, ""));
141
+ }
142
+
143
+ /**
144
+ * Bottom bar (OpenCode home/footer.tsx): 1 row of padding above and below, 2 columns at the sides;
145
+ * the folder and branch (with the branch icon) muted and the MCP count with a coloured dot on the left; on the right, the most
146
+ * recent other session in this directory and the leader key that resumes it. With `piVersion`, the
147
+ * brand with the pi and chassis versions comes first on the same line.
148
+ */
149
+ export function renderHomeFooter(state: UiState, theme: Theme, width: number, piVersion?: string): string[] {
150
+ const cwd = homeRelative(state.ctx?.cwd ?? process.cwd());
151
+ const branch = state.git?.branch;
152
+ // Same branch icon as the sidebar and footer: the folder, then the icon and the branch name.
153
+ const left: string[] = [theme.fg("muted", cwd) + (branch ? ` ${leadIcon(branchGlyph(), (s) => theme.fg("accent", s))}${theme.fg("muted", branch)}${worktreeTag(theme, state.git)}` : "")];
154
+ const mcp = widgetsFor("sidebar").find((w) => w.id === "mcp");
155
+ if (mcp) {
156
+ try {
157
+ const view = mcp.render({ theme, ctx: state.ctx, width });
158
+ if (view?.text) {
159
+ const connected = view.text.split("/")[0] ?? view.text;
160
+ const dot = view.level === "error" ? "error" : view.level === "warn" ? "warning" : view.level === "ok" ? "success" : "muted";
161
+ left.push(`${theme.fg(dot, "●")} ${theme.fg("text", `${connected} MCP`)}`);
162
+ }
163
+ } catch {
164
+ // widget error: leave it out
165
+ }
166
+ }
167
+ // The brand with the pi and chassis versions leads the line.
168
+ if (piVersion) left.unshift(brandLine(theme, piVersion, chassisVersion()));
169
+ const leftStr = left.join(" ");
170
+ // Right: the most recent other session here, with the leader key that resumes it.
171
+ const last = state.lastSession;
172
+ const inner = width - 4;
173
+ if (last) {
174
+ const tail = `${theme.fg("dim", fmtAgo(Date.now() - last.modified.getTime()))} ${theme.fg("text", "ctrl+x r")}`;
175
+ const mark = icon("resume");
176
+ const room = inner - visibleWidth(leftStr) - 4 - visibleWidth(tail) - 4; // gap, "⟲ ", quotes, spaces
177
+ if (room >= 8) {
178
+ // The label comes from a session file, so it is cleaned here whatever put it in the state.
179
+ const label = truncateToWidth(sanitize(last.label) || "untitled", Math.min(40, room), "…");
180
+ const right = `${leadIcon(mark, (s) => theme.fg("muted", s))}${theme.fg("muted", `"${label}"`)} ${tail}`;
181
+ const gap = inner - visibleWidth(leftStr) - visibleWidth(right);
182
+ return ["", ` ${leftStr}${" ".repeat(Math.max(2, gap))}${right}`, ""];
183
+ }
184
+ }
185
+ return ["", ` ${truncateToWidth(leftStr, inner, "…")}`, ""];
186
+ }
@@ -0,0 +1,220 @@
1
+ /**
2
+ * Icons: every glyph chassis draws from a Nerd Font lives here, each with a plain twin that needs
3
+ * no special font. The plain twin takes the same number of cells as the Nerd glyph (one, or none
4
+ * where the words beside it already say it), so no layout changes between the two sets.
5
+ *
6
+ * Which set is used, first match wins:
7
+ * 1. the PI_CHASSIS_ICONS environment variable ("nerd" or "plain")
8
+ * 2. the user's setting, `/chassis icons nerd|plain`, saved in chassis.json
9
+ * 3. the brand's default (`icons` in its spec: a brand that ships a font can ask for "nerd")
10
+ * 4. plain, so a terminal without a Nerd Font never shows empty boxes
11
+ *
12
+ * The plain glyphs are ASCII or characters that exist in the common monospace fonts (DejaVu Sans
13
+ * Mono, Noto Sans Mono, Consolas and Lucida Console were checked): • · ↑ ↓ → ● ○ ▲ × ▐ ▌.
14
+ *
15
+ * This file is the only place with Nerd Font code points. test/icons.test.ts fails on one anywhere else.
16
+ */
17
+
18
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
19
+ import { dirname } from "node:path";
20
+ import { getBrand } from "./brand.ts";
21
+ import { statePath } from "./api.ts";
22
+
23
+ export type IconSet = "nerd" | "plain";
24
+
25
+ /** An icon a widget supplies: one string for both sets, or one per set. */
26
+ export type IconLike = string | { nerd: string; plain?: string };
27
+
28
+ interface Pair {
29
+ nerd: string;
30
+ plain: string;
31
+ }
32
+
33
+ /** nf-md-* unless noted. "" means no icon in that set. */
34
+ export const ICONS = {
35
+ // sidebar: provider section
36
+ provider: { nerd: "\u{F06A9}", plain: "\u25A0" }, // robot; a filled square
37
+ usage: { nerd: "\u{F0766}", plain: " " }, // circle-outline; the filled slices are computed from it
38
+ branch: { nerd: "\uF418", plain: "" }, // octicons git-branch
39
+ worktree: { nerd: "\u{F04E0}", plain: "wt" }, // source-fork: a linked git worktree
40
+ cache: { nerd: "\u27F3", plain: "cache" },
41
+ resume: { nerd: "\u27F2", plain: "" },
42
+ // a widget row's level marker
43
+ levelOk: { nerd: "\u{F05E1}", plain: "\u25CF" }, // check-circle-outline
44
+ levelWarn: { nerd: "\u{F002A}", plain: "\u25B2" }, // alert-outline
45
+ levelError: { nerd: "\u{F015A}", plain: "\u00D7" }, // close-circle-outline
46
+ levelOff: { nerd: "\u{F0377}", plain: "\u25CB" }, // minus-circle-outline
47
+ levelInfo: { nerd: "\u{F02FD}", plain: "\u2022" }, // information-outline
48
+ // marks for plain setStatus() lines
49
+ statusLsp: { nerd: "\u{F0169}", plain: "\u2022" }, // code-braces
50
+ statusGraphify: { nerd: "\u{F104A}", plain: "\u2022" }, // graph-outline
51
+ // prompt row
52
+ modeBuild: { nerd: "\u{F06A9}", plain: "" }, // robot
53
+ modePlan: { nerd: "\u{F0208}", plain: "" }, // eye
54
+ capLeft: { nerd: "\uE0B6", plain: "\u2590" }, // powerline round cap; right half block
55
+ capRight: { nerd: "\uE0B4", plain: "\u258C" }, // powerline round cap; left half block
56
+ // tool rows
57
+ toolRead: { nerd: "\u{F09EE}", plain: "\u2192" }, // file-document-outline
58
+ toolWrite: { nerd: "\u{F0EED}", plain: "+" }, // file-plus-outline
59
+ toolEdit: { nerd: "\u{F03EB}", plain: "~" }, // pencil
60
+ toolBash: { nerd: "\u{F018D}", plain: "$" }, // console
61
+ toolGrep: { nerd: "\u{F0349}", plain: "?" }, // magnify
62
+ toolFind: { nerd: "\u{F0C7D}", plain: "*" }, // file-search-outline
63
+ toolLs: { nerd: "\u{F0256}", plain: "/" }, // folder-outline
64
+ toolOther: { nerd: "\uF013", plain: "\u2022" }, // fontawesome cog: a tool with no spec of its own
65
+ // turn telemetry: the words beside them say it
66
+ telSpeed: { nerd: "\u{F04C5}", plain: "" }, // speedometer
67
+ telTtft: { nerd: "\u{F051F}", plain: "" }, // timer-sand
68
+ telTotal: { nerd: "\u{F0150}", plain: "" }, // clock-outline
69
+ telStall: { nerd: "\u{F002A}", plain: "" }, // alert-outline
70
+ // diff view
71
+ diff: { nerd: "\u{F02A2}", plain: "" }, // source-branch
72
+ // widgets. A section heading or a row marker with no plain glyph falls back to the row bullet.
73
+ widgetContainer: { nerd: "\u{F0868}", plain: "" }, // docker
74
+ widgetK8s: { nerd: "\u{F10FE}", plain: "" }, // kubernetes
75
+ widgetMcp: { nerd: "\u{F06A5}", plain: "" }, // server-network
76
+ widgetSessionTodos: { nerd: "\u{F08A8}", plain: "" }, // clipboard-check-outline
77
+ widgetSubagents: { nerd: "\u{F0B58}", plain: "" }, // account-group-outline
78
+ widgetTodo: { nerd: "\u{F0756}", plain: "" }, // format-list-checks
79
+ } as const satisfies Record<string, Pair>;
80
+
81
+ export type IconName = keyof typeof ICONS;
82
+
83
+ /** The slice glyphs of the usage circle come after this one: U+F0A9E is one eighth. */
84
+ const USAGE_SLICE_BASE = 0xf0a9d;
85
+
86
+ // ---- which set --------------------------------------------------------------------------------
87
+
88
+ interface Slot {
89
+ /** The user's saved setting; `loaded` says whether the state file was read yet. */
90
+ setting?: IconSet;
91
+ loaded: boolean;
92
+ }
93
+
94
+ const KEY = Symbol.for("pi-chassis/icons");
95
+
96
+ function slot(): Slot {
97
+ const g = globalThis as unknown as Record<symbol, Slot | undefined>;
98
+ g[KEY] ??= { loaded: false };
99
+ return g[KEY]!;
100
+ }
101
+
102
+ const asSet = (v: unknown): IconSet | undefined => (v === "nerd" || v === "plain" ? v : undefined);
103
+
104
+ /** The saved setting from the state file (`icons`), or undefined. */
105
+ export function loadIconSetting(path = statePath()): IconSet | undefined {
106
+ try {
107
+ return asSet(JSON.parse(readFileSync(path, "utf8"))?.icons);
108
+ } catch {
109
+ return undefined;
110
+ }
111
+ }
112
+
113
+ /** Set the user's setting for this run (undefined forgets it). Saving to the file is `saveIconSetting`. */
114
+ export function setIconSetting(set: IconSet | undefined): void {
115
+ const s = slot();
116
+ s.setting = set;
117
+ s.loaded = true;
118
+ }
119
+
120
+ /** Forget what was read, so the next call reads the state file again (tests, and /reload). */
121
+ export function resetIconSetting(): void {
122
+ const s = slot();
123
+ s.setting = undefined;
124
+ s.loaded = false;
125
+ }
126
+
127
+ /** Where the current set comes from, for `/chassis icons`. */
128
+ export function iconSource(): "env" | "setting" | "brand" | "default" {
129
+ if (asSet(process.env.PI_CHASSIS_ICONS)) return "env";
130
+ const s = slot();
131
+ if (!s.loaded) {
132
+ s.setting = loadIconSetting();
133
+ s.loaded = true;
134
+ }
135
+ if (s.setting) return "setting";
136
+ return asSet(getBrand().icons) ? "brand" : "default";
137
+ }
138
+
139
+ /** The icon set in use. */
140
+ export function iconSet(): IconSet {
141
+ const env = asSet(process.env.PI_CHASSIS_ICONS);
142
+ if (env) return env;
143
+ const s = slot();
144
+ if (!s.loaded) {
145
+ s.setting = loadIconSetting();
146
+ s.loaded = true;
147
+ }
148
+ return s.setting ?? asSet(getBrand().icons) ?? "plain";
149
+ }
150
+
151
+ // ---- resolving --------------------------------------------------------------------------------
152
+
153
+ /** The glyph for `name` in the current set. May be "" (no icon). */
154
+ export function icon(name: IconName): string {
155
+ return ICONS[name][iconSet()];
156
+ }
157
+
158
+ /** `glyph`, a space, then `text`; just `text` when there is no glyph. */
159
+ export const withIcon = (glyph: string, text: string): string => (glyph ? `${glyph} ${text}` : text);
160
+
161
+ /** "<glyph> " painted with `paint`, or nothing when the set has no glyph here. */
162
+ export const leadIcon = (glyph: string, paint: (s: string) => string): string => (glyph ? `${paint(glyph)} ` : "");
163
+
164
+ /** Private-use code points: where Nerd Font (and any custom icon font) glyphs live. */
165
+ const PRIVATE_USE = /[\uE000-\uF8FF\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/gu;
166
+ export const hasPrivateUse = (s: string): boolean => new RegExp(PRIVATE_USE.source, "u").test(s);
167
+
168
+ /**
169
+ * A widget's or brand's icon in the current set, or undefined when it has none there. An object
170
+ * gives its `nerd` or `plain` string. A bare string is used as given in the nerd set; in the plain
171
+ * set it loses any private-use characters (a font the terminal may not have), and is undefined if
172
+ * nothing but blanks is left.
173
+ */
174
+ export function resolveIcon(like: IconLike | undefined): string | undefined {
175
+ if (like === undefined || like === "") return undefined;
176
+ if (typeof like === "object") {
177
+ const s = iconSet() === "nerd" ? like.nerd : like.plain;
178
+ return s ? s : undefined;
179
+ }
180
+ if (iconSet() === "nerd") return like;
181
+ const kept = like.replace(PRIVATE_USE, "");
182
+ return kept.trim() ? kept : undefined;
183
+ }
184
+
185
+ /**
186
+ * A single-cell mark that is safe to draw: in the plain set a private-use glyph (a brand's own
187
+ * font) is replaced by `fallback`.
188
+ */
189
+ export function safeGlyph(glyph: string, fallback = "\u25CF"): string {
190
+ return iconSet() === "plain" && hasPrivateUse(glyph) ? fallback : glyph;
191
+ }
192
+
193
+ /** The usage circle for 0 to 100 percent, filled in eighths; a blank slot in the plain set. */
194
+ export function usageIcon(percent: number | undefined): string {
195
+ if (iconSet() === "plain") return ICONS.usage.plain;
196
+ const eighths = percent === undefined || !Number.isFinite(percent) ? 0 : Math.round((Math.max(0, Math.min(100, percent)) / 100) * 8);
197
+ return eighths === 0 ? ICONS.usage.nerd : String.fromCodePoint(USAGE_SLICE_BASE + eighths);
198
+ }
199
+
200
+ // ---- saving -----------------------------------------------------------------------------------
201
+
202
+ /** Save the user's setting into the state file, keeping its other keys. Best effort. */
203
+ export function saveIconSetting(set: IconSet | undefined, path = statePath()): void {
204
+ try {
205
+ let data: Record<string, unknown> = {};
206
+ if (existsSync(path)) {
207
+ try {
208
+ data = JSON.parse(readFileSync(path, "utf8")) ?? {};
209
+ } catch {
210
+ data = {};
211
+ }
212
+ }
213
+ if (set) data.icons = set;
214
+ else delete data.icons;
215
+ mkdirSync(dirname(path), { recursive: true });
216
+ writeFileSync(path, `${JSON.stringify(data, null, 2)}\n`);
217
+ } catch {
218
+ // the in-memory setting still applies for this run
219
+ }
220
+ }