gentle-pi 4.5.0 → 4.6.0

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 (243) hide show
  1. package/README.md +9 -6
  2. package/assets/agents/gentle-ai-verify.md +4 -0
  3. package/assets/agents/gentle-ai-worker.md +1 -0
  4. package/assets/migrations/agent-body-history.json +147 -0
  5. package/assets/orchestrator-delegation-reference.md +3 -3
  6. package/assets/orchestrator-delegation.md +2 -2
  7. package/assets/orchestrator-verification.md +10 -6
  8. package/assets/orchestrator.md +8 -8
  9. package/bin/gentle-shell.mjs +61 -26
  10. package/docs/ci-performance.md +11 -0
  11. package/docs/delegated-verification.md +6 -0
  12. package/docs/fast-mode.md +15 -0
  13. package/docs/gentle-agents-activity.md +8 -0
  14. package/docs/gentle-music.md +6 -3
  15. package/docs/gentle-shell.md +70 -20
  16. package/docs/install-wizard.md +1 -1
  17. package/docs/mcp-status.md +52 -0
  18. package/docs/prompt-budget.md +28 -0
  19. package/docs/readme-reference.md +82 -21
  20. package/docs/session-profile-format.md +20 -5
  21. package/docs/sound-notifications.md +1 -1
  22. package/docs/star-prompt.md +32 -0
  23. package/docs/work-continuity.md +46 -0
  24. package/extensions/ask-user-question.ts +1 -0
  25. package/extensions/codegraph-tools.ts +38 -4
  26. package/extensions/gentle-agents.ts +477 -50
  27. package/extensions/gentle-ai.ts +1046 -191
  28. package/extensions/gentle-fast.ts +61 -0
  29. package/extensions/gentle-guide.ts +174 -0
  30. package/extensions/gentle-herdr-activity.ts +21 -1
  31. package/extensions/gentle-herdr-agent.ts +144 -0
  32. package/extensions/gentle-music.ts +10 -0
  33. package/extensions/gentle-program-identity.ts +61 -0
  34. package/extensions/gentle-shell.ts +642 -97
  35. package/extensions/gentle-star-prompt.ts +334 -0
  36. package/extensions/gentle-stats.ts +5 -5
  37. package/extensions/gentle-todo.ts +42 -22
  38. package/extensions/history/store.ts +18 -12
  39. package/extensions/skill-registry.ts +35 -3
  40. package/extensions/startup-banner.ts +39 -7
  41. package/lib/agent-assets.ts +74 -17
  42. package/lib/agent-profiles.ts +1 -1
  43. package/lib/agents-config.ts +12 -3
  44. package/lib/agents-keys.ts +8 -16
  45. package/lib/agents-protocol.ts +80 -4
  46. package/lib/agents-runner.ts +105 -4
  47. package/lib/agents-view.ts +6 -1
  48. package/lib/agents-widget.ts +132 -9
  49. package/lib/bridge-cost.ts +28 -0
  50. package/lib/codemode-renderer.ts +16 -0
  51. package/lib/command-palette-catalog.ts +1 -0
  52. package/lib/command-palette.ts +21 -8
  53. package/lib/exploration-budget.ts +62 -0
  54. package/lib/gentle-guide.ts +201 -0
  55. package/lib/gentle-shell-launcher.ts +4 -0
  56. package/lib/herdr-activity.ts +9 -3
  57. package/lib/herdr-task-summary-policy.ts +85 -0
  58. package/lib/inprocess-reviewer.ts +33 -13
  59. package/lib/jobs-sidebar-state.ts +5 -6
  60. package/lib/jobs-widget.ts +16 -52
  61. package/lib/keymaps-customize.ts +81 -0
  62. package/lib/keymaps.ts +291 -0
  63. package/lib/model-fallback-notice.ts +61 -0
  64. package/lib/model-fallback-policy.ts +141 -0
  65. package/lib/model-fallback-store.ts +143 -0
  66. package/lib/model-routing-authority.ts +10 -2
  67. package/lib/nan-provider.ts +3 -2
  68. package/lib/native-review-cli.ts +7 -2
  69. package/lib/notification-customize.ts +48 -51
  70. package/lib/openai-fast-tier.ts +22 -0
  71. package/lib/orchestrator-discovery.ts +5 -1
  72. package/lib/orchestrator-fallback.ts +75 -0
  73. package/lib/pasted-image-paths.ts +113 -0
  74. package/lib/questionnaire/questionnaire-view.ts +121 -7
  75. package/lib/review-candidate-view-owner.ts +4 -0
  76. package/lib/review-candidate-view.ts +10 -7
  77. package/lib/review-host-relay.ts +5 -1
  78. package/lib/review-integration-v2.ts +22 -7
  79. package/lib/review-repository.ts +5 -0
  80. package/lib/session-profile-append-controller.ts +21 -6
  81. package/lib/session-profile-authority.ts +119 -0
  82. package/lib/session-profile-binding.ts +54 -5
  83. package/lib/session-profile-freeze.ts +105 -9
  84. package/lib/session-profile-integration.ts +313 -0
  85. package/lib/session-profile-persistence.ts +63 -9
  86. package/lib/shell-bar.ts +171 -56
  87. package/lib/shell-card.ts +26 -6
  88. package/lib/shell-page.ts +120 -0
  89. package/lib/shell-panel.ts +149 -0
  90. package/lib/shell-prompt.ts +53 -1
  91. package/lib/shell-sidebar-layout.ts +98 -25
  92. package/lib/shell-sidebar.ts +54 -1
  93. package/lib/shell-stats.ts +123 -0
  94. package/lib/shell-todo.ts +71 -0
  95. package/lib/shell-usage.ts +12 -2
  96. package/lib/star-prompt.ts +197 -0
  97. package/lib/verifier-admission.ts +18 -8
  98. package/lib/verifier-settle-reminder.ts +64 -0
  99. package/lib/vim-editor-adapter.ts +6 -1
  100. package/lib/visual-customization-policy.ts +41 -6
  101. package/lib/visual-customize-view.ts +164 -26
  102. package/lib/visual-layout-preview.ts +43 -0
  103. package/lib/yolo-session-policy.ts +28 -1
  104. package/package.json +1 -1
  105. package/runtime/gentle-shell-launcher.mjs +4 -0
  106. package/runtime/native-review-cli.mjs +7 -2
  107. package/runtime/review-integration-v2.mjs +22 -7
  108. package/runtime/windows-session-transport.ps1 +60 -3
  109. package/scripts/bootstrap.sh +4 -1
  110. package/scripts/installer-preflight.mjs +1 -1
  111. package/scripts/pi-update.mjs +113 -3
  112. package/scripts/run-test-suite.mjs +17 -1
  113. package/scripts/shell-snapshot.mjs +340 -0
  114. package/scripts/test-packed-runner.mjs +1 -1
  115. package/scripts/update-agent-body-history.mjs +41 -0
  116. package/scripts/verify-installer-tap.mjs +45 -0
  117. package/scripts/verify-package-files.mjs +2 -0
  118. package/skills/gentle-ai/SKILL.md +2 -2
  119. package/skills/tui-design/NOTICE.md +5 -0
  120. package/skills/tui-design/SKILL.md +56 -0
  121. package/skills/tui-design/references/commands.md +75 -0
  122. package/skills/tui-design/references/critique.md +48 -0
  123. package/skills/tui-design/references/design-doc.md +44 -0
  124. package/skills/tui-design/references/terminal-craft.md +64 -0
  125. package/skills/tui-design/references/visual-loop.md +32 -0
  126. package/tests/agents-protocol.test.ts +53 -1
  127. package/tests/agents-runner.test.ts +168 -3
  128. package/tests/agents-view.test.ts +27 -0
  129. package/tests/agents-widget.test.ts +312 -10
  130. package/tests/bounded-scan-contract.test.ts +39 -0
  131. package/tests/bridge-cost.test.ts +32 -0
  132. package/tests/bundled-install.test.ts +6 -4
  133. package/tests/ci-concurrency.test.ts +11 -0
  134. package/tests/ci-merge-base-identity.test.ts +114 -0
  135. package/tests/codegraph-tools.test.ts +69 -0
  136. package/tests/codemode-rendering.test.ts +22 -2
  137. package/tests/command-palette.test.ts +16 -2
  138. package/tests/commit-slice-signal.test.ts +11 -9
  139. package/tests/delegate-for-reason-contract.test.ts +5 -4
  140. package/tests/design-canvas-server.test.ts +6 -2
  141. package/tests/exploration-budget.test.ts +128 -0
  142. package/tests/fixtures/agent-assets/gentle-ai-worker.strict-tdd-era.md +122 -0
  143. package/tests/fixtures/measure-orchestrator-prompt.mjs +2 -1
  144. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +18 -10
  145. package/tests/fixtures/session-profile-v1/replay.ts +125 -0
  146. package/tests/fixtures/session-profile-v1/session-profile-authority.ts +113 -0
  147. package/tests/fixtures/session-profile-v1/session-profile-binding.ts +83 -0
  148. package/tests/fixtures/session-profile-v1/session-profile-disk-reader.ts +182 -0
  149. package/tests/fixtures/session-profile-v1/session-profile-freeze.ts +290 -0
  150. package/tests/fixtures/session-profile-v1/session-profile-persistence.ts +195 -0
  151. package/tests/fixtures/session-profile-v1/v1-inputs.ts +16 -0
  152. package/tests/fixtures/windows-pipe-availability.ps1 +26 -0
  153. package/tests/fixtures/windows-session-bootstrap.ps1 +6 -2
  154. package/tests/gentle-agents.test.ts +416 -21
  155. package/tests/gentle-ai-exploration-budget.test.ts +135 -0
  156. package/tests/gentle-ai.test.ts +1011 -37
  157. package/tests/gentle-fast.test.ts +73 -0
  158. package/tests/gentle-guide.test.ts +208 -0
  159. package/tests/gentle-herdr-activity.test.ts +76 -2
  160. package/tests/gentle-herdr-agent.test.ts +111 -0
  161. package/tests/gentle-music.test.ts +36 -1
  162. package/tests/gentle-program-identity.test.ts +197 -0
  163. package/tests/gentle-shell-bin.test.ts +49 -26
  164. package/tests/gentle-shell-launcher.test.ts +18 -2
  165. package/tests/gentle-shell.test.ts +1068 -37
  166. package/tests/gentle-stats.test.ts +15 -2
  167. package/tests/gentle-todo.test.ts +50 -4
  168. package/tests/herdr-task-summary-policy.test.ts +128 -0
  169. package/tests/history-store-private-mode.test.ts +40 -0
  170. package/tests/image-paste-chips.test.ts +42 -0
  171. package/tests/inprocess-reviewer.test.ts +122 -0
  172. package/tests/installer-posix-bootstrap.test.ts +67 -5
  173. package/tests/installer-server.test.ts +2 -2
  174. package/tests/installer-windows-diagnostics.test.ts +4 -5
  175. package/tests/isolated-config-home.ts +28 -0
  176. package/tests/jobs-widget.test.ts +25 -37
  177. package/tests/keymaps-customize.test.ts +114 -0
  178. package/tests/keymaps.test.ts +103 -0
  179. package/tests/maintainer/mcp-status.maintest.ts +88 -0
  180. package/tests/maintainer/pi-update-source.maintest.ts +116 -0
  181. package/tests/model-fallback-notice.test.ts +45 -0
  182. package/tests/model-fallback-policy.test.ts +83 -0
  183. package/tests/model-fallback-store.test.ts +111 -0
  184. package/tests/nan-provider.test.ts +4 -4
  185. package/tests/no-self-pause-contract.test.ts +19 -0
  186. package/tests/notification-customize.test.ts +58 -34
  187. package/tests/odd-routing-canonical-ratchet.test.ts +3 -3
  188. package/tests/odd-routing-contract.test.ts +1 -1
  189. package/tests/orchestrator-fallback.test.ts +82 -0
  190. package/tests/orchestrator-prompt-budget.test.ts +131 -0
  191. package/tests/package-manifest.test.ts +160 -7
  192. package/tests/pasted-image-paths.test.ts +118 -0
  193. package/tests/persona-reply-language.test.ts +61 -0
  194. package/tests/pi-update-launcher.test.ts +32 -8
  195. package/tests/pi-update-source.test.ts +162 -0
  196. package/tests/profile-fast-tier.test.ts +311 -0
  197. package/tests/profile-tier-footer.test.ts +79 -0
  198. package/tests/questionnaire-view.test.ts +150 -0
  199. package/tests/review-candidate-owner-sweep.test.ts +93 -0
  200. package/tests/review-candidate-view.test.ts +51 -0
  201. package/tests/review-controller-native-routing.test.ts +120 -6
  202. package/tests/review-gate.test.ts +24 -0
  203. package/tests/review-inspect-preflight.test.ts +197 -0
  204. package/tests/review-integration-v2-forward.test.ts +59 -0
  205. package/tests/review-repository.test.ts +52 -1
  206. package/tests/review-sidebar-state.test.ts +5 -5
  207. package/tests/run-test-suite.test.ts +61 -5
  208. package/tests/sensitive-path-tools.test.ts +74 -0
  209. package/tests/session-profile-append-controller.test.ts +63 -0
  210. package/tests/session-profile-authority.test.ts +259 -0
  211. package/tests/session-profile-binding.test.ts +15 -0
  212. package/tests/session-profile-extension.test.ts +615 -0
  213. package/tests/session-profile-freeze.test.ts +110 -2
  214. package/tests/session-profile-integration.test.ts +857 -0
  215. package/tests/session-profile-persistence.test.ts +57 -0
  216. package/tests/session-profile-v1-compat.test.ts +221 -0
  217. package/tests/shell-bar.test.ts +113 -55
  218. package/tests/shell-card.test.ts +13 -1
  219. package/tests/shell-page.test.ts +108 -0
  220. package/tests/shell-panel.test.ts +332 -0
  221. package/tests/shell-prompt.test.ts +54 -0
  222. package/tests/shell-render-cache.test.ts +5 -0
  223. package/tests/shell-sidebar-fullscreen.test.ts +12 -0
  224. package/tests/shell-sidebar-layout.test.ts +159 -27
  225. package/tests/shell-stats.test.ts +90 -0
  226. package/tests/shell-usage.test.ts +14 -0
  227. package/tests/skill-registry.test.ts +68 -1
  228. package/tests/star-prompt.test.ts +470 -0
  229. package/tests/startup-banner.test.ts +57 -1
  230. package/tests/task-size-routing-contract.test.ts +45 -1
  231. package/tests/verifier-settle-reminder.test.ts +281 -0
  232. package/tests/verify-first-launch-contract.test.ts +56 -5
  233. package/tests/verify-installer-tap.test.ts +57 -0
  234. package/tests/vim-editor-adapter.test.ts +2 -2
  235. package/tests/visual-customization-policy.test.ts +61 -7
  236. package/tests/visual-customize-view.test.ts +253 -8
  237. package/tests/visual-layout-preview.test.ts +28 -0
  238. package/tests/windows-session-bootstrap.test.ts +105 -2
  239. package/tests/work-continuity-contract.test.ts +86 -0
  240. package/tests/writer-surfaces.test.ts +12 -10
  241. package/tests/yolo-customize.test.ts +30 -11
  242. package/tests/yolo-mode-runtime.test.ts +4 -2
  243. package/tests/yolo-mode.test.ts +16 -2
@@ -4,6 +4,7 @@ import { isValidProfileName } from "./agent-profiles.ts";
4
4
  import {
5
5
  isSafeAgentName,
6
6
  isThinkingLevel,
7
+ isServiceTier,
7
8
  normalizeModelId,
8
9
  normalizeRoutingEntry,
9
10
  type AgentModelConfig,
@@ -27,16 +28,30 @@ export function isSessionProfileFamilyEntry(entry: unknown): boolean {
27
28
  }
28
29
 
29
30
  export type SessionProfileOrigin = "user" | "local" | "repo" | "global";
31
+ export type SessionProfileStartupOrigin = Exclude<SessionProfileOrigin, "user">;
32
+
33
+ /** The profile a session took at startup, with the layer that supplied it. */
34
+ export interface SessionProfileStartupProfile {
35
+ origin: SessionProfileStartupOrigin;
36
+ name: string;
37
+ modelProfiles: AgentModelConfig;
38
+ }
39
+
40
+ /** A known startup state (gentle-shell#2742, section 3): a profile, or none in any layer. */
41
+ export type SessionProfileStartupState = SessionProfileStartupProfile | "none";
30
42
 
31
43
  export interface SessionProfileBindPayload {
32
44
  kind: "bind";
33
45
  origin: SessionProfileOrigin;
34
46
  name: string;
35
47
  modelProfiles: AgentModelConfig;
48
+ /** Only on an explicit choice (`origin: "user"`); a startup record is its own startup state. */
49
+ startup?: SessionProfileStartupState;
36
50
  }
37
51
 
38
52
  export interface SessionProfileClearPayload {
39
53
  kind: "clear";
54
+ startup?: "none";
40
55
  }
41
56
 
42
57
  /** Public structural entry shape only; ordinary messages need no custom fields. */
@@ -49,7 +64,7 @@ export interface SessionProfileEntry {
49
64
  export type SessionProfileReadResult =
50
65
  | { status: "absent" }
51
66
  | { status: "bound"; binding: SessionProfileBindPayload }
52
- | { status: "cleared" }
67
+ | { status: "cleared"; startup?: "none" }
53
68
  | { status: "invalid" }
54
69
  | { status: "unsupported" };
55
70
 
@@ -69,7 +84,12 @@ function hasOwn(value: Record<string, unknown>, key: string): boolean {
69
84
 
70
85
  function isOrigin(value: unknown): value is SessionProfileOrigin {
71
86
  return (
72
- value === "user" ||
87
+ value === "user" || isStartupOrigin(value)
88
+ );
89
+ }
90
+
91
+ function isStartupOrigin(value: unknown): value is SessionProfileStartupOrigin {
92
+ return (
73
93
  value === "local" ||
74
94
  value === "repo" ||
75
95
  value === "global"
@@ -89,7 +109,7 @@ function readRoute(
89
109
  ? Object.fromEntries(
90
110
  Object.entries(value).filter(
91
111
  ([key, field]) =>
92
- !((key === "model" || key === "thinking") && field === undefined),
112
+ !((key === "model" || key === "thinking" || key === "tier") && field === undefined),
93
113
  ),
94
114
  )
95
115
  : value;
@@ -99,10 +119,12 @@ function readRoute(
99
119
  return undefined;
100
120
  if (hasOwn(route, "effort") && !isThinkingLevel(route.effort))
101
121
  return undefined;
122
+ if (hasOwn(route, "tier") && !isServiceTier(route.tier))
123
+ return undefined;
102
124
  // Project only own known fields. Unknown extras, even an unknown-only route,
103
125
  // carry no routing meaning. Thinking wins over legacy effort as elsewhere.
104
126
  const known = Object.fromEntries(
105
- ["model", "thinking", "effort"]
127
+ ["model", "thinking", "effort", "tier"]
106
128
  .filter((key) => hasOwn(route, key))
107
129
  .map((key) => [key, route[key]]),
108
130
  );
@@ -140,21 +162,52 @@ function readBind(
140
162
  if (!isOrigin(data.origin) || !isValidProfileName(data.name)) return undefined;
141
163
  const modelProfiles = readSnapshot(data.modelProfiles, encoderInput);
142
164
  if (modelProfiles === undefined) return undefined;
143
- return { kind: "bind", origin: data.origin, name: data.name, modelProfiles };
165
+ const binding: SessionProfileBindPayload = { kind: "bind", origin: data.origin, name: data.name, modelProfiles };
166
+ if (data.origin !== "user" || !hasOwn(data, "startup")) return binding;
167
+ // Older readers ignore the startup state, so a malformed one only leaves it
168
+ // unknown: it never invalidates the selection the record routes.
169
+ const startup = readStartup(data.startup, encoderInput);
170
+ return startup === undefined ? binding : { ...binding, startup };
171
+ }
172
+
173
+ function readStartup(
174
+ value: unknown,
175
+ encoderInput = false,
176
+ ): SessionProfileStartupState | undefined {
177
+ if (value === "none") return "none";
178
+ if (!isRecord(value) || !isStartupOrigin(value.origin)) return undefined;
179
+ const binding = readBind({ origin: value.origin, name: value.name, modelProfiles: value.modelProfiles }, encoderInput);
180
+ return binding && { origin: value.origin, name: binding.name, modelProfiles: binding.modelProfiles };
144
181
  }
145
182
 
146
183
  /** Create a detached user selection payload; never appends or claims durability. */
147
184
  export function createSessionProfileBind(
148
185
  name: string,
149
186
  modelProfiles: AgentModelConfig,
187
+ startup?: SessionProfileStartupState,
150
188
  ): SessionProfileBindPayload {
151
189
  const binding = readBind({ origin: "user", name, modelProfiles }, true);
152
190
  if (!binding) throw new TypeError("Invalid session profile binding");
153
- return binding;
191
+ if (startup === undefined) return binding;
192
+ const state = readStartup(startup, true);
193
+ if (state === undefined) throw new TypeError("Invalid session profile startup state");
194
+ return { ...binding, startup: state };
195
+ }
196
+
197
+ /** Create a detached startup record: the full normalized definition, orchestrator included. */
198
+ export function createSessionProfileStartupBind(
199
+ origin: SessionProfileStartupOrigin,
200
+ name: string,
201
+ modelProfiles: AgentModelConfig,
202
+ ): SessionProfileBindPayload {
203
+ const startup = isStartupOrigin(origin) ? readStartup({ origin, name, modelProfiles }, true) : undefined;
204
+ if (typeof startup !== "object") throw new TypeError("Invalid session profile startup binding");
205
+ return { kind: "bind", ...startup };
154
206
  }
155
207
 
156
- export function createSessionProfileClear(): SessionProfileClearPayload {
157
- return { kind: "clear" };
208
+ /** A legacy clear, or with `"none"` the record of a session started without a profile. */
209
+ export function createSessionProfileClear(startup?: "none"): SessionProfileClearPayload {
210
+ return startup === "none" ? { kind: "clear", startup } : { kind: "clear" };
158
211
  }
159
212
 
160
213
  /** Unknown family identifiers are terminal unsupported states, regardless of data. */
@@ -166,7 +219,8 @@ export function readSessionProfileEntry(
166
219
  return { status: "unsupported" };
167
220
  const data = entry.data;
168
221
  if (!isRecord(data) || !hasOwn(data, "kind")) return { status: "invalid" };
169
- if (data.kind === "clear") return { status: "cleared" };
222
+ if (data.kind === "clear")
223
+ return data.startup === "none" ? { status: "cleared", startup: "none" } : { status: "cleared" };
170
224
  if (data.kind !== "bind") return { status: "invalid" };
171
225
  const binding = readBind(data);
172
226
  return binding ? { status: "bound", binding } : { status: "invalid" };
package/lib/shell-bar.ts CHANGED
@@ -2,7 +2,10 @@ import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works
2
2
  import { GAUGE_CELLS, gaugeTone, paintGauge, renderGauge, type GaugePaint, type GaugeTone } from "./shell-gauge.ts";
3
3
  import { renderUsageBar, selectUsageLimit, type ProviderUsage, type UsageWindow } from "./shell-usage.ts";
4
4
  import { sanitizeTerminalText } from "./terminal-theme.ts";
5
- import { CARD_TONE, floatRows, panelInnerWidth, renderCard } from "./shell-card.ts";
5
+ import { HOVER_ROLE } from "./shell-hover.ts";
6
+ import { renderStatsRows, type SessionStats } from "./shell-stats.ts";
7
+ import { CARD_TONE, floatRows, paintSurfaceRow, panelInnerWidth, renderCard, surfaceOpener } from "./shell-card.ts";
8
+ import { clipPanelText, fitPanelLine, PANEL_ROW_INDENT, PANEL_SURFACE_ROLE, renderPanelHeader, renderPanelRow } from "./shell-panel.ts";
6
9
  import { REVIEW_SCOPE_UNAVAILABLE, REVIEW_SIDEBAR_LABELS, type ReviewSidebarSnapshot } from "./review-sidebar-state.ts";
7
10
  import type { VisualSettings } from "./visual-customization-policy.ts";
8
11
  import { renderChangesWidget, type ChangesModel } from "./shell-changes.ts";
@@ -19,6 +22,8 @@ export { gaugeTone, renderGauge, type GaugeTone };
19
22
  // verified without a live TUI.
20
23
 
21
24
  export interface ShellBarModel {
25
+ /** Session statistics for the Power user rail; absent elsewhere. */
26
+ stats?: SessionStats;
22
27
  review?: ReviewSidebarSnapshot;
23
28
  jobs?: RunningJobDisplay[];
24
29
  profile?: string;
@@ -29,12 +34,18 @@ export interface ShellBarModel {
29
34
  sessionName: string | undefined;
30
35
  modelId: string;
31
36
  effort: string | undefined;
37
+ /** Orchestrator tier configured in the named profile; not a server observation. */
38
+ profileTier?: "standard" | "fast";
32
39
  contextPercent: number | null;
33
40
  contextWindow: number;
34
41
  costTotal: number;
35
42
  subscription: boolean;
36
43
  usage: ProviderUsage | undefined;
37
44
  statuses: string[];
45
+ /** The permission mode published under its own status key, shown once in the status bar. */
46
+ permission?: { mode: string; detail?: string };
47
+ /** Statuses for the rail's Integrations: `statuses` without the permission keys. */
48
+ integrations?: string[];
38
49
  }
39
50
 
40
51
  // The live header row above the fullscreen rail: session identity plus the
@@ -211,68 +222,171 @@ function joinSegments(segments: string[], theme: ShellBarTheme): string {
211
222
 
212
223
  // Sidebar groups use structured fields, never positional compact-bar segments
213
224
  // or inferred meanings from opaque extension status strings.
214
- export function renderShellSidebarBar(model: ShellBarModel, theme: ShellBarTheme, width: number, presentation?: Presentation): string[] {
215
- const value = (text: string) => theme.fg(ROLE.VALUE, theme.bold(text));
225
+ // The fullscreen rail's Status, drawn as panel sections (design/shell-rework/02-proposal.html):
226
+ // Changes, Review (only with current-session RDD evidence) and Integrations.
227
+ // Location and model live in the header row; Integrations also identifies the
228
+ // effective agent profile. Opaque integration statuses wrap so none of their
229
+ // meaning is clipped, and the optional key hints close the rail.
230
+ export function renderShellSidebarBar(model: ShellBarModel, theme: ShellBarTheme, width: number, presentation?: Presentation, hints?: string, options: StatusSectionsOptions = {}): string[] {
231
+ return renderShellStatusSections(model, theme, width, presentation, hints, options).lines;
232
+ }
233
+
234
+ export type StatusSection = "session" | "changes" | "review" | "stats" | "integrations";
235
+ export type StatusTarget = { row: number; kind: "toggle"; section: StatusSection } | { row: number; kind: "open-changes" };
236
+ export interface StatusSectionsOptions {
237
+ /** Keep the session name (no title row shows it). */
238
+ session?: boolean;
239
+ /** Sections folded to their header. */
240
+ collapsed?: ReadonlySet<StatusSection>;
241
+ /** The pointer is over this section's header, or over the Changes row. */
242
+ hovered?: StatusSection | "open-changes";
243
+ }
244
+
245
+ /** The rail Status with its click targets: section headers collapse them and the Changes row opens /gentle:changes. */
246
+ export function renderShellStatusSections(model: ShellBarModel, theme: ShellBarTheme, width: number, presentation?: Presentation, hints?: string, options: StatusSectionsOptions = {}): { lines: string[]; targets: StatusTarget[] } {
216
247
  const label = (text: string) => theme.fg(ROLE.LABEL, text);
217
- const changes = model.changes;
218
- const branch = model.branch ? `${label("Branch")} ${value(model.branch)}` : "";
219
- // Pre-wrap values before indenting so Unicode/ANSI continuation lines keep
220
- // the same inset without consuming the card's right border.
221
- const innerWidth = panelInnerWidth(theme, width);
222
- const inset = Math.min(1, innerWidth - 1);
223
- // Model, effort, context, cost, and the per-model usage table now live in
224
- // the always-visible header row (and /gentle:usage for the full table);
225
- // this event-driven card keeps only what a footer/model-switch event does
226
- // not already refresh every frame.
227
- const groups: Array<{ title: string; lines: string[] }> = [
228
- {
229
- title: "Project",
230
- lines: [
231
- value(model.cwd),
232
- ...(branch ? [branch] : []),
233
- ...(model.sessionName ? [`${label("Session")} ${value(model.sessionName)}`] : []),
234
- ...(model.profile ? [`${label("Profile")} ${value(sanitizeStatus(model.profile))}`] : []),
235
- ],
236
- },
237
- ...(presentation?.visibility.changes === false ? [] : [{
238
- title: "Changes",
239
- lines: [
240
- changes?.files
241
- ? `${changes.files} ${changes.files === 1 ? "file" : "files"} · ${theme.fg("success", `+${changes.added}`)} ${theme.fg("error", `−${changes.deleted}`)}`
242
- : label("No captured changes"),
243
- label("/gentle:changes"),
244
- ],
245
- }]),
246
- ...(model.review && presentation?.visibility.rdd !== false ? [{
247
- title: "🌹 RDD",
248
- lines: [
249
- value(REVIEW_SIDEBAR_LABELS[model.review.state]),
248
+ const wrapped = (text: string, role: string) => wrapTextWithAnsi(text, Math.max(1, width - PANEL_ROW_INDENT)).map((line) => renderPanelRow(width, theme.fg(role, line)));
249
+ type Section = { key?: StatusSection; header?: string; rows: string[]; openChangesRow?: number };
250
+ const sections: Section[] = [];
251
+ const header = (key: StatusSection, title: string, count?: string, countRole?: string) => renderPanelHeader(theme, width, { title, count, countRole, open: !options.collapsed?.has(key), hovered: options.hovered === key });
252
+ // Without the top title row (header below the input) the session name has no
253
+ // other home, so the rail keeps it.
254
+ if (options.session && model.sessionName) {
255
+ sections.push({ key: "session", header: header("session", "Session"), rows: wrapped(sanitizeStatus(model.sessionName), ROLE.VALUE) });
256
+ }
257
+ if (presentation?.visibility.changes !== false) {
258
+ const changes = model.changes;
259
+ const command = options.hovered === "open-changes" ? theme.fg(HOVER_ROLE, "/gentle:changes") : label("/gentle:changes");
260
+ sections.push({
261
+ key: "changes",
262
+ header: header("changes", "Changes", changes?.files ? `${changes.files} ${changes.files === 1 ? "file" : "files"}` : "clean"),
263
+ rows: [renderPanelRow(width, changes?.files ? `${theme.fg("success", `+${changes.added}`)} ${theme.fg("error", `−${changes.deleted}`)}` : label("no captured changes"), command)],
264
+ openChangesRow: 0,
265
+ });
266
+ }
267
+ if (model.review && presentation?.visibility.rdd !== false) {
268
+ const needsYou = model.review.state === "consent";
269
+ sections.push({
270
+ key: "review",
271
+ header: header("review", "Review", needsYou ? "needs you" : undefined, "warning"),
272
+ rows: [
273
+ ...wrapped(REVIEW_SIDEBAR_LABELS[model.review.state], needsYou ? "warning" : ROLE.VALUE),
250
274
  // Unknown scope is an internal sentinel, not something the user acts on.
251
- ...(model.review.scope !== REVIEW_SCOPE_UNAVAILABLE ? [label(sanitizeStatus(model.review.scope))] : []),
275
+ ...(model.review.scope !== REVIEW_SCOPE_UNAVAILABLE ? wrapped(sanitizeStatus(model.review.scope), ROLE.LABEL) : []),
252
276
  ],
253
- }] : []),
254
- // Running jobs live in their own sidebar card (extensions/gentle-shell.ts
255
- // registers the "jobs" rail part); the compact bar keeps the count.
256
- { title: "Integrations", lines: model.statuses.length
257
- ? model.statuses.map((status) => theme.fg(ROLE.STATUS, sanitizeStatus(status)))
258
- : [label("No status reported")] },
259
- ];
260
- // Wrap and indent every group line before it reaches the card, so Unicode and
261
- // ANSI continuation lines keep the same inset without consuming the right border.
262
- const body = groups.flatMap((group, index) => [
263
- ...(index && (!presentation || presentation.density === "comfortable") ? [""] : []),
264
- ...(presentation?.density === "minimal" ? [] : [label(group.title)]),
265
- ...group.lines.flatMap((line) => wrapTextWithAnsi(line, innerWidth - inset).map((part) => " ".repeat(inset) + part)),
266
- ]);
267
- return renderCard({ title: "Status", body, tone: CARD_TONE.INFO }, theme, width, { expanded: true, panel: true });
277
+ });
278
+ }
279
+ // Power user (compact density) adds what the session spent, per model.
280
+ if (model.stats) {
281
+ sections.push({ key: "stats", header: header("stats", "Stats", formatCost(model.stats.cost, model.subscription)), rows: renderStatsRows(model.stats, theme, width, model.subscription) });
282
+ }
283
+ // The status bar shows the permission mode once; Integrations only says
284
+ // what it means, so neither the mode nor its banner repeats here.
285
+ const integrations = model.integrations ?? model.statuses;
286
+ const integrationRows = (text: string) => wrapTextWithAnsi(text, Math.max(1, width - PANEL_ROW_INDENT - 2))
287
+ .map((line, index) => renderPanelRow(width, `${label(index === 0 ? "- " : " ")}${line}`));
288
+ const permission = model.permission?.detail ? integrationRows(`${label("permissions")} ${theme.fg(ROLE.STATUS, sanitizeStatus(model.permission.detail))}`) : [];
289
+ const profile = model.profile ? sanitizeStatus(model.profile) : "";
290
+ const profileRows = profile
291
+ ? wrapTextWithAnsi(`${label("Agent profile:")} ${theme.fg(ROLE.VALUE, profile)}`, Math.max(1, width - PANEL_ROW_INDENT)).map((line) => renderPanelRow(width, line))
292
+ : [];
293
+ const count = integrations.length + (permission.length ? 1 : 0);
294
+ sections.push({
295
+ key: "integrations",
296
+ header: header("integrations", "Integrations", count ? String(count) : "none"),
297
+ rows: [...profileRows, ...permission, ...(integrations.length ? integrations.flatMap((status) => integrationRows(theme.fg(ROLE.STATUS, sanitizeStatus(status)))) : permission.length ? [] : [renderPanelRow(width, label("no status reported"))])],
298
+ });
299
+ if (hints) sections.push({ rows: [renderPanelRow(width, label(hints))] });
300
+ const gap = !presentation || presentation.density === "comfortable" ? [" ".repeat(Math.max(0, width))] : [];
301
+ const lines: string[] = [];
302
+ const targets: StatusTarget[] = [];
303
+ sections.forEach((section, index) => {
304
+ if (index) lines.push(...gap);
305
+ if (section.key && section.header) {
306
+ targets.push({ row: lines.length, kind: "toggle", section: section.key });
307
+ lines.push(section.header);
308
+ if (options.collapsed?.has(section.key)) return;
309
+ }
310
+ if (section.openChangesRow !== undefined) targets.push({ row: lines.length + section.openChangesRow, kind: "open-changes" });
311
+ lines.push(...section.rows);
312
+ });
313
+ return { lines, targets };
314
+ }
315
+
316
+ // The wide fullscreen chrome (design/shell-rework/02-proposal.html): a title row
317
+ // with the project identity above the transcript and the rail, and one status
318
+ // bar row below them. Both sit on the rail's panel surface.
319
+ const STATUS_BAR_DIVIDER = "│";
320
+ const paintChromeRow = (theme: ShellBarTheme, row: string) => paintSurfaceRow(row, surfaceOpener(theme, PANEL_SURFACE_ROLE));
321
+
322
+ /** `✿ name path` left, the session name and profile right; the path gives way first, so the profile always shows. */
323
+ export function renderShellTitleRow(model: ShellBarModel, theme: ShellBarTheme, width: number, options: { model?: boolean } = {}): string {
324
+ const target = Math.max(0, Math.floor(width));
325
+ const name = model.cwd.split("/").filter((part) => part.length > 0).pop() ?? model.cwd;
326
+ const left = `${theme.fg(ROLE.BRAND, "✿")} ${theme.fg(ROLE.VALUE, theme.bold(name))} ${theme.fg(ROLE.PATH, model.cwd)}`;
327
+ // Mobile: the narrow status bar leaves the model out, so the title row carries it.
328
+ const right = options.model
329
+ ? executionSegment(model.modelId, model.effort, theme)
330
+ : [model.sessionName ? theme.fg(ROLE.VALUE, sanitizeStatus(model.sessionName)) : "", model.profile ? theme.fg(ROLE.LABEL, sanitizeStatus(model.profile)) : ""]
331
+ .filter(Boolean).join(theme.fg(ROLE.SEPARATOR, " · "));
332
+ return paintChromeRow(theme, ` ${fitPanelLine(left, right, Math.max(0, target - 2))} `);
333
+ }
334
+
335
+ /**
336
+ * The status bar: branch, dirty count and a non-default permission mode on
337
+ * the left; model · effort, context, cost and usage on the right. Usage gives
338
+ * way first (gauges, secondary windows, the segment), then the model; the
339
+ * usage segment stays the click target that opens the usage view.
340
+ */
341
+ export function renderShellStatusBar(model: ShellBarModel, theme: ShellBarTheme, width: number, usageHint?: string, presentation?: Presentation, paint?: GaugePaint, extras: { jobs?: boolean } = {}): ShellHeaderChrome {
342
+ const target = Math.max(0, Math.floor(width));
343
+ const divider = ` ${theme.fg(ROLE.SEPARATOR, STATUS_BAR_DIVIDER)} `;
344
+ const join = (segments: string[]) => segments.filter(Boolean).join(divider);
345
+ const dirty = model.dirty ? theme.fg(ROLE.DIRTY, `±${model.dirty}`) : "";
346
+ const branch = [model.branch ? theme.fg(ROLE.BRANCH, model.branch) : "", dirty].filter(Boolean).join(" ");
347
+ const mode = model.permission && model.permission.mode !== "NORMAL" ? theme.fg("warning", theme.bold(sanitizeStatus(model.permission.mode))) : "";
348
+ // Without a rail (mobile) the running jobs keep their compact count here.
349
+ const runningJobs = extras.jobs ? (model.jobs?.filter((job) => job.status === undefined).length ?? 0) : 0;
350
+ const tail = join([mode, runningJobs ? theme.fg(ROLE.STATUS, shellJobsCount(runningJobs)) : ""]);
351
+ const left = join([branch, tail]);
352
+ const showCounters = presentation?.visibility.usageCost !== false;
353
+ const tier = model.profileTier ? ` ${theme.fg(ROLE.LABEL, "·")} ${theme.fg(model.profileTier === "fast" ? "warning" : ROLE.LABEL, model.profileTier === "fast" ? "Fast" : "Standard")}` : "";
354
+ const exec = presentation?.visibility.modelDetails === false ? "" : executionSegment(model.modelId, model.effort, theme);
355
+ const counters = showCounters ? [contextSegment(model.contextPercent, theme, paint), costSegment(model.costTotal, model.subscription, theme)] : [];
356
+ const windows = model.usage ? (selectUsageLimit(model.usage, model.modelId)?.windows ?? []) : [];
357
+ const stages: Array<UsageStage | undefined> = showCounters ? ["full", "text", "primary", undefined] : [undefined];
358
+ const attempts = [...stages.map((stage) => ({ stage, withExec: true, withTier: true })),
359
+ ...(tier ? [{ stage: undefined, withExec: true, withTier: false }] : []), { stage: undefined, withExec: false, withTier: false }];
360
+ for (const { stage, withExec, withTier } of attempts) {
361
+ const usage = stage ? usageSegmentText(windows, theme, stage, usageHint, paint) : "";
362
+ const right = join([withExec ? exec + (exec && withTier ? tier : "") : "", ...counters, usage]);
363
+ const room = target - 2;
364
+ if (visibleWidth(left) + (right ? RIGHT_PADDING : 0) + visibleWidth(right) > room) continue;
365
+ const row = ` ${left}${" ".repeat(room - visibleWidth(left) - visibleWidth(right))}${right} `;
366
+ const usageSpan = usage ? { start: target - 1 - visibleWidth(usage), end: target - 1 } : undefined;
367
+ return { rows: [paintChromeRow(theme, row)], headerRow: 0, ...(usageSpan ? { usageSpan } : {}) };
368
+ }
369
+ // Still too wide (a phone, a long branch): the branch gives way before the
370
+ // context and cost, which give way last, context after cost.
371
+ const room = Math.max(0, target - 2);
372
+ const tailWidth = tail ? visibleWidth(tail) + (branch ? visibleWidth(divider) : 0) : 0;
373
+ for (const right of [join(counters), counters[0] ?? "", ""]) {
374
+ const leftRoom = room - visibleWidth(right) - (right ? RIGHT_PADDING : 0);
375
+ const branchRoom = leftRoom - tailWidth;
376
+ if (branch && branchRoom < 4 && right) continue;
377
+ const fitted = join([branch ? clipPanelText(branch, Math.max(1, branchRoom)) : "", tail]);
378
+ if (visibleWidth(fitted) > leftRoom && right) continue;
379
+ return { rows: [paintChromeRow(theme, ` ${fitPanelLine(fitted, right, room)} `)], headerRow: 0 };
380
+ }
381
+ return { rows: [paintChromeRow(theme, ` ${fitPanelLine(left, "", room)} `)], headerRow: 0 };
268
382
  }
269
383
 
270
384
  const HEADER_BRAND = "✿ Gentle Shell";
271
385
 
272
386
  // Narrower than the width, widest first: dropping the profile, then the
273
- // effort, then the whole location keeps the brand and the bare model id
274
- // alive as long as anything can still share the row with the right-aligned
275
- // counters.
387
+ // effort, then the whole location keeps the brand and the model alive.
388
+ // Once location goes, restore effort if it fits before trying model-only
389
+ // alongside the right-aligned counters.
276
390
  function headerLeftStages(model: ShellHeaderModel, theme: ShellBarTheme, showModelDetails: boolean): string[][] {
277
391
  const brand = theme.fg(ROLE.BRAND, theme.bold(HEADER_BRAND));
278
392
  const location = locationSegment(model, theme);
@@ -284,6 +398,7 @@ function headerLeftStages(model: ShellHeaderModel, theme: ShellBarTheme, showMod
284
398
  [brand, location, withProfile],
285
399
  [brand, location, withEffort],
286
400
  [brand, location, modelOnly],
401
+ ...(model.effort ? [[brand, withEffort]] : []),
287
402
  [brand, modelOnly],
288
403
  [brand],
289
404
  ];
@@ -386,7 +501,7 @@ function headerContent(model: ShellHeaderModel, theme: ShellBarTheme, width: num
386
501
  .map((stage) => presentation?.density === "minimal" ? stage.slice(1) : stage);
387
502
  const minimalLeft = Math.max(0, leftStages.length - 2); // brand + bare model id, before dropping the model too
388
503
  // One flat, ordered cascade — never a per-stage nested search — so the
389
- // left group fully degrades (profile → effort → location) before usage
504
+ // left group fully degrades (profile → effort → location → restored effort) before usage
390
505
  // ever gives anything up, and usage fully degrades (gauges → secondary
391
506
  // windows → the whole segment) before ctx/cost is touched: every window
392
507
  // with its gauge, then text-only, then the first window only, then gone.
package/lib/shell-card.ts CHANGED
@@ -138,8 +138,7 @@ function frame(theme: CardTheme, tone: CardTone, text: string): string {
138
138
  return theme.fg(FRAME_ROLE[tone], text);
139
139
  }
140
140
 
141
- export function cardTop(card: Card, theme: CardTheme, width: number, hint?: string): string {
142
- const targetWidth = Math.max(0, Math.floor(width));
141
+ export function cardTop(card: Card, theme: CardTheme, width: number, hint?: string): string { const targetWidth = Math.max(0, Math.floor(width));
143
142
  if (targetWidth === 0) return "";
144
143
  if (targetWidth < 5) {
145
144
  const left = theme.fg(FRAME_ROLE[card.tone], "╭");
@@ -159,6 +158,17 @@ export function cardTop(card: Card, theme: CardTheme, width: number, hint?: stri
159
158
  return theme.fg(FRAME_ROLE[card.tone], chrome.topLeft) + frame(theme, card.tone, chrome.topLead) + styledTitle + frame(theme, card.tone, ` ${fill}`) + tail + frame(theme, card.tone, chrome.topRight);
160
159
  }
161
160
 
161
+ /**
162
+ * Whether a heading row keeps its key hint at this width. Callers that compose
163
+ * a subtitle from optional facts (a model, an effort) use it to shed the least
164
+ * important chip instead of silently losing the affordance.
165
+ */
166
+ export function headingFits(card: Card, hint: string | undefined, width: number): boolean {
167
+ const targetWidth = Math.max(0, Math.floor(width));
168
+ const head = visibleWidth(`${card.glyph ?? CARD_GLYPH} ${card.title}`) + (card.subtitle ? visibleWidth(card.subtitle) + 3 : 0);
169
+ return head + 5 + (hint ? visibleWidth(hint) + 2 : 0) <= targetWidth;
170
+ }
171
+
162
172
  export function cardLine(text: string, tone: CardTone, theme: CardTheme, width: number): string {
163
173
  const targetWidth = Math.max(0, Math.floor(width));
164
174
  if (targetWidth === 0) return "";
@@ -274,17 +284,27 @@ const BG_RESET = "\x1b[49m";
274
284
  // Full resets (pi-tui truncation inserts one) and background resets.
275
285
  const BG_CLEARING = /\x1b\[(?:0|49)?m/g;
276
286
 
277
- function panelOpener(theme: CardTheme, tone: CardTone): string {
287
+ /** The SGR that opens `role` as a background, or "" when the theme cannot paint it. */
288
+ export function surfaceOpener(theme: CardTheme, role: string): string {
278
289
  if (typeof theme.bg !== "function") return "";
279
290
  try {
280
- const painted = theme.bg(FLOAT_BG_ROLE[tone], "");
291
+ const painted = theme.bg(role, "");
281
292
  return painted.endsWith(BG_RESET) ? painted.slice(0, -BG_RESET.length) : "";
282
293
  } catch {
283
- // A theme without the tool background keeps the outlined card.
294
+ // A theme without the role keeps the row unpainted (the outlined card).
284
295
  return "";
285
296
  }
286
297
  }
287
298
 
299
+ /** Paints `row` behind the background `open` starts, re-armed after every reset the row carries. */
300
+ export function paintSurfaceRow(row: string, open: string): string {
301
+ return open ? `${open}${row.replace(BG_CLEARING, (reset) => reset + open)}${BG_RESET}` : row;
302
+ }
303
+
304
+ function panelOpener(theme: CardTheme, tone: CardTone): string {
305
+ return surfaceOpener(theme, FLOAT_BG_ROLE[tone]);
306
+ }
307
+
288
308
  /**
289
309
  * Draws one conversation card component in the active style. The outlined
290
310
  * style returns the parts unchanged; the float style renders them one margin
@@ -322,7 +342,7 @@ function floatOpener(theme: CardTheme, tone: CardTone, width: number): string {
322
342
  // Padding rows keep their tone-coloured accent just like content rows.
323
343
  function paintFloat(rows: readonly string[], open: string): string[] {
324
344
  const margin = " ".repeat(FLOAT_MARGIN);
325
- return rows.map((row) => `${margin}${open}${row.replace(BG_CLEARING, (reset) => reset + open)}${BG_RESET}${margin}`);
345
+ return rows.map((row) => `${margin}${paintSurfaceRow(row, open)}${margin}`);
326
346
  }
327
347
 
328
348
  /**
@@ -0,0 +1,120 @@
1
+ import { visibleWidth } from "@earendil-works/pi-tui";
2
+
3
+ // A light theme on a dark terminal leaves every unpainted cell (prose,
4
+ // gaps, the column between the conversation and the rail) on the terminal's
5
+ // dark background, with the terminal's light default text on top. The page
6
+ // paint gives those cells a paper background and the theme's text color.
7
+ // Dark themes keep the terminal background (and any wallpaper behind it).
8
+
9
+ /** Paper behind a light theme: a hair darker than white so cards and the rail still read as surfaces. */
10
+ const PAPER = { r: 243, g: 242, b: 241 };
11
+ const PAPER_256 = 255;
12
+ const IMAGE_LINE = /\x1b_G|\x1b\]1337;File=/;
13
+ const SGR = /\x1b\[([0-9;:]*)m/g;
14
+
15
+ export interface PageTheme {
16
+ appearance?: string;
17
+ getFgAnsi?(token: string): string;
18
+ getColorMode?(): string;
19
+ }
20
+ export interface PageColors { bg: string; fg: string }
21
+
22
+ /** The page colors for `theme`, or undefined when the terminal background should show. */
23
+ export function pageColors(theme: PageTheme): PageColors | undefined {
24
+ if (theme.appearance !== "light" || typeof theme.getFgAnsi !== "function") return undefined;
25
+ let fg = "";
26
+ try {
27
+ fg = theme.getFgAnsi("text");
28
+ } catch {
29
+ return undefined;
30
+ }
31
+ const bg = theme.getColorMode?.() === "256color" ? `\x1b[48;5;${PAPER_256}m` : `\x1b[48;2;${PAPER.r};${PAPER.g};${PAPER.b}m`;
32
+ return { bg, fg };
33
+ }
34
+
35
+ /** Which defaults an SGR sequence restores: its foreground, its background, or both. */
36
+ function resetsOf(params: string): { fg: boolean; bg: boolean } {
37
+ if (params === "") return { fg: true, bg: true };
38
+ const codes = params.split(";");
39
+ let fg = false;
40
+ let bg = false;
41
+ for (let i = 0; i < codes.length; i++) {
42
+ const code = Number(codes[i]);
43
+ // 38/48/58 carry a color: skip `5;n` or `2;r;g;b` so a 0 component is not read as a reset.
44
+ if (code === 38 || code === 48 || code === 58) {
45
+ i += Number(codes[i + 1]) === 5 ? 2 : Number(codes[i + 1]) === 2 ? 4 : 0;
46
+ continue;
47
+ }
48
+ if (code === 0) fg = bg = true;
49
+ else if (code === 39) fg = true;
50
+ else if (code === 49) bg = true;
51
+ }
52
+ return { fg, bg };
53
+ }
54
+
55
+ /** Paints one screen row on the page: padded to `width`, re-arming only what each reset clears. */
56
+ export function paintPageRow(line: string, width: number, page: PageColors): string {
57
+ if (IMAGE_LINE.test(line)) return line;
58
+ const body = line.replace(SGR, (sgr, params: string) => {
59
+ const reset = resetsOf(params);
60
+ return sgr + (reset.bg ? page.bg : "") + (reset.fg ? page.fg : "");
61
+ });
62
+ const pad = Math.max(0, Math.floor(width) - visibleWidth(line));
63
+ return `${page.bg}${page.fg}${body}${" ".repeat(pad)}\x1b[0m`;
64
+ }
65
+
66
+ type PageHost = {
67
+ applyLineResets?: (lines: string[]) => string[];
68
+ doRender?: () => void;
69
+ terminal?: { columns: number };
70
+ };
71
+
72
+ /**
73
+ * Paints the fullscreen frame on the page while `theme()` is light. It wraps
74
+ * the frame's last pass (after overlays, selection and search highlights), and
75
+ * only during a fullscreen render, so the document Pi leaves in the scrollback
76
+ * on exit keeps the terminal's colors. Returns the uninstaller.
77
+ */
78
+ export function installPagePaint(host: PageHost, theme: () => PageTheme): () => void {
79
+ const ownResets = Object.prototype.hasOwnProperty.call(host, "applyLineResets");
80
+ const ownRender = Object.prototype.hasOwnProperty.call(host, "doRender");
81
+ const resets = host.applyLineResets;
82
+ const render = host.doRender;
83
+ if (typeof resets !== "function" || typeof render !== "function") return () => undefined;
84
+ let painting: PageColors | undefined;
85
+ let active = true;
86
+ const applyPageResets = function (this: PageHost, lines: string[]) {
87
+ const done = resets.call(this, lines);
88
+ const page = active ? painting : undefined;
89
+ if (!page) return done;
90
+ const width = Math.max(1, this.terminal?.columns ?? 0);
91
+ return done.map((line) => paintPageRow(line, width, page));
92
+ };
93
+ const renderPage = function (this: PageHost) {
94
+ // A newer wrapper may still call this one after its owner shut down.
95
+ if (!active) return render.call(this);
96
+ // Recomputed every frame: Pi's theme is one stable proxy whose target
97
+ // changes on a switch, so an identity cache would never see it.
98
+ painting = pageColors(theme());
99
+ try {
100
+ render.call(this);
101
+ } finally {
102
+ painting = undefined;
103
+ }
104
+ };
105
+ host.applyLineResets = applyPageResets;
106
+ host.doRender = renderPage;
107
+ return () => {
108
+ if (!active) return;
109
+ active = false;
110
+ painting = undefined;
111
+ if (host.applyLineResets === applyPageResets) {
112
+ if (ownResets) host.applyLineResets = resets;
113
+ else delete host.applyLineResets;
114
+ }
115
+ if (host.doRender === renderPage) {
116
+ if (ownRender) host.doRender = render;
117
+ else delete host.doRender;
118
+ }
119
+ };
120
+ }