pi-one-ui 0.1.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 (101) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +106 -0
  3. package/extensions/app/config/renderer.ts +452 -0
  4. package/extensions/app/config/shell.ts +2484 -0
  5. package/extensions/app/ownership.ts +18 -0
  6. package/extensions/app/panel.ts +533 -0
  7. package/extensions/app/presets.ts +36 -0
  8. package/extensions/features/agent-summary/core.ts +194 -0
  9. package/extensions/features/agent-summary/index.ts +37 -0
  10. package/extensions/features/compact-thinking.ts +1262 -0
  11. package/extensions/features/context.ts +857 -0
  12. package/extensions/features/reference/index.ts +643 -0
  13. package/extensions/features/reference/session.ts +278 -0
  14. package/extensions/features/reference/subagent.ts +218 -0
  15. package/extensions/features/shell/aliases.ts +28 -0
  16. package/extensions/features/shell/flush-docked-bash.ts +39 -0
  17. package/extensions/features/shell/startup-header.ts +357 -0
  18. package/extensions/features/shell/working-message.ts +226 -0
  19. package/extensions/index.ts +52 -0
  20. package/extensions/shell/accent-rail-editor.ts +112 -0
  21. package/extensions/shell/accent-rail-layout-patch.ts +530 -0
  22. package/extensions/shell/completion-menu.ts +186 -0
  23. package/extensions/shell/editor-metadata-format.ts +287 -0
  24. package/extensions/shell/editor-transfer.ts +73 -0
  25. package/extensions/shell/extension-status.ts +102 -0
  26. package/extensions/shell/footer-format.ts +388 -0
  27. package/extensions/shell/footer-layout.ts +144 -0
  28. package/extensions/shell/footer.ts +1035 -0
  29. package/extensions/shell/format.ts +577 -0
  30. package/extensions/shell/git.ts +434 -0
  31. package/extensions/shell/icons.ts +261 -0
  32. package/extensions/shell/index.ts +1659 -0
  33. package/extensions/shell/interaction-summary.ts +1194 -0
  34. package/extensions/shell/live-context.ts +82 -0
  35. package/extensions/shell/minimalist-editor.ts +548 -0
  36. package/extensions/shell/package-version.ts +675 -0
  37. package/extensions/shell/project-refresh.ts +130 -0
  38. package/extensions/shell/project-state.ts +60 -0
  39. package/extensions/shell/prototype-patch-registry.ts +183 -0
  40. package/extensions/shell/runtime.ts +915 -0
  41. package/extensions/shell/selector-border.ts +109 -0
  42. package/extensions/shell/session-lifecycle.ts +60 -0
  43. package/extensions/shell/settings-command.ts +2144 -0
  44. package/extensions/shell/settings-previews.ts +137 -0
  45. package/extensions/shell/state.ts +83 -0
  46. package/extensions/shell/style.ts +480 -0
  47. package/extensions/shell/telemetry.ts +90 -0
  48. package/extensions/shell/ui.ts +1326 -0
  49. package/extensions/shell/user-message-osc.ts +279 -0
  50. package/extensions/shell/user-message-styles.ts +266 -0
  51. package/extensions/shell/user-message.ts +226 -0
  52. package/extensions/shell/working-line-messages.ts +24 -0
  53. package/extensions/shell/working-line-spinners.ts +54 -0
  54. package/extensions/shell/working-line.ts +1603 -0
  55. package/extensions/tools/ansi-color.ts +44 -0
  56. package/extensions/tools/ansi-text.ts +52 -0
  57. package/extensions/tools/component-tree.ts +37 -0
  58. package/extensions/tools/format.ts +28 -0
  59. package/extensions/tools/fullscreen-detect.ts +11 -0
  60. package/extensions/tools/patch-keys.ts +158 -0
  61. package/extensions/tools/sgr-mouse.ts +59 -0
  62. package/extensions/tools/tool-loading-icon.ts +20 -0
  63. package/extensions/tools/tool-result-sanitize.ts +27 -0
  64. package/extensions/transcript/index.ts +65 -0
  65. package/extensions/transcript/renderer/compact-mode.ts +1443 -0
  66. package/extensions/transcript/renderer/default-mode.ts +735 -0
  67. package/extensions/transcript/renderer/index.ts +286 -0
  68. package/extensions/transcript/renderer/markdown-enhance.ts +325 -0
  69. package/extensions/transcript/renderer/mouse/hover.ts +175 -0
  70. package/extensions/transcript/renderer/mouse/interaction.ts +1016 -0
  71. package/extensions/transcript/renderer/mouse/layout.ts +207 -0
  72. package/extensions/transcript/renderer/mouse/packets.ts +96 -0
  73. package/extensions/transcript/renderer/mouse/scroll.ts +211 -0
  74. package/extensions/transcript/renderer/tool/diff/ATTRIBUTION.md +28 -0
  75. package/extensions/transcript/renderer/tool/diff/ansi-utils.ts +128 -0
  76. package/extensions/transcript/renderer/tool/diff/diff-component.ts +112 -0
  77. package/extensions/transcript/renderer/tool/diff/diff-edit-render.ts +255 -0
  78. package/extensions/transcript/renderer/tool/diff/diff-header.ts +184 -0
  79. package/extensions/transcript/renderer/tool/diff/diff-highlight.ts +131 -0
  80. package/extensions/transcript/renderer/tool/diff/diff-inline.ts +350 -0
  81. package/extensions/transcript/renderer/tool/diff/diff-layout.ts +870 -0
  82. package/extensions/transcript/renderer/tool/diff/diff-limits.ts +189 -0
  83. package/extensions/transcript/renderer/tool/diff/diff-palette.ts +436 -0
  84. package/extensions/transcript/renderer/tool/diff/diff-parse.ts +536 -0
  85. package/extensions/transcript/renderer/tool/diff/diff-presentation.ts +79 -0
  86. package/extensions/transcript/renderer/tool/diff/diff-renderer.ts +29 -0
  87. package/extensions/transcript/renderer/tool/diff/diff-text.ts +57 -0
  88. package/extensions/transcript/renderer/tool/diff/diff-write-render.ts +629 -0
  89. package/extensions/transcript/renderer/tool/diff/index.ts +147 -0
  90. package/extensions/transcript/renderer/tool/diff/line-width-safety.ts +100 -0
  91. package/extensions/transcript/renderer/tool/diff/shiki-highlight.ts +104 -0
  92. package/extensions/transcript/renderer/tool/diff/write-execution.ts +124 -0
  93. package/extensions/transcript/renderer/tool/grouping.ts +619 -0
  94. package/extensions/transcript/renderer/tool/message-display.ts +183 -0
  95. package/extensions/transcript/renderer/tool/names.ts +195 -0
  96. package/extensions/transcript/renderer/tool/result.ts +842 -0
  97. package/extensions/transcript/renderer/tool/show-more-hint.ts +42 -0
  98. package/extensions/transcript/renderer/transcript-refresh.ts +79 -0
  99. package/package.json +58 -0
  100. package/themes/cc-dark.json +91 -0
  101. package/themes/cc-light.json +91 -0
@@ -0,0 +1,186 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
3
+
4
+ export type CompletionRowsOptions = {
5
+ lines: string[];
6
+ width: number;
7
+ theme: Theme;
8
+ selectedPrefix: string;
9
+ ownedBackground: boolean;
10
+ };
11
+
12
+ export type CompletionPaletteOptions = {
13
+ lines: string[];
14
+ width: number;
15
+ theme: Theme;
16
+ renderSeparator: (text: string) => string;
17
+ ownedBackground: boolean;
18
+ };
19
+
20
+ const SGR_SEQUENCE = /(?:\x1b\[|\u009b)([0-9:;]*)m/g;
21
+
22
+ function normalizeC1Csi(content: string): string {
23
+ return content.replace(/\u009b([0-?]*[ -/]*[@-~])/g, "\x1b[$1");
24
+ }
25
+
26
+ function sgrBackgroundAction(parameters: string): "reset" | "set" | undefined {
27
+ let action: "reset" | "set" | undefined;
28
+ const values = (parameters || "0").split(";");
29
+ for (let index = 0; index < values.length; index++) {
30
+ const parameter = values[index] ?? "";
31
+ const primary =
32
+ parameter === ""
33
+ ? 0
34
+ : Number.parseInt(parameter.split(":", 1)[0] ?? "", 10);
35
+ if (primary === 38 || primary === 48 || primary === 58) {
36
+ if (primary === 48) action = "set";
37
+ if (!parameter.includes(":")) {
38
+ const mode = Number.parseInt(values[index + 1] ?? "", 10);
39
+ if (mode === 5) index += 2;
40
+ else if (mode === 2) index += 4;
41
+ }
42
+ continue;
43
+ }
44
+ if (primary === 0 || primary === 49) action = "reset";
45
+ else if (
46
+ (primary >= 40 && primary <= 47) ||
47
+ (primary >= 100 && primary <= 107)
48
+ )
49
+ action = "set";
50
+ }
51
+ return action;
52
+ }
53
+
54
+ function restoresOwnedBackground(sequence: string): boolean {
55
+ const parameters = sequence.slice(sequence.startsWith("\u009b") ? 1 : 2, -1);
56
+ return sgrBackgroundAction(parameters) === "reset";
57
+ }
58
+
59
+ function truncateTerminalLine(content: string, width: number): string {
60
+ const safeWidth = Math.max(0, width);
61
+ const normalized = normalizeC1Csi(content);
62
+ return visibleWidth(normalized) <= safeWidth
63
+ ? content
64
+ : truncateToWidth(normalized, safeWidth, "");
65
+ }
66
+
67
+ export function fillTerminalLine(content: string, width: number): string {
68
+ const truncated = truncateTerminalLine(content, width);
69
+ const renderedWidth = visibleWidth(normalizeC1Csi(truncated));
70
+ return `${truncated}${" ".repeat(Math.max(0, width - renderedWidth))}`;
71
+ }
72
+
73
+ export function applyOwnedSurfaceBackground(
74
+ theme: Theme,
75
+ text: string,
76
+ ): string {
77
+ try {
78
+ const background = theme.getBgAnsi("userMessageBg");
79
+ const restored = text.replace(SGR_SEQUENCE, (sequence) =>
80
+ restoresOwnedBackground(sequence) ? `${sequence}${background}` : sequence,
81
+ );
82
+ return `${background}${restored}\x1b[49m`;
83
+ } catch {
84
+ try {
85
+ let cursor = 0;
86
+ let rendered = "";
87
+ for (const match of text.matchAll(SGR_SEQUENCE)) {
88
+ if (!restoresOwnedBackground(match[0])) continue;
89
+ const before = text.slice(cursor, match.index);
90
+ if (before) rendered += theme.bg("userMessageBg", before);
91
+ rendered += match[0];
92
+ cursor = (match.index ?? 0) + match[0].length;
93
+ }
94
+ const trailing = text.slice(cursor);
95
+ if (trailing) rendered += theme.bg("userMessageBg", trailing);
96
+ return rendered || theme.bg("userMessageBg", text);
97
+ } catch {
98
+ return text;
99
+ }
100
+ }
101
+ }
102
+
103
+ export function replaceNativeSelectedPrefix(
104
+ line: string,
105
+ replacement: string,
106
+ ): string {
107
+ const selectedPrefix = /^((?:(?:\x1b\[|\u009b)[0-9:;]*m)*)→ /;
108
+ const match = line.match(selectedPrefix);
109
+ if (!match) return line;
110
+ return `${replacement}${match[1]}${line.slice(match[0].length)}`;
111
+ }
112
+
113
+ export function isNativeCompletionCountRow(line: string): boolean {
114
+ const withoutSgr = line.replace(/(?:\x1b\[|\u009b)[0-?]*[ -/]*m/g, "");
115
+ return /^\s*\(\d+\/\d+\)\s*$/.test(withoutSgr);
116
+ }
117
+
118
+ export function omitTrailingNativeCompletionCountRow(
119
+ lines: string[],
120
+ ): string[] {
121
+ return lines.length > 0 && isNativeCompletionCountRow(lines.at(-1) ?? "")
122
+ ? lines.slice(0, -1)
123
+ : lines;
124
+ }
125
+
126
+ export function renderCompletionRows({
127
+ lines,
128
+ width,
129
+ theme,
130
+ selectedPrefix,
131
+ ownedBackground,
132
+ }: CompletionRowsOptions): string[] {
133
+ return lines.map((line) => {
134
+ const content = fillTerminalLine(
135
+ replaceNativeSelectedPrefix(line, selectedPrefix),
136
+ width,
137
+ );
138
+ const surfaced = ownedBackground
139
+ ? applyOwnedSurfaceBackground(theme, content)
140
+ : content;
141
+ return truncateTerminalLine(surfaced, width);
142
+ });
143
+ }
144
+
145
+ function helpLabel(width: number): string {
146
+ const labels = [
147
+ " ↑↓ Navigate Enter Use Esc Close",
148
+ " ↑↓ Nav Enter Use Esc",
149
+ " ↑↓ Enter Esc",
150
+ ];
151
+ return (
152
+ labels.find((label) => visibleWidth(label) <= width) ?? labels.at(-1) ?? ""
153
+ );
154
+ }
155
+
156
+ /** Full-width, provenance-preserving completion shell for Opencode editor styles. */
157
+ export function renderCompletionPalette({
158
+ lines,
159
+ width,
160
+ theme,
161
+ renderSeparator,
162
+ ownedBackground,
163
+ }: CompletionPaletteOptions): string[] {
164
+ const resultLines = omitTrailingNativeCompletionCountRow(lines);
165
+ if (resultLines.length === 0) return [];
166
+ const safeWidth = Math.max(0, width);
167
+ const rows = renderCompletionRows({
168
+ lines: resultLines,
169
+ width: safeWidth,
170
+ theme,
171
+ selectedPrefix: " ",
172
+ ownedBackground,
173
+ });
174
+ const separator = renderSeparator("─".repeat(safeWidth));
175
+ if (safeWidth < 3)
176
+ return [...rows, truncateToWidth(separator, safeWidth, "")];
177
+ const helpText = fillTerminalLine(helpLabel(safeWidth), safeWidth);
178
+ const help = ownedBackground
179
+ ? applyOwnedSurfaceBackground(theme, helpText)
180
+ : helpText;
181
+ return [
182
+ ...rows,
183
+ truncateToWidth(separator, safeWidth, ""),
184
+ truncateToWidth(help, safeWidth, ""),
185
+ ];
186
+ }
@@ -0,0 +1,287 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+ import type { ZentuiConfig } from "../app/config/shell.ts";
3
+ import { type FormatToken, parseFooterFormat } from "./footer-format.ts";
4
+ import {
5
+ EDITOR_ACCENT_FALLBACK,
6
+ renderStyleForSourceOrFallback,
7
+ safeThemeFg,
8
+ } from "./style.ts";
9
+
10
+ export type EditorMetadataValues = {
11
+ model: string;
12
+ modelId: string;
13
+ modelName: string;
14
+ provider: string;
15
+ thinking: string;
16
+ sessionName: string;
17
+ };
18
+
19
+ type RenderedTokens = {
20
+ styled: string;
21
+ hasDynamic: boolean;
22
+ hasNonEmptyDynamic: boolean;
23
+ };
24
+
25
+ const ESC = 0x1b;
26
+ const BEL = 0x07;
27
+ const CAN = 0x18;
28
+ const SUB = 0x1a;
29
+ const C1_DCS = 0x90;
30
+ const C1_CSI = 0x9b;
31
+ const C1_ST = 0x9c;
32
+ const C1_OSC = 0x9d;
33
+ const C1_SOS = 0x98;
34
+ const C1_PM = 0x9e;
35
+ const C1_APC = 0x9f;
36
+
37
+ function consumeCsi(value: string, start: number): number {
38
+ for (let index = start; index < value.length; index++) {
39
+ const code = value.charCodeAt(index);
40
+ if (code === CAN || code === SUB) return index + 1;
41
+ if (code >= 0x40 && code <= 0x7e) return index + 1;
42
+ }
43
+ return value.length;
44
+ }
45
+
46
+ function consumeControlString(
47
+ value: string,
48
+ start: number,
49
+ allowBel: boolean,
50
+ ): number {
51
+ for (let index = start; index < value.length; index++) {
52
+ const code = value.charCodeAt(index);
53
+ if (code === CAN || code === SUB) return index + 1;
54
+ if (allowBel && code === BEL) return index + 1;
55
+ if (code === C1_ST) return index + 1;
56
+ if (code === ESC && value.charCodeAt(index + 1) === 0x5c) return index + 2;
57
+ }
58
+ return value.length;
59
+ }
60
+
61
+ function consumeEscape(value: string, start: number): number {
62
+ if (start + 1 >= value.length) return value.length;
63
+ const next = value.charCodeAt(start + 1);
64
+ if (next === 0x5b) return consumeCsi(value, start + 2);
65
+ if (next === 0x5d) return consumeControlString(value, start + 2, true);
66
+ if (next === 0x50 || next === 0x58 || next === 0x5e || next === 0x5f) {
67
+ return consumeControlString(value, start + 2, false);
68
+ }
69
+
70
+ let index = start + 1;
71
+ while (index < value.length) {
72
+ const code = value.charCodeAt(index);
73
+ if (code >= 0x20 && code <= 0x2f) {
74
+ index += 1;
75
+ continue;
76
+ }
77
+ return code >= 0x30 && code <= 0x7e ? index + 1 : index;
78
+ }
79
+ return value.length;
80
+ }
81
+
82
+ function isNormalizedWhitespace(code: number): boolean {
83
+ return (
84
+ code === 0x09 ||
85
+ code === 0x0a ||
86
+ code === 0x0b ||
87
+ code === 0x0c ||
88
+ code === 0x0d ||
89
+ code === 0x85 ||
90
+ code === 0x2028 ||
91
+ code === 0x2029
92
+ );
93
+ }
94
+
95
+ export function sanitizeEditorMetadataText(value: string): string {
96
+ let sanitized = "";
97
+ for (let index = 0; index < value.length; ) {
98
+ const code = value.charCodeAt(index);
99
+ if (code === ESC) {
100
+ index = consumeEscape(value, index);
101
+ continue;
102
+ }
103
+ if (code === C1_CSI) {
104
+ index = consumeCsi(value, index + 1);
105
+ continue;
106
+ }
107
+ if (code === C1_OSC) {
108
+ index = consumeControlString(value, index + 1, true);
109
+ continue;
110
+ }
111
+ if (
112
+ code === C1_DCS ||
113
+ code === C1_SOS ||
114
+ code === C1_PM ||
115
+ code === C1_APC
116
+ ) {
117
+ index = consumeControlString(value, index + 1, false);
118
+ continue;
119
+ }
120
+ if (isNormalizedWhitespace(code)) {
121
+ sanitized += " ";
122
+ do index += 1;
123
+ while (
124
+ index < value.length &&
125
+ isNormalizedWhitespace(value.charCodeAt(index))
126
+ );
127
+ continue;
128
+ }
129
+ if (code < 0x20 || (code >= 0x7f && code <= 0x9f)) {
130
+ index += 1;
131
+ continue;
132
+ }
133
+ sanitized += value[index];
134
+ index += 1;
135
+ }
136
+ return sanitized;
137
+ }
138
+
139
+ function editorThinkingStyle(
140
+ config: ZentuiConfig,
141
+ level: string,
142
+ ): string | undefined {
143
+ switch (level.toLowerCase()) {
144
+ case "minimal":
145
+ return (
146
+ config.colors.editorThinkingMinimal ?? config.colors.editorThinking
147
+ );
148
+ case "low":
149
+ return config.colors.editorThinkingLow ?? config.colors.editorThinking;
150
+ case "medium":
151
+ return config.colors.editorThinkingMedium ?? config.colors.editorThinking;
152
+ case "high":
153
+ return config.colors.editorThinkingHigh ?? config.colors.editorThinking;
154
+ case "xhigh":
155
+ return config.colors.editorThinkingXhigh ?? config.colors.editorThinking;
156
+ case "max":
157
+ return (
158
+ config.colors.editorThinkingMax ??
159
+ config.colors.editorThinkingXhigh ??
160
+ config.colors.editorThinking
161
+ );
162
+ default:
163
+ return config.colors.editorThinking;
164
+ }
165
+ }
166
+
167
+ function renderVariable(
168
+ name: string,
169
+ values: EditorMetadataValues,
170
+ uiTheme: Theme,
171
+ config: ZentuiConfig,
172
+ ): { plain: string; styled: string } {
173
+ const colorSource = config.components.editor.colorSource;
174
+ const thinking =
175
+ values.thinking.toLowerCase() === "off" ? "" : values.thinking;
176
+ const raw =
177
+ name === "model"
178
+ ? values.model
179
+ : name === "model_id"
180
+ ? values.modelId
181
+ : name === "model_name"
182
+ ? values.modelName
183
+ : name === "provider"
184
+ ? values.provider
185
+ : name === "thinking"
186
+ ? thinking
187
+ : name === "session_name"
188
+ ? values.sessionName
189
+ : "";
190
+ const plain = sanitizeEditorMetadataText(raw);
191
+ if (!plain) return { plain: "", styled: "" };
192
+
193
+ if (name === "model" || name === "model_id" || name === "model_name") {
194
+ return {
195
+ plain,
196
+ styled: renderStyleForSourceOrFallback(
197
+ uiTheme,
198
+ colorSource,
199
+ config.colors.editorModel,
200
+ EDITOR_ACCENT_FALLBACK,
201
+ plain,
202
+ ),
203
+ };
204
+ }
205
+ if (name === "provider") {
206
+ return {
207
+ plain,
208
+ styled: renderStyleForSourceOrFallback(
209
+ uiTheme,
210
+ colorSource,
211
+ config.colors.editorProvider,
212
+ "text",
213
+ plain,
214
+ ),
215
+ };
216
+ }
217
+ if (name === "thinking") {
218
+ return {
219
+ plain,
220
+ styled: renderStyleForSourceOrFallback(
221
+ uiTheme,
222
+ colorSource,
223
+ editorThinkingStyle(config, plain),
224
+ "muted",
225
+ plain,
226
+ ),
227
+ };
228
+ }
229
+ if (name === "session_name") {
230
+ return { plain, styled: safeThemeFg(uiTheme, "border", plain) };
231
+ }
232
+ return { plain: "", styled: "" };
233
+ }
234
+
235
+ function renderTokens(
236
+ tokens: FormatToken[],
237
+ values: EditorMetadataValues,
238
+ uiTheme: Theme,
239
+ config: ZentuiConfig,
240
+ ): RenderedTokens {
241
+ let styled = "";
242
+ let hasDynamic = false;
243
+ let hasNonEmptyDynamic = false;
244
+
245
+ for (const token of tokens) {
246
+ if (token.kind === "text") {
247
+ const plain = sanitizeEditorMetadataText(token.value);
248
+ if (plain) styled += safeThemeFg(uiTheme, "border", plain);
249
+ continue;
250
+ }
251
+ if (token.kind === "fill") {
252
+ hasDynamic = true;
253
+ continue;
254
+ }
255
+ if (token.kind === "var") {
256
+ hasDynamic = true;
257
+ const rendered = renderVariable(token.name, values, uiTheme, config);
258
+ styled += rendered.styled;
259
+ if (rendered.plain) hasNonEmptyDynamic = true;
260
+ continue;
261
+ }
262
+
263
+ const rendered = renderTokens(token.tokens, values, uiTheme, config);
264
+ const visible = !rendered.hasDynamic || rendered.hasNonEmptyDynamic;
265
+ hasDynamic = true;
266
+ if (visible) {
267
+ styled += rendered.styled;
268
+ hasNonEmptyDynamic = true;
269
+ }
270
+ }
271
+
272
+ return { styled, hasDynamic, hasNonEmptyDynamic };
273
+ }
274
+
275
+ export function renderEditorMetadataFormat(
276
+ format: string,
277
+ values: EditorMetadataValues,
278
+ uiTheme: Theme,
279
+ config: ZentuiConfig,
280
+ ): string {
281
+ return renderTokens(
282
+ parseFooterFormat(sanitizeEditorMetadataText(format)),
283
+ values,
284
+ uiTheme,
285
+ config,
286
+ ).styled;
287
+ }
@@ -0,0 +1,73 @@
1
+ export type EditorComponentFactory = (...args: never[]) => unknown;
2
+
3
+ export type EditorTransferUi<Factory = EditorComponentFactory> = {
4
+ getEditorText?: () => unknown;
5
+ setEditorText?: (text: string) => void;
6
+ setEditorComponent?: (factory: Factory | undefined) => void;
7
+ getEditorComponent?: () => Factory | undefined;
8
+ };
9
+
10
+ export type EditorTransferFailureReason =
11
+ | "unsupported-transfer-api"
12
+ | "editor-factory-snapshot-failed"
13
+ | "editor-text-snapshot-failed"
14
+ | "editor-text-preparation-failed"
15
+ | "editor-replacement-failed-with-rollback"
16
+ | "editor-replacement-rollback-failed";
17
+
18
+ export type EditorTransferResult =
19
+ | { ok: true }
20
+ | { ok: false; reason: EditorTransferFailureReason };
21
+
22
+ /**
23
+ * Prepare the active editor's public expanded text before Pi replaces its factory.
24
+ * This intentionally transfers prompt contents only; editor-private state is never inspected.
25
+ */
26
+ export function replaceEditorComponentWithExpandedText<Factory>(
27
+ ui: EditorTransferUi<Factory>,
28
+ factory: Factory | undefined,
29
+ ): EditorTransferResult {
30
+ if (
31
+ typeof ui.getEditorText !== "function" ||
32
+ typeof ui.setEditorText !== "function" ||
33
+ typeof ui.setEditorComponent !== "function" ||
34
+ typeof ui.getEditorComponent !== "function"
35
+ ) {
36
+ return { ok: false, reason: "unsupported-transfer-api" };
37
+ }
38
+
39
+ let previousFactory: Factory | undefined;
40
+ try {
41
+ previousFactory = ui.getEditorComponent();
42
+ } catch {
43
+ return { ok: false, reason: "editor-factory-snapshot-failed" };
44
+ }
45
+
46
+ let expandedText: unknown;
47
+ try {
48
+ expandedText = ui.getEditorText();
49
+ } catch {
50
+ return { ok: false, reason: "editor-text-snapshot-failed" };
51
+ }
52
+ if (typeof expandedText !== "string") {
53
+ return { ok: false, reason: "editor-text-snapshot-failed" };
54
+ }
55
+
56
+ try {
57
+ ui.setEditorText(expandedText);
58
+ } catch {
59
+ return { ok: false, reason: "editor-text-preparation-failed" };
60
+ }
61
+
62
+ try {
63
+ ui.setEditorComponent(factory);
64
+ } catch {
65
+ try {
66
+ ui.setEditorComponent(previousFactory);
67
+ return { ok: false, reason: "editor-replacement-failed-with-rollback" };
68
+ } catch {
69
+ return { ok: false, reason: "editor-replacement-rollback-failed" };
70
+ }
71
+ }
72
+ return { ok: true };
73
+ }
@@ -0,0 +1,102 @@
1
+ import { stripVTControlCharacters } from "node:util";
2
+ import type {
3
+ ExtensionStatusColorMode,
4
+ ExtensionStatusPlacement,
5
+ ZentuiConfig,
6
+ } from "../app/config/shell.ts";
7
+ import {
8
+ getExtensionStatusColorMode,
9
+ getExtensionStatusPlacement,
10
+ isExtensionStatusPlacement,
11
+ } from "../app/config/shell.ts";
12
+
13
+ export type ExtensionStatusSegment = {
14
+ key: string;
15
+ text: string;
16
+ placement: ExtensionStatusPlacement;
17
+ colorMode: ExtensionStatusColorMode;
18
+ };
19
+
20
+ export type ExtensionStatusSegmentsByPlacement = {
21
+ left: ExtensionStatusSegment[];
22
+ middle: ExtensionStatusSegment[];
23
+ right: ExtensionStatusSegment[];
24
+ };
25
+
26
+ const safeSgrPattern = /\x1b\[[0-9;:]*m/g;
27
+ const sgrPlaceholderPattern = /__ZENTUI_SGR_(\d+)__/g;
28
+
29
+ function compareKeys(
30
+ a: ExtensionStatusSegment,
31
+ b: ExtensionStatusSegment,
32
+ ): number {
33
+ return a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
34
+ }
35
+
36
+ function normalizeStatusWhitespace(value: string): string {
37
+ return value
38
+ .replace(/[\r\n\t\f\v]+/g, " ")
39
+ .replace(/[\u0000-\u001f\u007f-\u009f]/g, "")
40
+ .replace(/\s+/g, " ")
41
+ .trim();
42
+ }
43
+
44
+ export function sanitizeExtensionStatusText(value: string): string {
45
+ return normalizeStatusWhitespace(stripVTControlCharacters(value));
46
+ }
47
+
48
+ function hasVisibleStatusText(value: string): boolean {
49
+ return sanitizeExtensionStatusText(value).length > 0;
50
+ }
51
+
52
+ export function sanitizeExtensionStatusOriginalText(value: string): string {
53
+ const safeSequences: string[] = [];
54
+ const protectedValue = value.replace(safeSgrPattern, (sequence) => {
55
+ const index = safeSequences.push(sequence) - 1;
56
+ return `__ZENTUI_SGR_${index}__`;
57
+ });
58
+ const cleaned = normalizeStatusWhitespace(
59
+ stripVTControlCharacters(protectedValue),
60
+ );
61
+ const restored = cleaned.replace(
62
+ sgrPlaceholderPattern,
63
+ (_match, indexText: string) => {
64
+ const index = Number.parseInt(indexText, 10);
65
+ return safeSequences[index] ?? "";
66
+ },
67
+ );
68
+
69
+ return hasVisibleStatusText(restored) ? restored : "";
70
+ }
71
+
72
+ export function collectExtensionStatusSegments(
73
+ statuses: ReadonlyMap<string, string>,
74
+ config: ZentuiConfig,
75
+ ): ExtensionStatusSegmentsByPlacement {
76
+ const segments: ExtensionStatusSegmentsByPlacement = {
77
+ left: [],
78
+ middle: [],
79
+ right: [],
80
+ };
81
+
82
+ for (const [key, value] of statuses.entries()) {
83
+ const placement = getExtensionStatusPlacement(config, key);
84
+ if (placement === "off" || !isExtensionStatusPlacement(placement)) continue;
85
+ if (placement !== "left" && placement !== "middle" && placement !== "right")
86
+ continue;
87
+
88
+ const colorMode = getExtensionStatusColorMode(config, key);
89
+ const text =
90
+ colorMode === "original"
91
+ ? sanitizeExtensionStatusOriginalText(value)
92
+ : sanitizeExtensionStatusText(value);
93
+ if (!text) continue;
94
+
95
+ segments[placement].push({ key, text, placement, colorMode });
96
+ }
97
+
98
+ segments.left.sort(compareKeys);
99
+ segments.middle.sort(compareKeys);
100
+ segments.right.sort(compareKeys);
101
+ return segments;
102
+ }