@narumitw/pi-starship 0.60.1 → 0.62.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 (114) hide show
  1. package/README.md +63 -6
  2. package/dist/chunks/chunk-43VIENBN.ts +1586 -0
  3. package/dist/chunks/chunk-43VIENBN.ts.map +7 -0
  4. package/dist/chunks/chunk-HPZTMIZS.ts +646 -0
  5. package/dist/chunks/chunk-HPZTMIZS.ts.map +7 -0
  6. package/dist/chunks/chunk-IYDZ3R2T.ts +69 -0
  7. package/dist/chunks/chunk-IYDZ3R2T.ts.map +7 -0
  8. package/dist/chunks/chunk-KP33I6BR.ts +579 -0
  9. package/dist/chunks/chunk-KP33I6BR.ts.map +7 -0
  10. package/dist/chunks/{chunk-KZZKGGFW.ts → chunk-PWTSHSP3.ts} +853 -1001
  11. package/dist/chunks/chunk-PWTSHSP3.ts.map +7 -0
  12. package/dist/chunks/{chunk-PD457PX5.ts → chunk-S2KBLHE2.ts} +75 -10
  13. package/dist/chunks/chunk-S2KBLHE2.ts.map +7 -0
  14. package/dist/chunks/chunk-XQUIQO2G.ts +20 -0
  15. package/dist/chunks/chunk-XQUIQO2G.ts.map +7 -0
  16. package/dist/chunks/{chunk-ADX4CY27.ts → chunk-XTLQ4WUL.ts} +1 -1
  17. package/dist/chunks/chunk-XTLQ4WUL.ts.map +7 -0
  18. package/dist/chunks/{cloud-EPAEV4ZB.ts → cloud-J2ZOE3HE.ts} +6 -2
  19. package/dist/chunks/cloud-J2ZOE3HE.ts.map +7 -0
  20. package/dist/chunks/command-configuration-menu-S2LXCOJG.ts +147 -0
  21. package/dist/chunks/command-configuration-menu-S2LXCOJG.ts.map +7 -0
  22. package/dist/chunks/command-settings-chat-O34BEU4X.ts +1041 -0
  23. package/dist/chunks/command-settings-chat-O34BEU4X.ts.map +7 -0
  24. package/dist/chunks/commands-ZYIJVIEJ.ts +1022 -0
  25. package/dist/chunks/commands-ZYIJVIEJ.ts.map +7 -0
  26. package/dist/chunks/{deployment-7J54EHNR.ts → deployment-NOJ2KCLI.ts} +85 -5
  27. package/dist/chunks/deployment-NOJ2KCLI.ts.map +7 -0
  28. package/dist/chunks/{development-IWJAAAEV.ts → development-T3XXVVDP.ts} +67 -15
  29. package/dist/chunks/development-T3XXVVDP.ts.map +7 -0
  30. package/dist/chunks/directory-OX6BWJZA.ts +31 -0
  31. package/dist/chunks/directory-OX6BWJZA.ts.map +7 -0
  32. package/dist/chunks/{execution-P4WZALW2.ts → execution-R2OHIP2L.ts} +8 -4
  33. package/dist/chunks/execution-R2OHIP2L.ts.map +7 -0
  34. package/dist/chunks/jujutsu-XLDYKSX2.ts +174 -0
  35. package/dist/chunks/jujutsu-XLDYKSX2.ts.map +7 -0
  36. package/dist/chunks/languages-CBQNNYXM.ts +262 -0
  37. package/dist/chunks/languages-CBQNNYXM.ts.map +7 -0
  38. package/dist/chunks/{package-H24VJEX3.ts → package-7KVAK3TC.ts} +6 -2
  39. package/dist/chunks/package-7KVAK3TC.ts.map +7 -0
  40. package/dist/chunks/system-574MHB4R.ts +165 -0
  41. package/dist/chunks/system-574MHB4R.ts.map +7 -0
  42. package/dist/index.ts +558 -150
  43. package/dist/index.ts.map +4 -4
  44. package/package.json +5 -1
  45. package/skills/configure-pi-starship/SKILL.md +14 -0
  46. package/skills/configure-pi-starship/references/configuration.md +109 -24
  47. package/skills/configure-pi-starship/references/module-catalog.md +278 -25
  48. package/skills/configure-pi-starship/references/modules.md +213 -36
  49. package/skills/configure-pi-starship/references/runtime-and-security.md +88 -28
  50. package/src/command-configuration-menu.ts +155 -0
  51. package/src/command-configuration.ts +9 -84
  52. package/src/command-preview.ts +3 -3
  53. package/src/command-settings-chat.ts +210 -0
  54. package/src/commands.ts +54 -98
  55. package/src/config/module-options.ts +112 -0
  56. package/src/config.ts +17 -53
  57. package/src/effective-config.ts +5 -4
  58. package/src/format/bounded-regex.ts +66 -0
  59. package/src/format/version.ts +24 -0
  60. package/src/modules/catalog.ts +10 -0
  61. package/src/modules/cloud.ts +1 -0
  62. package/src/modules/deployment.ts +8 -0
  63. package/src/modules/development.ts +20 -2
  64. package/src/modules/directory.ts +171 -51
  65. package/src/modules/execution.ts +2 -0
  66. package/src/modules/git/branch.ts +19 -4
  67. package/src/modules/git/commit.ts +9 -2
  68. package/src/modules/git/metrics.ts +9 -4
  69. package/src/modules/git/runtime.ts +122 -33
  70. package/src/modules/git/state.ts +23 -2
  71. package/src/modules/git/status-templates.ts +58 -0
  72. package/src/modules/git/status.ts +96 -30
  73. package/src/modules/jujutsu.ts +225 -0
  74. package/src/modules/languages.ts +26 -2
  75. package/src/modules/package.ts +1 -0
  76. package/src/modules/render.ts +42 -16
  77. package/src/modules/system.ts +54 -0
  78. package/src/modules/time-format.ts +188 -0
  79. package/src/modules/time.ts +11 -5
  80. package/src/modules/types.ts +42 -4
  81. package/src/pi-starship.ts +56 -12
  82. package/src/profile-store.ts +5 -0
  83. package/src/runtime/cloud.ts +3 -0
  84. package/src/runtime/command.ts +1 -1
  85. package/src/runtime/deployment.ts +120 -4
  86. package/src/runtime/development.ts +86 -13
  87. package/src/runtime/directory.ts +33 -0
  88. package/src/runtime/execution.ts +12 -2
  89. package/src/runtime/helpers.ts +57 -8
  90. package/src/runtime/jujutsu.ts +225 -0
  91. package/src/runtime/languages.ts +106 -19
  92. package/src/runtime/package.ts +3 -0
  93. package/src/runtime/system.ts +202 -0
  94. package/src/runtime/types.ts +3 -0
  95. package/src/runtime/version-requirements.ts +30 -0
  96. package/src/runtime/workspace.ts +12 -1
  97. package/src/settings-agent.ts +80 -0
  98. package/src/settings-chat-transcript.ts +140 -0
  99. package/src/settings-chat-ui.ts +426 -0
  100. package/src/settings-draft.ts +260 -0
  101. package/src/settings-snapshots.ts +41 -0
  102. package/dist/chunks/chunk-ADX4CY27.ts.map +0 -7
  103. package/dist/chunks/chunk-KZZKGGFW.ts.map +0 -7
  104. package/dist/chunks/chunk-PD457PX5.ts.map +0 -7
  105. package/dist/chunks/cloud-EPAEV4ZB.ts.map +0 -7
  106. package/dist/chunks/commands-C2VJ6ZBN.ts +0 -3374
  107. package/dist/chunks/commands-C2VJ6ZBN.ts.map +0 -7
  108. package/dist/chunks/deployment-7J54EHNR.ts.map +0 -7
  109. package/dist/chunks/development-IWJAAAEV.ts.map +0 -7
  110. package/dist/chunks/execution-P4WZALW2.ts.map +0 -7
  111. package/dist/chunks/languages-JO6R2PHL.ts +0 -168
  112. package/dist/chunks/languages-JO6R2PHL.ts.map +0 -7
  113. package/dist/chunks/package-H24VJEX3.ts.map +0 -7
  114. package/src/command-inspector.ts +0 -41
@@ -1,3374 +0,0 @@
1
- // @generated by scripts/build-runtime.mjs; do not edit.
2
- // @ts-nocheck -- the generated entry uses a .ts extension for Pi's Jiti loader.
3
- import {
4
- BUILT_IN_EXAMPLE,
5
- ConfigPublicationError,
6
- MODULE_DEFINITIONS,
7
- STARSHIP_SUBCOMMANDS,
8
- assertConfigDocumentUnchanged,
9
- atomicRestoreConfigDocument,
10
- atomicSaveConfigDocument,
11
- completeStarshipArguments,
12
- inspectUnavailableModules,
13
- loadStarshipConfig,
14
- readConfigDocumentSnapshot,
15
- removeConfigDocumentIfMatches,
16
- validateConfigDocument
17
- } from "./chunk-KZZKGGFW.ts";
18
-
19
- // src/commands.ts
20
- import { isKeyRelease as isKeyRelease2, Key as Key3, matchesKey as matchesKey3 } from "@earendil-works/pi-tui";
21
- import { defineMenu as defineMenu3, runMenu as runMenu3 } from "@narumitw/pi-tui-kit";
22
-
23
- // src/command-commit.ts
24
- import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
25
-
26
- // src/profile-store.ts
27
- import { randomUUID } from "node:crypto";
28
- import {
29
- closeSync,
30
- constants,
31
- fstatSync,
32
- fsyncSync,
33
- lstatSync,
34
- mkdirSync,
35
- openSync,
36
- readdirSync,
37
- readFileSync,
38
- realpathSync,
39
- renameSync,
40
- rmdirSync,
41
- unlinkSync,
42
- writeFileSync
43
- } from "node:fs";
44
- import { basename, dirname, join, parse, resolve, sep } from "node:path";
45
- var HISTORY_NAME = /^(\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}\.\d{3}Z)-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.toml$/u;
46
- var LEGACY_NAME = /^pi-starship-(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})\.toml$/u;
47
- var RESERVED_NAME = /^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]|conin\$|conout\$|clock\$)(?:\.|$)/iu;
48
- function normalizeProfileName(value) {
49
- const name = value.normalize("NFC");
50
- if ([...name].length < 1 || [...name].length > 80 || name !== name.trim() || name.startsWith(".") || name.endsWith(".") || /[\p{Cc}\p{Cf}\p{Cs}<>:"/\\|?*]/u.test(name) || RESERVED_NAME.test(name) || Buffer.byteLength(`${name}.toml`, "utf8") > 255) {
51
- throw new Error("Invalid profile name: use 1\u201380 characters without controls, path characters, or reserved names");
52
- }
53
- return name;
54
- }
55
- function trustedDirectory(path) {
56
- try {
57
- return realpathSync(path);
58
- } catch (error) {
59
- if (!isMissing(error)) throw error;
60
- const parent = dirname(path);
61
- if (parent === path) throw error;
62
- return join(trustedDirectory(parent), basename(path));
63
- }
64
- }
65
- function rootPath(settingsPath) {
66
- return join(trustedDirectory(dirname(resolve(settingsPath))), "pi-starship");
67
- }
68
- function profileDirectory(settingsPath) {
69
- return join(rootPath(settingsPath), "profiles");
70
- }
71
- function historyDirectory(settingsPath) {
72
- return join(rootPath(settingsPath), "history");
73
- }
74
- function isMissing(error) {
75
- return error.code === "ENOENT";
76
- }
77
- function statIfPresent(path) {
78
- try {
79
- return lstatSync(path, { bigint: true });
80
- } catch (error) {
81
- if (isMissing(error)) return void 0;
82
- throw error;
83
- }
84
- }
85
- function checkedDirectory(path, create = false) {
86
- const absolute = resolve(path);
87
- const root = parse(absolute).root;
88
- let current3 = root;
89
- for (const part of absolute.slice(root.length).split(sep).filter(Boolean)) {
90
- current3 = join(current3, part);
91
- let stat = statIfPresent(current3);
92
- let created = false;
93
- if (!stat && create) {
94
- try {
95
- mkdirSync(current3, { mode: 448 });
96
- } catch (error) {
97
- if (error.code !== "EEXIST") throw error;
98
- }
99
- stat = statIfPresent(current3);
100
- created = true;
101
- }
102
- if (!stat) return false;
103
- if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error(`Not a safe directory: ${current3}`);
104
- if (created) flushDirectory(dirname(current3));
105
- }
106
- return true;
107
- }
108
- function identity(stat) {
109
- return Object.freeze({ dev: stat.dev, ino: stat.ino, size: stat.size, mtimeNs: stat.mtimeNs, ctimeNs: stat.ctimeNs });
110
- }
111
- function sameIdentity(left, right) {
112
- return left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeNs === right.mtimeNs && left.ctimeNs === right.ctimeNs;
113
- }
114
- function sameFile(left, right) {
115
- return left.dev === right.dev && left.ino === right.ino;
116
- }
117
- function encodeDocument(rawDocument) {
118
- const bytes = Buffer.from(rawDocument, "utf8");
119
- if (bytes.toString("utf8") !== rawDocument) throw new Error("Document is not lossless UTF-8 text");
120
- return bytes;
121
- }
122
- function readBytes(path) {
123
- if (!checkedDirectory(dirname(path))) throw new Error(`Document directory is missing: ${dirname(path)}`);
124
- const before = statIfPresent(path);
125
- if (!before?.isFile() || before.isSymbolicLink()) throw new Error(`Not a regular document: ${path}`);
126
- const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
127
- try {
128
- const opened = fstatSync(fd, { bigint: true });
129
- if (!opened.isFile() || !sameIdentity(identity(before), identity(opened))) {
130
- throw new Error(`Document changed while opening: ${path}`);
131
- }
132
- const bytes = readFileSync(fd);
133
- const after = fstatSync(fd, { bigint: true });
134
- const published = statIfPresent(path);
135
- if (!sameIdentity(identity(opened), identity(after)) || !published || !sameIdentity(identity(after), identity(published))) {
136
- throw new Error(`Document changed while reading: ${path}`);
137
- }
138
- return { rawBytes: bytes, identity: identity(after) };
139
- } finally {
140
- closeSync(fd);
141
- }
142
- }
143
- function readProfile(settingsPath, name) {
144
- const normalized = normalizeProfileName(name);
145
- const path = join(profileDirectory(settingsPath), `${normalized}.toml`);
146
- const document = readBytes(path);
147
- const decoded = document.rawBytes.toString("utf8");
148
- const valid = Buffer.from(decoded, "utf8").equals(document.rawBytes);
149
- return Object.freeze({
150
- kind: "profile",
151
- name: normalized,
152
- path,
153
- ...document,
154
- rawDocument: valid ? decoded : void 0,
155
- ...valid ? {} : { readError: "Profile document is not valid UTF-8; raw bytes are preserved" }
156
- });
157
- }
158
- function listProfiles(settingsPath) {
159
- const directory = profileDirectory(settingsPath);
160
- if (!checkedDirectory(directory)) return [];
161
- const profiles = [];
162
- for (const filename of readdirSync(directory).sort()) {
163
- if (!filename.endsWith(".toml")) continue;
164
- const name = filename.slice(0, -5);
165
- try {
166
- if (normalizeProfileName(name) !== name) continue;
167
- } catch {
168
- continue;
169
- }
170
- const stat = statIfPresent(join(directory, filename));
171
- if (!stat?.isFile() || stat.isSymbolicLink()) continue;
172
- profiles.push(readProfile(settingsPath, name));
173
- }
174
- return profiles;
175
- }
176
- function mutate(settingsPath, operation) {
177
- const root = rootPath(settingsPath);
178
- checkedDirectory(root, true);
179
- const lock = join(root, ".mutation-lock");
180
- try {
181
- mkdirSync(lock, { mode: 448 });
182
- } catch (error) {
183
- if (error.code === "EEXIST") {
184
- throw new Error(`Profile/history storage is locked; inspect the owner before manually removing ${lock}`);
185
- }
186
- throw error;
187
- }
188
- const owned = lstatSync(lock, { bigint: true });
189
- let result;
190
- let operationError;
191
- let failed = false;
192
- try {
193
- result = operation();
194
- } catch (error) {
195
- failed = true;
196
- operationError = error;
197
- }
198
- try {
199
- const current3 = statIfPresent(lock);
200
- if (current3?.isDirectory() && sameFile(identity(owned), current3)) rmdirSync(lock);
201
- } catch (error) {
202
- if (failed) throw new AggregateError([operationError, error], `Mutation and lock cleanup failed at ${lock}`);
203
- throw new Error(`Mutation completed but lock cleanup failed at ${lock}`, { cause: error });
204
- }
205
- if (failed) throw operationError;
206
- return result;
207
- }
208
- function collisionKey(name) {
209
- return name.normalize("NFC").toUpperCase().toLowerCase().toUpperCase().toLowerCase().normalize("NFC");
210
- }
211
- function assertAvailable(directory, filename) {
212
- const key = collisionKey(filename);
213
- if (readdirSync(directory).some((entry) => collisionKey(entry) === key)) {
214
- throw new Error(`Document name already exists: ${filename}`);
215
- }
216
- }
217
- function assertExpected(current3, expected) {
218
- if (current3.kind !== expected.kind || current3.path !== expected.path || current3.name !== expected.name || current3.rawDocument !== expected.rawDocument || !current3.rawBytes.equals(expected.rawBytes) || !sameIdentity(current3.identity, expected.identity)) {
219
- throw new Error(`Document changed since review: ${current3.path}`);
220
- }
221
- }
222
- function flushDirectory(path) {
223
- if (process.platform === "win32") return;
224
- checkedDirectory(path);
225
- const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_DIRECTORY);
226
- try {
227
- fsyncSync(fd);
228
- } finally {
229
- closeSync(fd);
230
- }
231
- }
232
- function flushMutation(directory, path) {
233
- try {
234
- flushDirectory(directory);
235
- } catch (error) {
236
- throw new Error(`Mutation completed at ${path}, but directory flush failed: ${String(error)}`, { cause: error });
237
- }
238
- }
239
- function publish(directory, filename, bytes, beforeRename) {
240
- const temporary = join(directory, `.tmp-${randomUUID()}`);
241
- const fd = openSync(
242
- temporary,
243
- constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,
244
- 384
245
- );
246
- const owned = fstatSync(fd, { bigint: true });
247
- let open = true;
248
- try {
249
- writeFileSync(fd, bytes);
250
- fsyncSync(fd);
251
- closeSync(fd);
252
- open = false;
253
- checkedDirectory(directory);
254
- beforeRename();
255
- const destination = join(directory, filename);
256
- renameSync(temporary, destination);
257
- flushMutation(directory, destination);
258
- } finally {
259
- try {
260
- if (open) closeSync(fd);
261
- } finally {
262
- const current3 = statIfPresent(temporary);
263
- if (current3 && sameFile(identity(owned), current3)) unlinkSync(temporary);
264
- }
265
- }
266
- }
267
- function readTextProfile(settingsPath, name) {
268
- const document = readProfile(settingsPath, name);
269
- if (document.rawDocument === void 0) throw new Error(document.readError);
270
- return { ...document, rawDocument: document.rawDocument };
271
- }
272
- function createProfile(settingsPath, name, rawDocument) {
273
- const normalized = normalizeProfileName(name);
274
- const bytes = encodeDocument(rawDocument);
275
- return mutate(settingsPath, () => {
276
- const directory = profileDirectory(settingsPath);
277
- checkedDirectory(directory, true);
278
- const filename = `${normalized}.toml`;
279
- assertAvailable(directory, filename);
280
- publish(directory, filename, bytes, () => assertAvailable(directory, filename));
281
- return readTextProfile(settingsPath, normalized);
282
- });
283
- }
284
- function duplicateProfile(settingsPath, name, newName, expected) {
285
- const normalized = normalizeProfileName(newName);
286
- return mutate(settingsPath, () => {
287
- const current3 = readProfile(settingsPath, name);
288
- assertExpected(current3, expected);
289
- const directory = profileDirectory(settingsPath);
290
- const filename = `${normalized}.toml`;
291
- assertAvailable(directory, filename);
292
- publish(directory, filename, current3.rawBytes, () => {
293
- assertExpected(readProfile(settingsPath, name), expected);
294
- assertAvailable(directory, filename);
295
- });
296
- return readProfile(settingsPath, normalized);
297
- });
298
- }
299
- function saveProfile(settingsPath, name, rawDocument, expected) {
300
- const normalized = normalizeProfileName(name);
301
- const bytes = encodeDocument(rawDocument);
302
- return mutate(settingsPath, () => {
303
- const current3 = readProfile(settingsPath, normalized);
304
- assertExpected(current3, expected);
305
- if (current3.rawDocument === rawDocument) return { ...current3, rawDocument };
306
- publish(profileDirectory(settingsPath), `${normalized}.toml`, bytes, () => {
307
- assertExpected(readProfile(settingsPath, normalized), expected);
308
- });
309
- return readTextProfile(settingsPath, normalized);
310
- });
311
- }
312
- function renameProfile(settingsPath, name, newName, expected) {
313
- const normalized = normalizeProfileName(newName);
314
- return mutate(settingsPath, () => {
315
- const current3 = readProfile(settingsPath, name);
316
- assertExpected(current3, expected);
317
- if (current3.name === normalized) return current3;
318
- if (collisionKey(current3.name) === collisionKey(normalized))
319
- throw new Error("Case-only profile rename is not supported");
320
- const directory = profileDirectory(settingsPath);
321
- assertAvailable(directory, `${normalized}.toml`);
322
- assertExpected(readProfile(settingsPath, name), expected);
323
- const destination = join(directory, `${normalized}.toml`);
324
- renameSync(current3.path, destination);
325
- flushMutation(directory, destination);
326
- return readProfile(settingsPath, normalized);
327
- });
328
- }
329
- function deleteProfile(settingsPath, name, expected) {
330
- mutate(settingsPath, () => {
331
- const current3 = readProfile(settingsPath, name);
332
- assertExpected(current3, expected);
333
- unlinkSync(current3.path);
334
- flushMutation(dirname(current3.path), current3.path);
335
- });
336
- }
337
- function assertTimestamp(value) {
338
- const time = Date.parse(value);
339
- if (!Number.isFinite(time) || new Date(time).toISOString() !== value) throw new Error("Invalid history timestamp");
340
- }
341
- function historyLocation(settingsPath, name) {
342
- const modern = HISTORY_NAME.exec(name);
343
- if (modern) {
344
- const createdAt = modern[1].replace(/T(\d{2})-(\d{2})-(\d{2})/u, "T$1:$2:$3");
345
- assertTimestamp(createdAt);
346
- return { path: join(historyDirectory(settingsPath), name), legacy: false, createdAt };
347
- }
348
- const legacy = LEGACY_NAME.exec(name);
349
- if (legacy) {
350
- const createdAt = `${legacy[1]}-${legacy[2]}-${legacy[3]}T${legacy[4]}:${legacy[5]}`;
351
- assertTimestamp(`${createdAt}:00.000Z`);
352
- return { path: join(rootPath(settingsPath), name), legacy: true, createdAt };
353
- }
354
- throw new Error("Invalid history filename");
355
- }
356
- function readHistory(settingsPath, name) {
357
- const location = historyLocation(settingsPath, name);
358
- const document = readBytes(location.path);
359
- const decoded = document.rawBytes.toString("utf8");
360
- const valid = Buffer.from(decoded, "utf8").equals(document.rawBytes);
361
- return Object.freeze({
362
- kind: "history",
363
- name,
364
- ...location,
365
- ...document,
366
- rawDocument: valid ? decoded : void 0,
367
- ...valid ? {} : { readError: "Recovery document is not valid UTF-8; raw bytes are preserved" }
368
- });
369
- }
370
- function listHistory(settingsPath) {
371
- const history = [];
372
- for (const [directory, pattern] of [
373
- [historyDirectory(settingsPath), HISTORY_NAME],
374
- [rootPath(settingsPath), LEGACY_NAME]
375
- ]) {
376
- if (!checkedDirectory(directory)) continue;
377
- for (const name of readdirSync(directory).sort()) {
378
- if (!pattern.test(name)) continue;
379
- try {
380
- historyLocation(settingsPath, name);
381
- } catch (error) {
382
- if (error instanceof Error && error.message === "Invalid history timestamp") continue;
383
- throw error;
384
- }
385
- const stat = statIfPresent(join(directory, name));
386
- if (!stat?.isFile() || stat.isSymbolicLink()) continue;
387
- history.push(readHistory(settingsPath, name));
388
- }
389
- }
390
- return history.sort(
391
- (left, right) => Date.parse(right.createdAt) - Date.parse(left.createdAt) || left.name.localeCompare(right.name)
392
- );
393
- }
394
- function archiveConfigDocument(settingsPath, rawDocument) {
395
- const bytes = typeof rawDocument === "string" ? encodeDocument(rawDocument) : Buffer.from(rawDocument);
396
- return mutate(settingsPath, () => {
397
- const directory = historyDirectory(settingsPath);
398
- checkedDirectory(directory, true);
399
- const name = `${(/* @__PURE__ */ new Date()).toISOString().replace(/:/gu, "-")}-${randomUUID()}.toml`;
400
- publish(directory, name, bytes, () => assertAvailable(directory, name));
401
- return Object.freeze({ name, path: join(directory, name) });
402
- });
403
- }
404
- function deleteHistory(settingsPath, name, expected) {
405
- if (historyLocation(settingsPath, name).legacy) throw new Error("Legacy recovery files are read-only");
406
- mutate(settingsPath, () => {
407
- const current3 = readHistory(settingsPath, name);
408
- assertExpected(current3, expected);
409
- unlinkSync(current3.path);
410
- flushMutation(dirname(current3.path), current3.path);
411
- });
412
- }
413
-
414
- // src/command-commit.ts
415
- function captureCommitExpectation(options) {
416
- return {
417
- previous: options.getLoaded(),
418
- revision: options.getLoadedRevision?.(),
419
- disk: readConfigDocumentSnapshot(options.settingsPath)
420
- };
421
- }
422
- function commitOwnerCurrent(options, owner, expected) {
423
- const loaded = options.getLoaded();
424
- return !owner.signal.aborted && owner.isCurrent() && loaded.rawDocument === expected.previous.rawDocument && loaded.source === expected.previous.source && JSON.stringify(loaded.diagnostics) === JSON.stringify(expected.previous.diagnostics) && options.getLoadedRevision?.() === expected.revision;
425
- }
426
- async function commitActiveDocument(ctx, options, candidate, owner, expected, allowInvalid = false, checkCandidate) {
427
- const raw = candidate.rawDocument;
428
- if (raw === void 0) throw new Error("The candidate settings document is unavailable");
429
- return withFileMutationQueue(options.settingsPath, async () => {
430
- if (!commitOwnerCurrent(options, owner, expected)) return "cancel";
431
- checkCandidate?.();
432
- assertConfigDocumentUnchanged(options.settingsPath, expected.disk);
433
- const previousBytes = expected.disk.rawBytes;
434
- if (expected.previous.rawDocument !== previousBytes?.toString("utf8")) {
435
- throw new Error(
436
- "The active file differs from the loaded document. Reload and review it before replacing settings."
437
- );
438
- }
439
- const invalid = expected.previous.diagnostics.some((item) => item.severity === "error");
440
- if (invalid && !allowInvalid)
441
- throw new Error("The active settings document is invalid. Use explicit repair or recovery before replacing it.");
442
- validateConfigDocument(options.settingsPath, raw);
443
- if (previousBytes?.equals(Buffer.from(raw))) return "applied";
444
- let recoveryPath;
445
- if (previousBytes !== void 0) {
446
- recoveryPath = (options.archive ?? archiveConfigDocument)(options.settingsPath, previousBytes).path;
447
- }
448
- try {
449
- assertConfigDocumentUnchanged(options.settingsPath, expected.disk);
450
- if (!commitOwnerCurrent(options, owner, expected)) return "cancel";
451
- checkCandidate?.();
452
- } catch (error) {
453
- throw new Error(`${message(error)}.${recoveryNote(recoveryPath)}`);
454
- }
455
- let saved;
456
- try {
457
- saved = options.save ? options.save(options.settingsPath, raw) : atomicSaveConfigDocument(options.settingsPath, raw, {}, expected.disk);
458
- } catch (error) {
459
- if (error instanceof ConfigPublicationError) {
460
- const rollback = restorePrevious(ctx, options, owner, expected, raw, error.fileIdentity, false);
461
- throw new Error(`Footer settings were not saved: ${message(error)}. ${rollback}${recoveryNote(recoveryPath)}`);
462
- }
463
- throw new Error(
464
- `Footer settings were not saved: ${message(error)}. The previous footer remains active.${recoveryNote(recoveryPath)}`
465
- );
466
- }
467
- try {
468
- if (owner.signal.aborted || !(owner.isSessionCurrent?.() ?? owner.isCurrent()) || options.getLoadedRevision?.() !== expected.revision) {
469
- throw new Error("The configuration owner changed during publication");
470
- }
471
- options.apply(saved, ctx);
472
- } catch (error) {
473
- const rollback = restorePrevious(ctx, options, owner, expected, raw, saved.fileIdentity, true);
474
- throw new Error(
475
- `Footer settings could not be applied: ${message(error)}. ${rollback}${recoveryNote(recoveryPath)}`
476
- );
477
- }
478
- return "applied";
479
- });
480
- }
481
- function restorePrevious(ctx, options, owner, expected, raw, identity2, restoreRuntime) {
482
- try {
483
- if (owner.signal.aborted || !(owner.isSessionCurrent?.() ?? owner.isCurrent()))
484
- throw new Error("The session owner changed; stale restoration was blocked");
485
- const current3 = options.getLoaded();
486
- if (current3.rawDocument !== expected.previous.rawDocument && current3.rawDocument !== raw) {
487
- throw new Error("The active runtime changed; stale restoration was blocked");
488
- }
489
- if (!identity2) throw new Error("The saved settings document identity is unavailable");
490
- assertConfigDocumentUnchanged(options.settingsPath, { rawBytes: Buffer.from(raw), fileIdentity: identity2 });
491
- if (expected.disk.rawBytes === void 0) {
492
- removeConfigDocumentIfMatches(options.settingsPath, raw, identity2);
493
- } else if (options.restore && expected.disk.rawBytes.equals(Buffer.from(expected.previous.rawDocument ?? ""))) {
494
- options.restore(options.settingsPath, expected.previous.rawDocument ?? "");
495
- } else {
496
- atomicRestoreConfigDocument(
497
- options.settingsPath,
498
- expected.disk.rawBytes,
499
- {},
500
- { rawBytes: Buffer.from(raw), fileIdentity: identity2 }
501
- );
502
- }
503
- if (restoreRuntime) options.apply(expected.previous, ctx);
504
- return "The previous configuration was restored.";
505
- } catch (error) {
506
- return `Restoring the previous configuration also failed: ${message(error)}. Active path: ${options.settingsPath}.`;
507
- }
508
- }
509
- function recoveryNote(path) {
510
- return path ? ` Recovery copy retained: ${path}.` : "";
511
- }
512
- function message(error) {
513
- return error instanceof Error ? error.message : String(error);
514
- }
515
-
516
- // src/command-configuration.ts
517
- import { withFileMutationQueue as withFileMutationQueue2 } from "@earendil-works/pi-coding-agent";
518
- import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
519
-
520
- // src/command-preview.ts
521
- import { stripVTControlCharacters } from "node:util";
522
- import { Key, matchesKey, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
523
- import { runCustomInteraction } from "@narumitw/pi-tui-kit";
524
- var RESERVED_HOST_ROWS = 3;
525
- async function showPreviewActionMenu(ctx, title, body, items, signal, isCurrent = () => !signal?.aborted) {
526
- if (signal?.aborted || !isCurrent()) return { kind: "closed" };
527
- const result = await runCustomInteraction(ctx, {
528
- signal,
529
- isCurrent,
530
- create: ({ tui, theme, keybindings, complete }) => {
531
- let selectedIndex = 0;
532
- let scrollOffset = 0;
533
- let lastMaximumScroll = 0;
534
- let lastViewportSize = 1;
535
- let disposed = false;
536
- const requestRender = () => {
537
- if (!disposed) tui.requestRender();
538
- };
539
- const moveSelection = (delta) => {
540
- if (items.length === 0) return;
541
- selectedIndex = (selectedIndex + delta + items.length) % items.length;
542
- requestRender();
543
- };
544
- const movePreview = (offset) => {
545
- scrollOffset = Math.max(0, Math.min(offset, lastMaximumScroll));
546
- requestRender();
547
- };
548
- return {
549
- render(width) {
550
- const safeWidth = Math.max(1, width);
551
- const terminalRows = Number.isFinite(tui.terminal.rows) ? Math.floor(tui.terminal.rows) : 24;
552
- const availableRows = Math.max(1, terminalRows - RESERVED_HOST_ROWS);
553
- const bodyLines = body(safeWidth).flatMap((line) => line ? wrapTextWithAnsi(line, safeWidth) : [""]);
554
- const layout = allocateLayout(availableRows, items.length, bodyLines.length);
555
- lastViewportSize = layout.previewRows;
556
- lastMaximumScroll = Math.max(0, bodyLines.length - layout.previewRows);
557
- scrollOffset = Math.max(0, Math.min(scrollOffset, lastMaximumScroll));
558
- const actionStart = actionWindowStart(selectedIndex, items.length, layout.actionRows);
559
- const actionLines = items.slice(actionStart, actionStart + layout.actionRows).map((item, index) => {
560
- const absoluteIndex = actionStart + index;
561
- const prefix = absoluteIndex === selectedIndex ? "\u2192 " : " ";
562
- return theme.fg(
563
- absoluteIndex === selectedIndex ? "accent" : "text",
564
- `${prefix}${safeDisplayText(item.label)}`
565
- );
566
- });
567
- const position = layout.positionRows ? [theme.fg("dim", previewPosition(scrollOffset, layout.previewRows, bodyLines.length))] : [];
568
- const lines = [
569
- ...layout.titleRows ? [theme.fg("accent", theme.bold(safeDisplayText(title)))] : [],
570
- ...bodyLines.slice(scrollOffset, scrollOffset + layout.previewRows),
571
- ...position,
572
- ...actionLines,
573
- ...layout.hintRows ? [theme.fg("dim", previewHint(keybindings))] : []
574
- ];
575
- return lines.map((line) => truncateToWidth(line, safeWidth, ""));
576
- },
577
- invalidate() {
578
- },
579
- handleInput(data) {
580
- if (disposed) return;
581
- if (matchesKey(data, Key.ctrl("c"))) {
582
- complete({ kind: "closed" });
583
- } else if (keybindings.matches(data, "tui.select.cancel")) {
584
- complete({ kind: "cancelled" });
585
- } else if (keybindings.matches(data, "tui.select.up")) {
586
- moveSelection(-1);
587
- } else if (keybindings.matches(data, "tui.select.down")) {
588
- moveSelection(1);
589
- } else if (keybindings.matches(data, "tui.select.pageUp")) {
590
- movePreview(scrollOffset - lastViewportSize);
591
- } else if (keybindings.matches(data, "tui.select.pageDown")) {
592
- movePreview(scrollOffset + lastViewportSize);
593
- } else if (matchesKey(data, Key.home)) {
594
- movePreview(0);
595
- } else if (matchesKey(data, Key.end)) {
596
- movePreview(lastMaximumScroll);
597
- } else if (keybindings.matches(data, "tui.select.confirm")) {
598
- const item = items[selectedIndex];
599
- if (item) complete({ kind: "selected", value: item.value });
600
- }
601
- },
602
- dispose() {
603
- if (disposed) return;
604
- disposed = true;
605
- }
606
- };
607
- }
608
- });
609
- if (result.kind === "completed") return result.value;
610
- if (result.kind === "error") throw result.error;
611
- if (result.kind === "stale" && (signal?.aborted || !isCurrent())) return { kind: "closed" };
612
- return void 0;
613
- }
614
- function allocateLayout(availableRows, actionCount, bodyLineCount) {
615
- if (availableRows === 1) {
616
- return { titleRows: 0, previewRows: 0, positionRows: 0, actionRows: 1, hintRows: 0 };
617
- }
618
- const titleRows = availableRows >= 3 ? 1 : 0;
619
- const hintRows = availableRows >= 3 ? 1 : 0;
620
- const minimumPreviewRows = bodyLineCount > 0 && availableRows >= 4 ? 1 : 0;
621
- const availableActionRows = Math.max(1, availableRows - titleRows - hintRows - minimumPreviewRows);
622
- const actionRows = Math.min(Math.max(1, actionCount), availableActionRows);
623
- let previewRows = Math.max(0, availableRows - titleRows - hintRows - actionRows);
624
- const positionRows = previewRows >= 2 && bodyLineCount > previewRows ? 1 : 0;
625
- previewRows -= positionRows;
626
- return { titleRows, previewRows, positionRows, actionRows, hintRows };
627
- }
628
- function actionWindowStart(selectedIndex, itemCount, viewportSize) {
629
- if (itemCount <= viewportSize) return 0;
630
- return Math.max(0, Math.min(selectedIndex, itemCount - viewportSize));
631
- }
632
- function previewPosition(offset, viewportSize, lineCount) {
633
- if (lineCount === 0) return "0/0";
634
- return `${offset + 1}-${Math.min(lineCount, offset + viewportSize)}/${lineCount}`;
635
- }
636
- function previewHint(keybindings) {
637
- const up = bindingText(keybindings, "tui.select.up");
638
- const down = bindingText(keybindings, "tui.select.down");
639
- const confirm = bindingText(keybindings, "tui.select.confirm");
640
- const cancel = bindingText(keybindings, "tui.select.cancel", "ctrl+c");
641
- const pageUp = bindingText(keybindings, "tui.select.pageUp");
642
- const pageDown = bindingText(keybindings, "tui.select.pageDown");
643
- return [
644
- ...up || down ? [`${[up, down].filter(Boolean).join("/")} navigate`] : [],
645
- ...confirm ? [`${confirm} select`] : [],
646
- ...cancel ? [`${cancel} discard`] : [],
647
- "ctrl+c close",
648
- ...pageUp || pageDown ? [`${[pageUp, pageDown].filter(Boolean).join("/")} preview`] : []
649
- ].join(" \u2022 ");
650
- }
651
- function bindingText(keybindings, binding, excluded) {
652
- return keybindings.getKeys(binding).filter((key) => key !== excluded).map((key) => {
653
- if (key === "up") return "\u2191";
654
- if (key === "down") return "\u2193";
655
- if (key === "escape") return "esc";
656
- if (key === "return") return "enter";
657
- return safeDisplayText(key);
658
- }).join("/");
659
- }
660
- function safeDisplayText(value) {
661
- return Array.from(stripVTControlCharacters(value), (character) => {
662
- const codePoint = character.codePointAt(0) ?? 0;
663
- const control = codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
664
- return control ? "" : character;
665
- }).join("");
666
- }
667
-
668
- // src/effective-config.ts
669
- import { stringify } from "smol-toml";
670
- function projectEffectiveConfig(config) {
671
- const projected = {
672
- format: config.format
673
- };
674
- if (config.palette !== void 0) projected.palette = config.palette;
675
- projected.palettes = Object.fromEntries(
676
- sortedEntries(config.palettes).map(([name, colors]) => [name, sortedRecord(colors)])
677
- );
678
- for (const definition of MODULE_DEFINITIONS) {
679
- const module = config.modules[definition.name];
680
- const table = {
681
- format: module.format,
682
- symbol: module.symbol
683
- };
684
- if (definition.styleDefaults) {
685
- if (definition.fallbackStyle) table.style = module.style;
686
- for (const field of Object.keys(definition.styleDefaults)) {
687
- table[field] = module.styles[field] ?? "";
688
- }
689
- } else if (!definition.displayDefaults) {
690
- table.style = module.style;
691
- }
692
- if (definition.displayDefaults) {
693
- table.display = module.display.map((entry) => ({ ...entry }));
694
- }
695
- if (definition.styleRuleSelectors && module.styleRules.length > 0) {
696
- table.style_rules = module.styleRules.map((rule) => ({ ...rule.selectors, style: rule.style }));
697
- }
698
- table.disabled = module.disabled;
699
- for (const key of Object.keys(definition.options ?? {})) {
700
- table[key] = cloneOptionValue(module.options[key]);
701
- }
702
- if (definition.name === "extension_status") {
703
- table.separator = config.extensionStatus.separator;
704
- table.max_statuses = config.extensionStatus.maxStatuses;
705
- table.icons = sortedRecord(config.extensionStatus.icons);
706
- table.styles = sortedRecord(config.extensionStatus.styles);
707
- }
708
- projected[definition.name] = table;
709
- }
710
- return projected;
711
- }
712
- function serializeEffectiveConfig(config) {
713
- return stringify(projectEffectiveConfig(config));
714
- }
715
- function cloneOptionValue(value) {
716
- if (value === void 0) throw new Error("Missing normalized module option");
717
- if (Array.isArray(value)) return [...value];
718
- if (typeof value === "object") {
719
- return sortedRecord(value);
720
- }
721
- return value;
722
- }
723
- function sortedRecord(values) {
724
- return Object.fromEntries(sortedEntries(values));
725
- }
726
- function sortedEntries(values) {
727
- return Object.entries(values).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
728
- }
729
-
730
- // src/presets/bracketed-segments.ts
731
- var BRACKETED_SEGMENTS_PRESET = String.raw`# Font-safe bracketed segments inspired by Starship.
732
- format = "$brand$model$thinking$directory$git_branch$git_status$activity$context$time"
733
-
734
- [brand]
735
- format = '[\[$symbol\]]($style) '
736
- style = "bold white"
737
-
738
- [model]
739
- format = '[\[$symbol $model\]]($style) '
740
- symbol = "AI"
741
- style = "bold blue"
742
-
743
- [thinking]
744
- format = '[\[$symbol $level\]]($style) '
745
- symbol = "think"
746
- style = "bold purple"
747
-
748
- [directory]
749
- format = '[\[$symbol $path\]]($style) '
750
- symbol = "dir"
751
- style = "cyan bold"
752
-
753
- [git_branch]
754
- format = '[\[$symbol $branch\]]($style) '
755
- symbol = "git"
756
- style = "bold purple"
757
-
758
- [git_status]
759
- format = '[\[$all_status( $ahead_behind)\]]($style) '
760
- style = "red bold"
761
-
762
- [activity]
763
- format = '[\[$text\]]($style) '
764
- symbol = "run"
765
- style = "bold yellow"
766
-
767
- [context]
768
- format = '[\[$symbol $percentage\]]($style) '
769
- symbol = "ctx"
770
-
771
- [time]
772
- format = '[\[$time\]]($style)'
773
- symbol = ""
774
- style = "bold yellow"
775
- `;
776
-
777
- // src/presets/catppuccin-powerline.ts
778
- var CATPPUCCIN_POWERLINE_PRESET = `# Pi-native adaptation of Starship's Catppuccin Powerline preset.
779
- format = "[\uE0B6](red)$brand$model[\uE0B0](bg:peach fg:red)$directory[\uE0B0](bg:yellow fg:peach)$git_branch$git_status[\uE0B0](fg:yellow bg:green)$thinking$activity[\uE0B0](fg:green bg:sapphire)$context[\uE0B0](fg:sapphire bg:lavender)$time[\uE0B4](fg:lavender)"
780
- palette = "catppuccin_mocha"
781
-
782
- [brand]
783
- format = "[ $symbol ]($style)"
784
- symbol = "\uE285"
785
- style = "fg:crust bg:red bold"
786
-
787
- [model]
788
- format = "[$model ]($style)"
789
- symbol = ""
790
- style = "fg:crust bg:red bold"
791
-
792
- [directory]
793
- format = "[ $path ]($style)"
794
- symbol = ""
795
- style = "fg:crust bg:peach bold"
796
- truncation_length = 3
797
- truncation_symbol = "\u2026/"
798
-
799
- [git_branch]
800
- format = "[ $symbol $branch ]($style)"
801
- symbol = "\uF418"
802
- style = "fg:crust bg:yellow bold"
803
-
804
- [git_status]
805
- format = "[$all_status$ahead_behind ]($style)"
806
- style = "fg:crust bg:yellow bold"
807
-
808
- [thinking]
809
- format = "[ $symbol $level ]($style)"
810
- symbol = "\u{F051F}"
811
- style = "fg:crust bg:green bold"
812
-
813
- [activity]
814
- format = "[ $text ]($style)"
815
- symbol = "\u{F046E}"
816
- style = "fg:crust bg:green bold"
817
-
818
- [context]
819
- format = "[ $symbol $percentage ](fg:crust bg:sapphire bold)"
820
- symbol = "\u{F035B}"
821
-
822
- [[context.display]]
823
- threshold = 0
824
- style = "sapphire"
825
- hidden = false
826
-
827
- [time]
828
- format = "[ \uF43A $time ]($style)"
829
- symbol = ""
830
- style = "fg:crust bg:lavender bold"
831
-
832
- [palettes.catppuccin_mocha]
833
- red = "#f38ba8"
834
- peach = "#fab387"
835
- yellow = "#f9e2af"
836
- green = "#a6e3a1"
837
- sapphire = "#74c7ec"
838
- lavender = "#b4befe"
839
- crust = "#11111b"
840
-
841
- [palettes.catppuccin_frappe]
842
- red = "#e78284"
843
- peach = "#ef9f76"
844
- yellow = "#e5c890"
845
- green = "#a6d189"
846
- sapphire = "#85c1dc"
847
- lavender = "#babbf1"
848
- crust = "#232634"
849
-
850
- [palettes.catppuccin_latte]
851
- red = "#d20f39"
852
- peach = "#fe640b"
853
- yellow = "#df8e1d"
854
- green = "#40a02b"
855
- sapphire = "#209fb5"
856
- lavender = "#7287fd"
857
- crust = "#dce0e8"
858
-
859
- [palettes.catppuccin_macchiato]
860
- red = "#ed8796"
861
- peach = "#f5a97f"
862
- yellow = "#eed49f"
863
- green = "#a6da95"
864
- sapphire = "#7dc4e4"
865
- lavender = "#b7bdf8"
866
- crust = "#181926"
867
- `;
868
-
869
- // src/presets/gruvbox-rainbow.ts
870
- var GRUVBOX_RAINBOW_PRESET = `# Pi-native adaptation of Starship's Gruvbox Rainbow preset.
871
- format = "[\uE0B6](color_orange)$brand$model[\uE0B0](bg:color_yellow fg:color_orange)$directory[\uE0B0](fg:color_yellow bg:color_aqua)$git_branch$git_status[\uE0B0](fg:color_aqua bg:color_blue)$thinking$activity[\uE0B0](fg:color_blue bg:color_bg3)$context[\uE0B0](fg:color_bg3 bg:color_bg1)$time[\uE0B4](fg:color_bg1)"
872
- palette = "gruvbox_dark"
873
-
874
- [palettes.gruvbox_dark]
875
- color_fg0 = "#fbf1c7"
876
- color_bg1 = "#3c3836"
877
- color_bg3 = "#665c54"
878
- color_blue = "#458588"
879
- color_aqua = "#689d6a"
880
- color_green = "#98971a"
881
- color_orange = "#d65d0e"
882
- color_purple = "#b16286"
883
- color_red = "#cc241d"
884
- color_yellow = "#d79921"
885
-
886
- [brand]
887
- format = "[ $symbol ]($style)"
888
- symbol = "\uE285"
889
- style = "fg:color_fg0 bg:color_orange bold"
890
-
891
- [model]
892
- format = "[$model ]($style)"
893
- symbol = ""
894
- style = "fg:color_fg0 bg:color_orange bold"
895
-
896
- [directory]
897
- format = "[ $path ]($style)"
898
- symbol = ""
899
- style = "fg:color_fg0 bg:color_yellow bold"
900
- truncation_length = 3
901
- truncation_symbol = "\u2026/"
902
-
903
- [git_branch]
904
- format = "[ $symbol $branch ]($style)"
905
- symbol = "\uF418"
906
- style = "fg:color_fg0 bg:color_aqua bold"
907
-
908
- [git_status]
909
- format = "[$all_status$ahead_behind ]($style)"
910
- style = "fg:color_fg0 bg:color_aqua bold"
911
-
912
- [thinking]
913
- format = "[ $symbol $level ]($style)"
914
- symbol = "\u{F051F}"
915
- style = "fg:color_fg0 bg:color_blue bold"
916
-
917
- [activity]
918
- format = "[ $text ]($style)"
919
- symbol = "\u{F046E}"
920
- style = "fg:color_fg0 bg:color_blue bold"
921
-
922
- [context]
923
- format = "[ $symbol $percentage ](fg:color_fg0 bg:color_bg3 bold)"
924
- symbol = "\u{F035B}"
925
-
926
- [[context.display]]
927
- threshold = 0
928
- style = "color_bg3"
929
- hidden = false
930
-
931
- [time]
932
- format = "[ \uF43A $time ]($style)"
933
- symbol = ""
934
- style = "fg:color_fg0 bg:color_bg1 bold"
935
- `;
936
-
937
- // src/presets/jetpack.ts
938
- var JETPACK_PRESET = `# Pi-native adaptation of Starship's Jetpack preset.
939
- # Left-side session activity and right-side workspace context meet at $fill.
940
- format = "$activity$context$fill$directory$git_branch$git_state$git_status$time"
941
-
942
- [activity]
943
- format = "[\u25C4 $text ]($style)"
944
- symbol = ""
945
- style = "italic white"
946
-
947
- [context]
948
- format = "[\u25EF $percentage]($style) "
949
- symbol = ""
950
-
951
- [[context.display]]
952
- threshold = 0
953
- style = "bold purple"
954
- hidden = false
955
-
956
- [fill]
957
- symbol = " "
958
- style = "none"
959
-
960
- [directory]
961
- format = "[$path]($style) "
962
- symbol = ""
963
- style = "italic blue"
964
- truncation_length = 2
965
- truncation_symbol = "\u25A1 "
966
- home_symbol = "\u2302"
967
-
968
- [git_branch]
969
- format = "[$symbol$branch]($style)"
970
- symbol = "\u25B3 "
971
- style = "italic bright-blue"
972
- truncation_length = 11
973
- truncation_symbol = "\u22EF"
974
-
975
- [git_state]
976
- format = "([\u23AA$state $progress_current/$progress_total\u23A5]($style))"
977
- symbol = ""
978
- style = "italic bright-purple"
979
-
980
- [git_status]
981
- format = "([\u23AA$all_status$ahead_behind\u23A5]($style))"
982
- style = "bold italic bright-blue"
983
-
984
- [time]
985
- format = "[ $time]($style)"
986
- symbol = ""
987
- style = "italic dimmed white"
988
- `;
989
-
990
- // src/presets/minimal.ts
991
- var MINIMAL_PRESET = `# A compact, font-safe Pi footer.
992
- format = "$model$directory$git_branch$activity"
993
-
994
- [model]
995
- format = "[$model]($style) "
996
- symbol = ""
997
- style = "bold blue"
998
-
999
- [directory]
1000
- format = "[$path]($style) "
1001
- symbol = ""
1002
- style = "cyan bold"
1003
-
1004
- [git_branch]
1005
- format = "[git:$branch]($style) "
1006
- symbol = ""
1007
- style = "bold purple"
1008
-
1009
- [activity]
1010
- format = "[$text]($style)"
1011
- symbol = "*"
1012
- style = "bold yellow"
1013
- `;
1014
-
1015
- // src/presets/nerd-font-symbols.ts
1016
- var NERD_FONT_SYMBOLS_PRESET = `# Balanced Pi footer with Nerd Font symbols.
1017
- format = "$brand$model$thinking$directory$git_branch$git_status$activity$context$time"
1018
-
1019
- [brand]
1020
- symbol = "\uE285"
1021
-
1022
- [model]
1023
- symbol = "\u{F06A9}"
1024
-
1025
- [thinking]
1026
- symbol = "\u{F051F}"
1027
-
1028
- [directory]
1029
- symbol = "\u{F024B}"
1030
-
1031
- [git_branch]
1032
- symbol = "\uF418"
1033
-
1034
- [activity]
1035
- symbol = "\u{F046E}"
1036
-
1037
- [context]
1038
- symbol = "\u{F035B}"
1039
-
1040
- [time]
1041
- symbol = "\uF43A"
1042
- `;
1043
-
1044
- // src/presets/no-empty-icons.ts
1045
- var NO_EMPTY_ICONS_PRESET = `# Pi-native adaptation of Starship's No Empty Icons preset.
1046
- # Each label lives inside the same conditional group as its value.
1047
- format = "$model$thinking$directory$git_branch$git_status$activity$context$time"
1048
-
1049
- [model]
1050
- format = "([model $model]($style) )"
1051
- symbol = ""
1052
- style = "bold blue"
1053
-
1054
- [thinking]
1055
- format = "([thinking $level]($style) )"
1056
- symbol = ""
1057
- style = "bold purple"
1058
-
1059
- [directory]
1060
- format = "([in $path]($style) )"
1061
- symbol = ""
1062
- style = "cyan bold"
1063
-
1064
- [git_branch]
1065
- format = "([on $branch]($style) )"
1066
- symbol = ""
1067
- style = "bold purple"
1068
-
1069
- [git_status]
1070
- format = "([$all_status$ahead_behind]($style) )"
1071
- style = "red bold"
1072
-
1073
- [activity]
1074
- format = "([while $text]($style) )"
1075
- symbol = ""
1076
- style = "bold yellow"
1077
-
1078
- [context]
1079
- format = "([using $percentage context]($style) )"
1080
- symbol = ""
1081
-
1082
- [[context.display]]
1083
- threshold = 0
1084
- style = "bold green"
1085
- hidden = false
1086
-
1087
- [time]
1088
- format = "([at $time]($style))"
1089
- symbol = ""
1090
- style = "bold yellow"
1091
- `;
1092
-
1093
- // src/presets/no-nerd-font.ts
1094
- var NO_NERD_FONT_PRESET = `# Pi-native adaptation of Starship's No Nerd Font preset.
1095
- format = "$brand$model$thinking$directory$git_branch$git_status$activity$context$time"
1096
-
1097
- [brand]
1098
- format = "[$symbol]($style) "
1099
- symbol = "\u2726"
1100
- style = "bold white"
1101
-
1102
- [model]
1103
- format = "[$symbol $model]($style) "
1104
- symbol = "\u25C6"
1105
- style = "bold blue"
1106
-
1107
- [thinking]
1108
- format = "[$symbol $level]($style) "
1109
- symbol = "\u25C7"
1110
- style = "bold purple"
1111
-
1112
- [directory]
1113
- format = "[$symbol $path]($style) "
1114
- symbol = "\u2302"
1115
- style = "cyan bold"
1116
-
1117
- [git_branch]
1118
- format = "[$symbol $branch]($style) "
1119
- symbol = "\u2387"
1120
- style = "bold purple"
1121
-
1122
- [git_status]
1123
- format = "[$all_status( $ahead_behind)]($style) "
1124
- style = "red bold"
1125
-
1126
- [activity]
1127
- format = "[$text]($style) "
1128
- symbol = "\u25CF"
1129
- style = "bold yellow"
1130
-
1131
- [context]
1132
- format = "[$symbol $percentage]($style) "
1133
- symbol = "\u25CC"
1134
-
1135
- [[context.display]]
1136
- threshold = 0
1137
- style = "bold green"
1138
- hidden = false
1139
-
1140
- [time]
1141
- format = "[$symbol $time]($style)"
1142
- symbol = "\u25F4"
1143
- style = "bold yellow"
1144
- `;
1145
-
1146
- // src/presets/no-runtime-versions.ts
1147
- var NO_RUNTIME_VERSIONS_PRESET = `# Pi-native adaptation of Starship's No Runtime Versions preset.
1148
- # Model and thinking modules retain presence symbols while hiding version-like details.
1149
- format = "$brand$model$thinking$directory$git_branch$git_status$activity$context$time"
1150
-
1151
- [brand]
1152
- format = "[$symbol]($style) "
1153
- symbol = "\u03C0"
1154
- style = "bold white"
1155
-
1156
- [model]
1157
- format = "[$symbol]($style) "
1158
- symbol = "AI"
1159
- style = "bold blue"
1160
-
1161
- [thinking]
1162
- format = "[$symbol]($style) "
1163
- symbol = "think"
1164
- style = "bold purple"
1165
-
1166
- [directory]
1167
- format = "[$path]($style) "
1168
- symbol = ""
1169
- style = "cyan bold"
1170
-
1171
- [git_branch]
1172
- format = "[$symbol$branch]($style) "
1173
- symbol = "git:"
1174
- style = "bold purple"
1175
-
1176
- [git_status]
1177
- format = "[$all_status( $ahead_behind)]($style) "
1178
- style = "red bold"
1179
-
1180
- [activity]
1181
- format = "[$symbol]($style) "
1182
- symbol = "run"
1183
- style = "bold yellow"
1184
-
1185
- [context]
1186
- format = "[$percentage]($style) "
1187
- symbol = ""
1188
-
1189
- [[context.display]]
1190
- threshold = 0
1191
- style = "bold green"
1192
- hidden = false
1193
-
1194
- [time]
1195
- format = "[$time]($style)"
1196
- symbol = ""
1197
- style = "bold yellow"
1198
- `;
1199
-
1200
- // src/presets/pastel-powerline.ts
1201
- var PASTEL_POWERLINE_PRESET = `# Pi-native adaptation of Starship's Pastel Powerline preset.
1202
- format = "[\uE0B6](#9A348E)$brand$model[\uE0B0](bg:#DA627D fg:#9A348E)$directory[\uE0B0](fg:#DA627D bg:#FCA17D)$git_branch$git_status[\uE0B0](fg:#FCA17D bg:#86BBD8)$thinking$activity[\uE0B0](fg:#86BBD8 bg:#06969A)$context[\uE0B0](fg:#06969A bg:#33658A)$time[\uE0B4](fg:#33658A)"
1203
-
1204
- [brand]
1205
- format = "[ $symbol ]($style)"
1206
- symbol = "\uE285"
1207
- style = "fg:#ffffff bg:#9A348E bold"
1208
-
1209
- [model]
1210
- format = "[$model ]($style)"
1211
- symbol = ""
1212
- style = "fg:#ffffff bg:#9A348E bold"
1213
-
1214
- [directory]
1215
- format = "[ $path ]($style)"
1216
- symbol = ""
1217
- style = "fg:#ffffff bg:#DA627D bold"
1218
- truncation_length = 3
1219
- truncation_symbol = "\u2026/"
1220
-
1221
- [git_branch]
1222
- format = "[ $symbol $branch ]($style)"
1223
- symbol = "\uF418"
1224
- style = "fg:#1f1f1f bg:#FCA17D bold"
1225
-
1226
- [git_status]
1227
- format = "[$all_status$ahead_behind ]($style)"
1228
- style = "fg:#1f1f1f bg:#FCA17D bold"
1229
-
1230
- [thinking]
1231
- format = "[ $symbol $level ]($style)"
1232
- symbol = "\u{F051F}"
1233
- style = "fg:#1f1f1f bg:#86BBD8 bold"
1234
-
1235
- [activity]
1236
- format = "[ $text ]($style)"
1237
- symbol = "\u{F046E}"
1238
- style = "fg:#1f1f1f bg:#86BBD8 bold"
1239
-
1240
- [context]
1241
- format = "[ $symbol $percentage ](fg:#ffffff bg:#06969A bold)"
1242
- symbol = "\u{F035B}"
1243
-
1244
- [[context.display]]
1245
- threshold = 0
1246
- style = "#06969A"
1247
- hidden = false
1248
-
1249
- [time]
1250
- format = "[ \u2665 $time ]($style)"
1251
- symbol = ""
1252
- style = "fg:#ffffff bg:#33658A bold"
1253
- `;
1254
-
1255
- // src/presets/plain-text-symbols.ts
1256
- var PLAIN_TEXT_SYMBOLS_PRESET = `# Pi-native adaptation of Starship's Plain Text Symbols preset.
1257
- format = "$brand$model$thinking$directory$git_branch$git_status$activity$context$time"
1258
-
1259
- [brand]
1260
- format = "[$symbol]($style) "
1261
- symbol = "pi"
1262
- style = "bold white"
1263
-
1264
- [model]
1265
- format = "[$symbol $model]($style) "
1266
- symbol = "model"
1267
- style = "bold blue"
1268
-
1269
- [thinking]
1270
- format = "[$symbol $level]($style) "
1271
- symbol = "thinking"
1272
- style = "bold purple"
1273
-
1274
- [directory]
1275
- format = "[$symbol $path]($style) "
1276
- symbol = "dir"
1277
- style = "cyan bold"
1278
-
1279
- [git_branch]
1280
- format = "[$symbol $branch]($style) "
1281
- symbol = "git"
1282
- style = "bold purple"
1283
- truncation_symbol = "..."
1284
-
1285
- [git_status]
1286
- format = "[$all_status( $ahead_behind)]($style) "
1287
- style = "red bold"
1288
-
1289
- [activity]
1290
- format = "[$text]($style) "
1291
- symbol = "active"
1292
- style = "bold yellow"
1293
-
1294
- [context]
1295
- format = "[$symbol $percentage]($style) "
1296
- symbol = "context"
1297
-
1298
- [[context.display]]
1299
- threshold = 0
1300
- style = "bold green"
1301
- hidden = false
1302
-
1303
- [time]
1304
- format = "[$symbol $time]($style)"
1305
- symbol = "time"
1306
- style = "bold yellow"
1307
- `;
1308
-
1309
- // src/presets/pure-preset.ts
1310
- var PURE_PRESET = `# Pi-native adaptation of Starship's Pure preset.
1311
- format = "$directory$git_branch$git_state$git_status$activity\\n$model$thinking$context$fill$time"
1312
-
1313
- [directory]
1314
- format = "[$path]($style) "
1315
- symbol = ""
1316
- style = "blue"
1317
-
1318
- [git_branch]
1319
- format = "[$branch]($style) "
1320
- symbol = ""
1321
- style = "bright-black"
1322
-
1323
- [git_state]
1324
- format = '([($state( $progress_current/$progress_total))]($style) )'
1325
- symbol = ""
1326
- style = "bright-black"
1327
-
1328
- [git_status]
1329
- format = "[(*$all_status)](218) [$ahead_behind]($style) "
1330
- style = "cyan"
1331
-
1332
- [activity]
1333
- format = "[$text]($style) "
1334
- symbol = ""
1335
- style = "yellow"
1336
-
1337
- [model]
1338
- format = "[$model]($style) "
1339
- symbol = ""
1340
- style = "bright-black"
1341
-
1342
- [thinking]
1343
- format = "[$level]($style) "
1344
- symbol = ""
1345
- style = "bright-black"
1346
-
1347
- [context]
1348
- format = "[$percentage]($style)"
1349
- symbol = ""
1350
-
1351
- [[context.display]]
1352
- threshold = 0
1353
- style = "bright-black"
1354
- hidden = false
1355
-
1356
- [fill]
1357
- symbol = " "
1358
- style = "none"
1359
-
1360
- [time]
1361
- format = "[$time]($style)"
1362
- symbol = ""
1363
- style = "bright-black"
1364
- `;
1365
-
1366
- // src/presets/tokyo-night.ts
1367
- var TOKYO_NIGHT_PRESET = `# Pi-native adaptation of Starship's Tokyo Night preset.
1368
- format = "[\u2591\u2592\u2593](#a3aed2)$brand$model[\uE0B4](bg:#769ff0 fg:#a3aed2)$directory[\uE0B4](fg:#769ff0 bg:#394260)$git_branch$git_status[\uE0B4](fg:#394260 bg:#212736)$thinking$activity[\uE0B4](fg:#212736 bg:#1d2230)$context$time[\uE0B4](fg:#1d2230)"
1369
-
1370
- [brand]
1371
- format = "[ $symbol ]($style)"
1372
- symbol = "\uE285"
1373
- style = "fg:#090c0c bg:#a3aed2 bold"
1374
-
1375
- [model]
1376
- format = "[$model ]($style)"
1377
- symbol = ""
1378
- style = "fg:#090c0c bg:#a3aed2 bold"
1379
-
1380
- [directory]
1381
- format = "[ $path ]($style)"
1382
- symbol = ""
1383
- style = "fg:#e3e5e5 bg:#769ff0 bold"
1384
- truncation_length = 3
1385
- truncation_symbol = "\u2026/"
1386
-
1387
- [git_branch]
1388
- format = "[ $symbol $branch ]($style)"
1389
- symbol = "\uF418"
1390
- style = "fg:#769ff0 bg:#394260 bold"
1391
-
1392
- [git_status]
1393
- format = "[$all_status$ahead_behind ]($style)"
1394
- style = "fg:#769ff0 bg:#394260 bold"
1395
-
1396
- [thinking]
1397
- format = "[ $symbol $level ]($style)"
1398
- symbol = "\u{F051F}"
1399
- style = "fg:#769ff0 bg:#212736 bold"
1400
-
1401
- [activity]
1402
- format = "[ $text ]($style)"
1403
- symbol = "\u{F046E}"
1404
- style = "fg:#769ff0 bg:#212736 bold"
1405
-
1406
- [context]
1407
- format = "[ $symbol $percentage ](fg:#a0a9cb bg:#1d2230 bold)"
1408
- symbol = "\u{F035B}"
1409
-
1410
- [[context.display]]
1411
- threshold = 0
1412
- style = "#1d2230"
1413
- hidden = false
1414
-
1415
- [time]
1416
- format = "[\uF43A $time ]($style)"
1417
- symbol = ""
1418
- style = "fg:#a0a9cb bg:#1d2230 bold"
1419
- `;
1420
-
1421
- // src/presets/catalog.ts
1422
- var STARSHIP_PRESETS = [
1423
- {
1424
- id: "minimal",
1425
- label: "Minimal",
1426
- description: "Compact Pi essentials \xB7 font-safe",
1427
- requiresNerdFont: false,
1428
- rawDocument: MINIMAL_PRESET
1429
- },
1430
- {
1431
- id: "bracketed-segments",
1432
- label: "Bracketed Segments",
1433
- description: "Balanced Pi and Git details in brackets \xB7 font-safe",
1434
- requiresNerdFont: false,
1435
- rawDocument: BRACKETED_SEGMENTS_PRESET
1436
- },
1437
- {
1438
- id: "catppuccin-powerline",
1439
- label: "Catppuccin Powerline",
1440
- description: "Mocha connected color blocks \xB7 requires Nerd Font",
1441
- requiresNerdFont: true,
1442
- rawDocument: CATPPUCCIN_POWERLINE_PRESET
1443
- },
1444
- {
1445
- id: "gruvbox-rainbow",
1446
- label: "Gruvbox Rainbow",
1447
- description: "Warm Gruvbox connected segments \xB7 requires Nerd Font",
1448
- requiresNerdFont: true,
1449
- rawDocument: GRUVBOX_RAINBOW_PRESET
1450
- },
1451
- {
1452
- id: "jetpack",
1453
- label: "Jetpack",
1454
- description: "Airy geometric left/right layout \xB7 font-safe",
1455
- requiresNerdFont: false,
1456
- rawDocument: JETPACK_PRESET
1457
- },
1458
- {
1459
- id: "nerd-font-symbols",
1460
- label: "Nerd Font Symbols",
1461
- description: "Balanced default layout with icon-rich symbols \xB7 requires Nerd Font",
1462
- requiresNerdFont: true,
1463
- rawDocument: NERD_FONT_SYMBOLS_PRESET
1464
- },
1465
- {
1466
- id: "no-empty-icons",
1467
- label: "No Empty Icons",
1468
- description: "Conditional labels never appear without values \xB7 font-safe",
1469
- requiresNerdFont: false,
1470
- rawDocument: NO_EMPTY_ICONS_PRESET
1471
- },
1472
- {
1473
- id: "no-nerd-font",
1474
- label: "No Nerd Font",
1475
- description: "Portable Unicode symbols without private-use glyphs \xB7 font-safe",
1476
- requiresNerdFont: false,
1477
- rawDocument: NO_NERD_FONT_PRESET
1478
- },
1479
- {
1480
- id: "no-runtime-versions",
1481
- label: "No Runtime Versions",
1482
- description: "Presence indicators without model or thinking details \xB7 font-safe",
1483
- requiresNerdFont: false,
1484
- rawDocument: NO_RUNTIME_VERSIONS_PRESET
1485
- },
1486
- {
1487
- id: "pastel-powerline",
1488
- label: "Pastel Powerline",
1489
- description: "Pastel connected color blocks \xB7 requires Nerd Font",
1490
- requiresNerdFont: true,
1491
- rawDocument: PASTEL_POWERLINE_PRESET
1492
- },
1493
- {
1494
- id: "plain-text-symbols",
1495
- label: "Plain Text Symbols",
1496
- description: "Plain words replace pictograms \xB7 font-safe",
1497
- requiresNerdFont: false,
1498
- rawDocument: PLAIN_TEXT_SYMBOLS_PRESET
1499
- },
1500
- {
1501
- id: "pure-preset",
1502
- label: "Pure Preset",
1503
- description: "Clean two-line workspace and session context \xB7 font-safe",
1504
- requiresNerdFont: false,
1505
- rawDocument: PURE_PRESET
1506
- },
1507
- {
1508
- id: "tokyo-night",
1509
- label: "Tokyo Night",
1510
- description: "Cool connected color blocks \xB7 requires Nerd Font",
1511
- requiresNerdFont: true,
1512
- rawDocument: TOKYO_NIGHT_PRESET
1513
- }
1514
- ];
1515
- function getStarshipPreset(id) {
1516
- const preset = STARSHIP_PRESETS.find((candidate) => candidate.id === id);
1517
- if (!preset) throw new Error(`Unknown pi-starship preset: ${id}`);
1518
- return preset;
1519
- }
1520
- function presetForDocument(rawDocument) {
1521
- return STARSHIP_PRESETS.find((preset) => preset.rawDocument === rawDocument);
1522
- }
1523
-
1524
- // src/command-configuration.ts
1525
- var RELOAD_ACTIONS = {
1526
- apply: "apply",
1527
- cancel: "cancel"
1528
- };
1529
- function configurationPresentation(loaded) {
1530
- const healthyMissing = isHealthyMissing(loaded);
1531
- const savedBuiltIn = loaded.source === "user" && loaded.rawDocument === BUILT_IN_EXAMPLE;
1532
- const activePreset = presetForDocument(loaded.rawDocument);
1533
- const fallback = loaded.source === "built-in" && loaded.diagnostics.length > 0;
1534
- return {
1535
- state: healthyMissing ? "Built-in defaults" : savedBuiltIn ? "Saved built-in configuration" : activePreset ? `${activePreset.label} preset` : fallback ? "Built-in fallback" : "Custom configuration",
1536
- source: healthyMissing ? "No settings file" : activePreset ? "Bundled preset" : loaded.source === "user" ? "User file" : "Built-in fallback",
1537
- health: configurationHealth(loaded),
1538
- restoreDisabled: healthyMissing || savedBuiltIn,
1539
- restoreDescription: healthyMissing ? "Already using defaults \xB7 no file to replace" : savedBuiltIn ? "Built-in configuration already saved" : fallback ? "Preview before replacing invalid settings" : "Preview before replacing the document"
1540
- };
1541
- }
1542
- function configurationMenuScreen(loaded) {
1543
- const presentation = configurationPresentation(loaded);
1544
- return {
1545
- kind: "actions",
1546
- title: "Configuration",
1547
- lines: [`${presentation.state} \xB7 ${presentation.health}`],
1548
- items: [
1549
- {
1550
- id: "configuration-overview",
1551
- label: "Overview",
1552
- description: "State, source, path, health, and warnings",
1553
- to: "configuration-overview"
1554
- },
1555
- {
1556
- id: "configuration-effective",
1557
- label: "Effective configuration",
1558
- description: "Normalized public TOML currently in use",
1559
- to: "configuration-effective"
1560
- },
1561
- {
1562
- id: "configuration-document",
1563
- label: "Settings document",
1564
- description: isHealthyMissing(loaded) ? "No settings file \xB7 built-in defaults are active" : "Exact loaded UTF-8 text \xB7 read-only",
1565
- to: "configuration-document"
1566
- },
1567
- {
1568
- id: "configuration-reload",
1569
- label: "Reload from disk\u2026",
1570
- description: "Validate and preview external changes",
1571
- action: "configuration-reload"
1572
- },
1573
- {
1574
- id: "gist-share",
1575
- label: "Share settings as Gist\u2026",
1576
- description: "Upload reviewed TOML to GitHub \xB7 unlisted, not private \xB7 requires gh",
1577
- action: "gist-share"
1578
- },
1579
- {
1580
- id: "gist-import",
1581
- label: "Import settings from Gist\u2026",
1582
- description: "Review and preview remote TOML before replacing settings \xB7 requires gh",
1583
- action: "gist-import"
1584
- },
1585
- {
1586
- id: "history",
1587
- label: "History",
1588
- description: "Review and restore recovery copies; legacy skill backups are read-only",
1589
- action: "history"
1590
- }
1591
- ],
1592
- hint: "back"
1593
- };
1594
- }
1595
- function configurationOverviewScreen(loaded, settingsPath) {
1596
- const presentation = configurationPresentation(loaded);
1597
- return {
1598
- kind: "detail",
1599
- title: "Configuration overview",
1600
- lines: [
1601
- `State: ${presentation.state}`,
1602
- `Source: ${presentation.source}`,
1603
- `Path: ${sanitizeTerminalText(settingsPath)}`,
1604
- ...diagnosticLines(loaded, true)
1605
- ],
1606
- hint: "back"
1607
- };
1608
- }
1609
- function effectiveConfigurationScreen(loaded) {
1610
- const presentation = configurationPresentation(loaded);
1611
- return {
1612
- kind: "review",
1613
- title: "Effective configuration",
1614
- lines: [
1615
- `${presentation.state} \xB7 ${presentation.health}`,
1616
- "Normalized public TOML; comments and unknown fields are intentionally excluded."
1617
- ],
1618
- content: serializeEffectiveConfig(loaded.config),
1619
- enableSearch: true,
1620
- format: { kind: "code", language: "toml" },
1621
- viewportSize: "adaptive",
1622
- hint: "back"
1623
- };
1624
- }
1625
- function settingsDocumentScreen(loaded, settingsPath) {
1626
- const path = sanitizeTerminalText(settingsPath);
1627
- if (loaded.rawDocument !== void 0) {
1628
- return {
1629
- kind: "review",
1630
- title: "Settings document",
1631
- lines: ["Exact loaded UTF-8 text \xB7 display controls sanitized \xB7 read-only", `Path: ${path}`],
1632
- content: loaded.rawDocument,
1633
- enableSearch: true,
1634
- format: { kind: "code", language: "toml" },
1635
- viewportSize: "adaptive",
1636
- hint: "back"
1637
- };
1638
- }
1639
- return {
1640
- kind: "detail",
1641
- title: "Settings document",
1642
- lines: [
1643
- ...isHealthyMissing(loaded) ? ["No settings document exists.", "Built-in defaults are active; this read created no file."] : ["The settings document could not be loaded.", ...diagnosticLines(loaded, false)],
1644
- `Path: ${path}`
1645
- ],
1646
- hint: "back"
1647
- };
1648
- }
1649
- async function reloadConfiguration(ctx, options, owner) {
1650
- if (!isCurrentOwner(owner)) return "stay";
1651
- const previous = options.getLoaded();
1652
- const revision = options.getLoadedRevision?.();
1653
- const candidate = readReloadCandidate(options);
1654
- let disk;
1655
- try {
1656
- disk = readConfigDocumentSnapshot(options.settingsPath);
1657
- } catch (error) {
1658
- ctx.ui.notify(`Footer reload was blocked: ${safeError(error)}`, "error");
1659
- return "stay";
1660
- }
1661
- if (!candidate.ok) {
1662
- ctx.ui.notify(`Footer reload was blocked: ${safeError(candidate.error)}`, "error");
1663
- return "stay";
1664
- }
1665
- if (sameLoadedDocument(previous, candidate.loaded)) {
1666
- ctx.ui.notify("The current disk configuration is already loaded.", "info");
1667
- return "stay";
1668
- }
1669
- const selection = await showPreviewActionMenu(
1670
- ctx,
1671
- "Reload preview",
1672
- (width) => reloadPreviewBody(ctx, options, candidate.loaded, width),
1673
- [
1674
- { value: RELOAD_ACTIONS.apply, label: "Apply reloaded configuration\u2026" },
1675
- { value: RELOAD_ACTIONS.cancel, label: "Cancel" }
1676
- ],
1677
- owner.signal,
1678
- owner.isCurrent
1679
- );
1680
- if (!isCurrentOwner(owner) || activeRevisionChanged(options, revision)) return "stay";
1681
- if (selection?.kind === "closed") return "close";
1682
- if (selectedReloadAction(selection) !== RELOAD_ACTIONS.apply) return "stay";
1683
- const confirmed = await ctx.ui.confirm(
1684
- "Apply configuration from disk?",
1685
- candidate.loaded.rawDocument === void 0 ? "Use built-in defaults for this session? No settings file will be created." : "Apply the validated settings document to this session without changing its bytes? The previous loaded document will be kept in History.",
1686
- { signal: owner.signal }
1687
- );
1688
- if (!isCurrentOwner(owner) || activeRevisionChanged(options, revision) || !confirmed) {
1689
- return "stay";
1690
- }
1691
- let warnings = 0;
1692
- try {
1693
- const applied = await withFileMutationQueue2(options.settingsPath, async () => {
1694
- if (!isCurrentOwner(owner) || activeRevisionChanged(options, revision) || !sameLoadedDocument(previous, options.getLoaded()))
1695
- return false;
1696
- assertConfigDocumentUnchanged(options.settingsPath, disk);
1697
- const fresh = readReloadCandidate(options);
1698
- if (!fresh.ok) throw new Error(fresh.error);
1699
- if (!sameLoadedDocument(candidate.loaded, fresh.loaded)) {
1700
- throw new Error(
1701
- "The settings document changed after preview. The previous footer remains active; reload again to review the latest version."
1702
- );
1703
- }
1704
- let recoveryPath;
1705
- const previousBytes = previous.rawBytes ?? previous.rawDocument;
1706
- if (previousBytes !== void 0) {
1707
- recoveryPath = (options.archive ?? archiveConfigDocument)(options.settingsPath, previousBytes).path;
1708
- }
1709
- assertConfigDocumentUnchanged(options.settingsPath, disk);
1710
- if (!isCurrentOwner(owner) || activeRevisionChanged(options, revision)) return false;
1711
- try {
1712
- options.apply(fresh.loaded, ctx);
1713
- } catch (error) {
1714
- let rollbackError;
1715
- try {
1716
- if (!isCurrentOwner(owner)) throw new Error("The session owner changed; stale restoration was blocked");
1717
- const current3 = options.getLoaded();
1718
- if (!sameLoadedDocument(current3, previous) && !sameLoadedDocument(current3, fresh.loaded))
1719
- throw new Error("The active runtime changed; stale restoration was blocked");
1720
- options.apply(previous, ctx);
1721
- } catch (rollback) {
1722
- rollbackError = rollback;
1723
- }
1724
- throw new Error(
1725
- `Footer reload failed: ${formatError(error)}. ${rollbackError ? `Restoring the previous configuration also failed: ${formatError(rollbackError)}.` : "The previous configuration was restored."}${recoveryPath ? ` Recovery copy retained: ${recoveryPath}.` : ""}`
1726
- );
1727
- }
1728
- warnings = fresh.loaded.diagnostics.length;
1729
- return true;
1730
- });
1731
- if (!isCurrentOwner(owner) || !applied) return "stay";
1732
- } catch (error) {
1733
- if (isCurrentOwner(owner))
1734
- ctx.ui.notify(`Footer reload was blocked after confirmation: ${safeError(error)}`, "error");
1735
- return "stay";
1736
- }
1737
- ctx.ui.notify(
1738
- warnings === 0 ? "Footer configuration reloaded and applied." : `Footer configuration reloaded and applied with ${warnings} warning${warnings === 1 ? "" : "s"}.`,
1739
- "info"
1740
- );
1741
- return "applied";
1742
- }
1743
- function readReloadCandidate(options) {
1744
- let loaded;
1745
- try {
1746
- loaded = (options.read ?? loadStarshipConfig)(options.settingsPath);
1747
- } catch (error) {
1748
- return { ok: false, error: formatError(error) };
1749
- }
1750
- const errors = loaded.diagnostics.filter((item) => item.severity === "error");
1751
- if (errors.length > 0) {
1752
- return { ok: false, error: errors.map((item) => item.message).join("; ") };
1753
- }
1754
- return { ok: true, loaded };
1755
- }
1756
- function reloadPreviewBody(ctx, options, loaded, width) {
1757
- const presentation = configurationPresentation(loaded);
1758
- let preview;
1759
- try {
1760
- preview = options.renderPreview?.(loaded, width, ctx) ?? ["Live preview is unavailable until the footer is ready."];
1761
- } catch (error) {
1762
- preview = [`Preview unavailable: ${safeError(formatError(error))}`];
1763
- }
1764
- return [
1765
- `Candidate: ${presentation.state}`,
1766
- `Source: ${presentation.source}`,
1767
- `Path: ${sanitizeTerminalText(options.settingsPath)}`,
1768
- loaded.rawDocument === void 0 ? "Applying uses built-in defaults and creates no settings file." : "Applying changes only the active session; the settings document bytes stay unchanged.",
1769
- ...diagnosticLines(loaded, true),
1770
- "",
1771
- ...preview
1772
- ];
1773
- }
1774
- function diagnosticLines(loaded, includeSummary) {
1775
- const diagnostics = loaded.diagnostics.slice(0, 8).map((item) => `${sanitizeTerminalText(item.path || "root")}: ${sanitizeTerminalText(item.message)}`);
1776
- const remaining = loaded.diagnostics.length - diagnostics.length;
1777
- return [
1778
- ...includeSummary ? [`Health: ${configurationHealth(loaded)}`] : [],
1779
- ...diagnostics.length > 0 ? diagnostics : ["No configuration warnings."],
1780
- ...remaining > 0 ? [`${remaining} additional warnings not shown.`] : []
1781
- ];
1782
- }
1783
- function configurationHealth(loaded) {
1784
- const errors = loaded.diagnostics.filter((item) => item.severity === "error").length;
1785
- if (errors > 0) return `${errors} error${errors === 1 ? "" : "s"}`;
1786
- const warnings = loaded.diagnostics.length;
1787
- return warnings === 0 ? "Healthy" : `${warnings} warning${warnings === 1 ? "" : "s"}`;
1788
- }
1789
- function isHealthyMissing(loaded) {
1790
- return loaded.source === "built-in" && loaded.rawDocument === void 0 && loaded.diagnostics.length === 0;
1791
- }
1792
- function sameLoadedDocument(left, right) {
1793
- return left.source === right.source && left.rawDocument === right.rawDocument && JSON.stringify(left.diagnostics) === JSON.stringify(right.diagnostics);
1794
- }
1795
- function activeRevisionChanged(options, revision) {
1796
- return revision !== void 0 && options.getLoadedRevision?.() !== revision;
1797
- }
1798
- function isCurrentOwner(owner) {
1799
- return !owner.signal.aborted && owner.isCurrent();
1800
- }
1801
- function selectedReloadAction(result) {
1802
- return result?.kind === "selected" ? result.value : null;
1803
- }
1804
- function safeError(value) {
1805
- return sanitizeTerminalText(typeof value === "string" ? value : formatError(value));
1806
- }
1807
- function formatError(error) {
1808
- return error instanceof Error ? error.message : String(error);
1809
- }
1810
-
1811
- // src/command-gist.ts
1812
- import { defineMenu, runMenu, runTask } from "@narumitw/pi-tui-kit";
1813
- import { sanitizeTerminalText as sanitizeTerminalText2 } from "@narumitw/pi-tui-kit/terminal-text";
1814
-
1815
- // src/gist.ts
1816
- import { spawn } from "node:child_process";
1817
- var GIST_FILENAME = "pi-starship.toml";
1818
- var MAX_GIST_DOCUMENT_BYTES = 64 * 1024;
1819
- var MAX_RESPONSE_BYTES = 512 * 1024;
1820
- var REQUEST_TIMEOUT_MS = 3e4;
1821
- function gistId(value) {
1822
- const text = value.trim();
1823
- if (/^[a-f\d]{5,64}$/iu.test(text)) return text;
1824
- try {
1825
- const url = new URL(text);
1826
- const match = /^\/(?:[\w-]+\/)?([a-f\d]{5,64})\/?$/iu.exec(url.pathname);
1827
- if (url.protocol === "https:" && url.hostname === "gist.github.com" && !url.port && !url.username && !url.password && !url.search && match?.[1])
1828
- return match[1];
1829
- } catch {
1830
- }
1831
- throw new Error("Enter a github.com Gist ID or https://gist.github.com/<owner>/<id> URL.");
1832
- }
1833
- function checkGistDocument(rawDocument) {
1834
- if (!rawDocument.trim()) throw new Error("The Gist settings document is empty.");
1835
- if (Buffer.byteLength(rawDocument, "utf8") > MAX_GIST_DOCUMENT_BYTES) {
1836
- throw new Error("The Gist settings document exceeds 64 KiB.");
1837
- }
1838
- }
1839
- async function createSettingsGist(rawDocument, signal, api = executeGhApi) {
1840
- checkGistDocument(rawDocument);
1841
- const response = JSON.parse(
1842
- await api(
1843
- ["/gists", "--method", "POST", "--input", "-"],
1844
- JSON.stringify({
1845
- description: "pi-starship footer settings",
1846
- public: false,
1847
- files: { [GIST_FILENAME]: { content: rawDocument } }
1848
- }),
1849
- signal
1850
- )
1851
- );
1852
- signal.throwIfAborted();
1853
- if (!isRecord(response) || response.public !== false || typeof response.html_url !== "string") {
1854
- throw new Error("GitHub returned an invalid Gist response. Check your Gists before retrying.");
1855
- }
1856
- return `https://gist.github.com/${gistId(response.html_url)}`;
1857
- }
1858
- async function fetchSettingsGist(value, signal, api = executeGhApi) {
1859
- const id = gistId(value);
1860
- const response = JSON.parse(await api([`/gists/${id}`, "--method", "GET"], void 0, signal));
1861
- signal.throwIfAborted();
1862
- const file = isRecord(response) && isRecord(response.files) ? response.files[GIST_FILENAME] : void 0;
1863
- if (!isRecord(file) || typeof file.content !== "string" || file.truncated !== false) {
1864
- throw new Error(`The Gist must contain a complete ${GIST_FILENAME} file. Truncated files are not supported.`);
1865
- }
1866
- checkGistDocument(file.content);
1867
- return file.content;
1868
- }
1869
- function isRecord(value) {
1870
- return value !== null && typeof value === "object" && !Array.isArray(value);
1871
- }
1872
- var executeGhApi = (args, input, signal) => {
1873
- signal.throwIfAborted();
1874
- return new Promise((resolve2, reject) => {
1875
- const child = spawn(process.platform === "win32" ? "gh.exe" : "gh", ["api", "--hostname", "github.com", ...args], {
1876
- env: { ...process.env, GH_PROMPT_DISABLED: "1", GH_PAGER: "", GH_DEBUG: "" },
1877
- stdio: ["pipe", "pipe", "ignore"],
1878
- windowsHide: true
1879
- });
1880
- const chunks = [];
1881
- let bytes = 0;
1882
- let failure;
1883
- const stop = (error) => {
1884
- failure ??= error;
1885
- child.kill("SIGKILL");
1886
- };
1887
- const onAbort = () => stop(new Error("Gist request cancelled."));
1888
- const timer = setTimeout(
1889
- () => stop(new Error("Gist request timed out. Check GitHub before retrying an upload.")),
1890
- REQUEST_TIMEOUT_MS
1891
- );
1892
- timer.unref();
1893
- signal.addEventListener("abort", onAbort, { once: true });
1894
- child.stdout.on("data", (chunk) => {
1895
- bytes += chunk.length;
1896
- if (bytes > MAX_RESPONSE_BYTES) stop(new Error("GitHub Gist response exceeds 512 KiB."));
1897
- else chunks.push(chunk);
1898
- });
1899
- child.stdin.on("error", () => {
1900
- stop(new Error("Unable to send settings to gh."));
1901
- });
1902
- child.on("error", () => {
1903
- failure ??= new Error("Unable to start gh. Install GitHub CLI and run gh auth login with Gist access.");
1904
- });
1905
- child.on("close", (code) => {
1906
- clearTimeout(timer);
1907
- signal.removeEventListener("abort", onAbort);
1908
- if (failure) reject(failure);
1909
- else if (code !== 0)
1910
- reject(
1911
- new Error(
1912
- "Gist request failed. Check gh auth status, Gist access, and connectivity. An upload may already exist."
1913
- )
1914
- );
1915
- else resolve2(Buffer.concat(chunks).toString("utf8"));
1916
- });
1917
- if (signal.aborted) onAbort();
1918
- child.stdin.end(input);
1919
- });
1920
- };
1921
-
1922
- // src/command-gist.ts
1923
- async function shareSettingsGist(ctx, options, owner, api) {
1924
- if (ctx.mode !== "tui" || !current(owner)) return "cancel";
1925
- const loaded = options.getLoaded();
1926
- if (loaded.diagnostics.some((item) => item.severity === "error")) {
1927
- ctx.ui.notify("Fix configuration errors before sharing settings.", "warning");
1928
- return "cancel";
1929
- }
1930
- const raw = loaded.rawDocument ?? BUILT_IN_EXAMPLE;
1931
- try {
1932
- checkGistDocument(raw);
1933
- } catch (error) {
1934
- ctx.ui.notify(safeError2(error), "error");
1935
- return "cancel";
1936
- }
1937
- const review = await reviewDocument(
1938
- ctx,
1939
- owner,
1940
- "Share settings as Gist",
1941
- raw,
1942
- [
1943
- "Review the entire loaded document, including comments and unknown fields, for secrets and local paths.",
1944
- "No settings file is created when sharing built-in defaults."
1945
- ],
1946
- "Share unlisted Gist\u2026"
1947
- );
1948
- if (!current(owner)) return "cancel";
1949
- if (!review) return "close";
1950
- const confirmed = await ctx.ui.confirm(
1951
- "Upload settings to GitHub?",
1952
- [
1953
- "Send the reviewed pi-starship.toml to github.com as a new unlisted Gist?",
1954
- "Unlisted is not private: anyone with the link can read it. Comments and unknown fields are included.",
1955
- "Cancellation or a network error cannot undo an upload already accepted by GitHub; check your Gists before retrying."
1956
- ].join("\n"),
1957
- { signal: owner.signal }
1958
- );
1959
- if (!current(owner) || !confirmed) return "cancel";
1960
- const result = await runTask(ctx, {
1961
- label: "Sharing settings with GitHub\u2026",
1962
- signal: owner.signal,
1963
- isCurrent: owner.isCurrent,
1964
- task: ({ signal }) => createSettingsGist(raw, signal, api),
1965
- onError: () => ctx.ui.notify(
1966
- "Gist upload failed. Check gh auth status, Gist access, connectivity, and your Gists before retrying. The upload may already exist.",
1967
- "error"
1968
- )
1969
- });
1970
- if (!current(owner)) return "cancel";
1971
- if (result.kind === "completed") {
1972
- ctx.ui.notify(`Settings Gist: ${result.value}`, "info");
1973
- return "cancel";
1974
- }
1975
- return result.kind === "error" ? "cancel" : "close";
1976
- }
1977
- async function importSettingsGist(ctx, options, owner, reviewImport, api) {
1978
- if (ctx.mode !== "tui" || !current(owner)) return "cancel";
1979
- const previous = options.getLoaded();
1980
- const revision = options.getLoadedRevision?.();
1981
- const disk = diskSnapshot(options);
1982
- const initialDisk = readConfigDocumentSnapshot(options.settingsPath);
1983
- const guardedOwner = {
1984
- signal: owner.signal,
1985
- isSessionCurrent: () => owner.isSessionCurrent?.() ?? owner.isCurrent(),
1986
- isCurrent: () => current(owner) && options.getLoadedRevision?.() === revision && options.getLoaded().rawDocument === previous.rawDocument && options.getLoaded().source === previous.source
1987
- };
1988
- const value = await ctx.ui.input("Import pi-starship settings from Gist", "https://gist.github.com/<owner>/<id>", {
1989
- signal: owner.signal
1990
- });
1991
- if (!current(guardedOwner) || value === void 0) return "cancel";
1992
- let id;
1993
- try {
1994
- id = gistId(value);
1995
- } catch (error) {
1996
- ctx.ui.notify(safeError2(error), "error");
1997
- return "cancel";
1998
- }
1999
- const result = await runTask(ctx, {
2000
- label: "Reading settings from GitHub\u2026",
2001
- signal: owner.signal,
2002
- isCurrent: guardedOwner.isCurrent,
2003
- task: ({ signal }) => fetchSettingsGist(id, signal, api),
2004
- onError: () => ctx.ui.notify(
2005
- "Gist import failed. Check the Gist ID, gh auth status, connectivity, and a complete pi-starship.toml file (up to 64 KiB).",
2006
- "error"
2007
- )
2008
- });
2009
- if (!current(guardedOwner)) return "cancel";
2010
- if (result.kind !== "completed") return result.kind === "error" ? "cancel" : "close";
2011
- let validated;
2012
- try {
2013
- validated = (options.validate ?? validateConfigDocument)(options.settingsPath, result.value);
2014
- } catch (error) {
2015
- ctx.ui.notify(`Gist settings are invalid: ${safeError2(error)}`, "error");
2016
- return "cancel";
2017
- }
2018
- const reviewed = await reviewDocument(
2019
- ctx,
2020
- guardedOwner,
2021
- "Review Gist settings",
2022
- result.value,
2023
- [
2024
- `Source: https://gist.github.com/${id}`,
2025
- "Untrusted settings can enable local commands and network requests. Review the complete TOML before applying.",
2026
- "Import replaces the entire local document, including comments and unknown fields; its previous bytes will be kept in History."
2027
- ],
2028
- "Preview imported footer\u2026"
2029
- );
2030
- if (!current(guardedOwner)) return "cancel";
2031
- if (!reviewed) return "close";
2032
- return reviewImport(
2033
- validated,
2034
- {
2035
- ...options,
2036
- save(path, raw) {
2037
- if (!current(guardedOwner) || diskSnapshot(options) !== disk) {
2038
- throw new Error("Settings changed during import. Start a new import to review the latest state.");
2039
- }
2040
- return options.save ? options.save(path, raw) : atomicSaveConfigDocument(path, raw, {}, initialDisk);
2041
- }
2042
- },
2043
- guardedOwner
2044
- );
2045
- }
2046
- async function reviewDocument(ctx, owner, title, content, lines, label) {
2047
- let approved = false;
2048
- const menu = defineMenu({
2049
- start: "document",
2050
- screens: {
2051
- document: () => ({
2052
- kind: "review",
2053
- title,
2054
- lines,
2055
- content,
2056
- format: { kind: "code", language: "toml" },
2057
- viewportSize: "adaptive",
2058
- enableSearch: true,
2059
- confirm: { id: "continue", label, action: "continue" },
2060
- hint: "close"
2061
- })
2062
- },
2063
- actions: {
2064
- continue: () => {
2065
- approved = true;
2066
- return { kind: "close" };
2067
- }
2068
- }
2069
- });
2070
- await runMenu(ctx, menu, { getState: () => void 0, signal: owner.signal, isCurrent: owner.isCurrent });
2071
- return current(owner) && approved;
2072
- }
2073
- function diskSnapshot(options) {
2074
- const loaded = (options.read ?? loadStarshipConfig)(options.settingsPath);
2075
- return JSON.stringify([
2076
- loaded.rawDocument,
2077
- loaded.source,
2078
- loaded.diagnostics,
2079
- readConfigDocumentSnapshot(options.settingsPath)
2080
- ]);
2081
- }
2082
- function current(owner) {
2083
- return !owner.signal.aborted && owner.isCurrent();
2084
- }
2085
- function safeError2(error) {
2086
- return sanitizeTerminalText2(error instanceof Error ? error.message : String(error));
2087
- }
2088
-
2089
- // src/command-inspector.ts
2090
- import { stripVTControlCharacters as stripVTControlCharacters2 } from "node:util";
2091
- function formatFooterExplanation(inspection) {
2092
- if (!inspection) {
2093
- return safeLines([
2094
- "Footer inspection is unavailable until the TUI footer is ready.",
2095
- "No collection work was started."
2096
- ]);
2097
- }
2098
- if (inspection.showing.length === 0) {
2099
- return safeLines([
2100
- "No modules are currently showing.",
2101
- "Open Modules to inspect empty, disabled, or unreachable modules."
2102
- ]);
2103
- }
2104
- return safeLines(
2105
- inspection.showing.flatMap((module, index) => [
2106
- ...index > 0 ? [""] : [],
2107
- module.name,
2108
- ...previewLines(module.preview),
2109
- module.description
2110
- ])
2111
- );
2112
- }
2113
- function previewLines(preview) {
2114
- const lines = preview ? preview.split("\n") : ["(no text)"];
2115
- return lines.map((line, index) => `${index === 0 ? "Value: " : " "}${line}`);
2116
- }
2117
- function safeLines(lines) {
2118
- return lines.map(safeDisplayText2).join("\n");
2119
- }
2120
- function safeDisplayText2(value) {
2121
- return Array.from(stripVTControlCharacters2(value), (character) => {
2122
- const codePoint = character.codePointAt(0) ?? 0;
2123
- return codePoint <= 31 || codePoint >= 127 && codePoint <= 159 ? "" : character;
2124
- }).join("");
2125
- }
2126
-
2127
- // src/command-preset-picker.ts
2128
- import { runLiveChoice } from "@narumitw/pi-tui-kit";
2129
- async function showPresetPicker(ctx, options) {
2130
- const current3 = options.presets.find((preset) => preset.id === options.activePresetId)?.label ?? "Custom configuration";
2131
- const result = await runLiveChoice(ctx, {
2132
- title: `Presets \xB7 current: ${current3}`,
2133
- items: options.presets.map((preset) => ({
2134
- id: preset.id,
2135
- label: preset.label,
2136
- description: preset.id === options.activePresetId ? `Currently applied \xB7 ${preset.description}` : preset.description,
2137
- details: [`Selected: ${preset.label} \xB7 ${preset.requiresNerdFont ? "requires Nerd Font" : "font-safe"}`],
2138
- confirmationDisabled: preset.id === options.activePresetId,
2139
- confirmationDisabledReason: "Already applied; press e to customize"
2140
- })),
2141
- currentItemId: options.activePresetId,
2142
- initialItemId: options.initialPresetId ?? options.activePresetId,
2143
- viewportSize: Math.min(options.presets.length, 10),
2144
- hint: "back",
2145
- navigationLabel: "live preview",
2146
- confirmLabel: "apply",
2147
- shortcuts: [
2148
- { id: "customize", keys: ["e", "shift+e"], label: "customize" },
2149
- { id: "save-profile", keys: ["s", "shift+s"], label: "save as profile" }
2150
- ],
2151
- onSelectionChange: ({ item }) => {
2152
- const preset = options.presets.find((candidate) => candidate.id === item.id);
2153
- if (preset) options.preview(preset);
2154
- },
2155
- signal: options.signal,
2156
- isCurrent: options.isCurrent
2157
- });
2158
- if (result.kind === "selected") return { kind: "apply", presetId: result.itemId };
2159
- if (result.kind === "shortcut") {
2160
- return { kind: result.shortcutId === "save-profile" ? "save-profile" : "customize", presetId: result.itemId };
2161
- }
2162
- if (result.kind === "closed" && result.reason === "back") return { kind: "back" };
2163
- return { kind: "close" };
2164
- }
2165
-
2166
- // src/command-profiles.ts
2167
- import { isKeyRelease, Key as Key2, matchesKey as matchesKey2 } from "@earendil-works/pi-tui";
2168
- import { defineMenu as defineMenu2, runLiveChoice as runLiveChoice2, runMenu as runMenu2 } from "@narumitw/pi-tui-kit";
2169
- import { sanitizeTerminalText as sanitizeTerminalText3 } from "@narumitw/pi-tui-kit/terminal-text";
2170
- var PREVIEW_NOTICE = "Preview uses the current runtime snapshot only; unavailable module data can be empty.";
2171
- var SAVE_CURRENT = "save-current";
2172
- var FlowEnded = class extends Error {
2173
- };
2174
- async function showProfiles(ctx, options, owner, applyCandidate) {
2175
- return browseDocuments(ctx, options, owner, applyCandidate, "profile");
2176
- }
2177
- async function showHistory(ctx, options, owner, applyCandidate) {
2178
- return browseDocuments(ctx, options, owner, applyCandidate, "history");
2179
- }
2180
- async function saveAsProfile(ctx, options, owner, raw) {
2181
- if (!interactive(ctx) || !current2(owner)) return void 0;
2182
- const flow = createFlow(ctx, options, owner);
2183
- try {
2184
- candidateFor(options, raw, true);
2185
- const saved = await saveNamedCopy(ctx, options, flow, raw);
2186
- flow.ensure();
2187
- return saved;
2188
- } catch (error) {
2189
- if (flow.signal.aborted || !flow.sessionCurrent()) return "close";
2190
- report(ctx, flow, error);
2191
- return void 0;
2192
- } finally {
2193
- flow.dispose();
2194
- }
2195
- }
2196
- async function browseDocuments(ctx, options, owner, applyCandidate, kind) {
2197
- if (!interactive(ctx) || !current2(owner)) return "close";
2198
- const flow = createFlow(ctx, options, owner);
2199
- let selectedId;
2200
- try {
2201
- while (flow.current()) {
2202
- let interacted = false;
2203
- try {
2204
- const documents = kind === "profile" ? listProfiles(options.settingsPath) : listHistory(options.settingsPath);
2205
- const active = options.getLoaded();
2206
- const matches = documents.filter(
2207
- (document2) => document2.rawDocument !== void 0 && document2.rawDocument === active.rawDocument
2208
- );
2209
- const candidates = new Map(
2210
- documents.map((document2) => [documentId(document2), candidateFor(options, document2.rawDocument)])
2211
- );
2212
- const selection = await runLiveChoice2(ctx, {
2213
- title: kind === "profile" ? "Profiles" : "History",
2214
- lines: [
2215
- active.rawDocument === void 0 && active.diagnostics.length === 0 ? "Active: Built-in defaults" : active.diagnostics.some((item) => item.severity === "error") ? "Active: Invalid settings document \xB7 replacement requires explicit recovery" : "Active: Independent settings document",
2216
- ...kind === "profile" && matches.length === 0 ? ["Current settings are not saved as a profile"] : [],
2217
- PREVIEW_NOTICE
2218
- ],
2219
- items: [
2220
- ...kind === "profile" ? [
2221
- {
2222
- id: SAVE_CURRENT,
2223
- label: "Save current as\u2026",
2224
- description: "Copy exact loaded TOML; keep active settings unchanged"
2225
- }
2226
- ] : [],
2227
- ...documents.map((document2) => ({
2228
- id: documentId(document2),
2229
- label: safe(document2.name),
2230
- description: [
2231
- ...document2.kind === "history" ? [safe(document2.createdAt), ...document2.legacy ? ["Legacy \xB7 read-only"] : []] : [],
2232
- ...document2.rawDocument !== void 0 && document2.rawDocument === active.rawDocument ? ["Matches active settings"] : [],
2233
- ...!candidates.get(documentId(document2))?.loaded ? ["Invalid document \xB7 review or repair"] : []
2234
- ].join(" \xB7 "),
2235
- details: [
2236
- `Selected: ${safe(document2.name)}`,
2237
- `Path: ${safe(document2.path)}`,
2238
- ...candidates.get(documentId(document2))?.lines ?? []
2239
- ]
2240
- }))
2241
- ],
2242
- initialItemId: selectedId,
2243
- enableSearch: true,
2244
- viewportSize: 10,
2245
- hint: "back",
2246
- confirmLabel: "actions",
2247
- navigationLabel: "live preview",
2248
- signal: flow.signal,
2249
- isCurrent: flow.current,
2250
- onSelectionChange: ({ item, signal }) => {
2251
- if (signal.aborted || !flow.current()) return;
2252
- selectedId = item.id;
2253
- flow.preview(candidates.get(item.id)?.loaded);
2254
- }
2255
- });
2256
- flow.ensure();
2257
- interacted = true;
2258
- if (selection.kind !== "selected") {
2259
- return selection.kind === "closed" && selection.reason === "back" ? "back" : "close";
2260
- }
2261
- selectedId = selection.itemId;
2262
- if (selectedId === SAVE_CURRENT) {
2263
- flow.preview(void 0);
2264
- const loaded = options.getLoaded();
2265
- if (loaded.diagnostics.some((item) => item.severity === "error")) {
2266
- throw new Error(
2267
- "Cannot save unreadable or malformed active settings as a profile. Repair the settings document first."
2268
- );
2269
- }
2270
- const raw = loaded.rawDocument ?? BUILT_IN_EXAMPLE;
2271
- candidateFor(options, raw, true);
2272
- const saved = await saveNamedCopy(ctx, options, flow, raw);
2273
- flow.ensure();
2274
- if (saved) selectedId = documentId(saved);
2275
- continue;
2276
- }
2277
- const document = documents.find((item) => documentId(item) === selectedId);
2278
- if (!document) continue;
2279
- flow.ensure(document);
2280
- const outcome = await documentActions(ctx, options, flow, document, applyCandidate);
2281
- flow.ensure();
2282
- if (outcome === "close") return "close";
2283
- if (outcome) selectedId = documentId(outcome);
2284
- } catch (error) {
2285
- if (error instanceof FlowEnded || !flow.current()) return "close";
2286
- flow.preview(void 0);
2287
- report(ctx, flow, error);
2288
- if (!interacted) return "close";
2289
- }
2290
- }
2291
- return "close";
2292
- } finally {
2293
- flow.dispose();
2294
- }
2295
- }
2296
- async function documentActions(ctx, options, flow, document, applyCandidate) {
2297
- const candidate = candidateFor(options, document.rawDocument);
2298
- const profile = document.kind === "profile";
2299
- const activeInvalid = profile && options.getLoaded().diagnostics.some((item) => item.severity === "error");
2300
- const action = await actionScreen(ctx, flow, {
2301
- title: `${profile ? "Profile" : "Recovery copy"}: ${safe(document.name)}`,
2302
- lines: [
2303
- `Path: ${safe(document.path)}`,
2304
- ...document.kind === "history" ? [`Recovery time: ${safe(document.createdAt)}`, "A recovery copy is not proof that an application succeeded."] : [],
2305
- ...document.kind === "history" && document.legacy ? ["Legacy backup \xB7 read-only; restore copies bytes without changing this backup."] : [],
2306
- ...document.readError ? [safe(document.readError)] : [],
2307
- ...candidate.lines,
2308
- PREVIEW_NOTICE
2309
- ],
2310
- raw: document.rawDocument,
2311
- actions: [
2312
- {
2313
- id: "apply",
2314
- label: profile ? "Apply\u2026" : "Restore\u2026",
2315
- disabled: !candidate.loaded || activeInvalid,
2316
- disabledReason: activeInvalid ? "Repair active settings or use explicit recovery first" : "Invalid TOML cannot be applied"
2317
- },
2318
- ...profile ? [
2319
- { id: "edit", label: "Edit TOML\u2026" },
2320
- { id: "rename", label: "Rename\u2026" },
2321
- { id: "duplicate", label: "Duplicate\u2026" }
2322
- ] : [
2323
- {
2324
- id: "save-as",
2325
- label: "Save as a profile\u2026",
2326
- disabled: !candidate.loaded,
2327
- disabledReason: "Invalid TOML cannot be saved as a validated profile"
2328
- }
2329
- ],
2330
- {
2331
- id: "delete",
2332
- label: "Delete\u2026",
2333
- disabled: document.kind === "history" && document.legacy,
2334
- disabledReason: "Legacy backups are read-only"
2335
- }
2336
- ]
2337
- });
2338
- flow.ensure(document);
2339
- if (action === "close") return "close";
2340
- if (action === "back") return void 0;
2341
- if (action === "apply" && candidate.loaded) {
2342
- const result = await applyReviewedCandidate(flow, candidate.loaded, applyCandidate, document);
2343
- flow.ensure(document);
2344
- return result === "close" ? "close" : document;
2345
- }
2346
- if (action === "edit" && profile) {
2347
- const result = await editProfile(ctx, options, flow, document, applyCandidate);
2348
- flow.ensure();
2349
- return result;
2350
- }
2351
- if (action === "rename" && profile) {
2352
- const name = await flow.dialog(
2353
- () => ctx.ui.input(`Rename profile: ${safe(document.name)}`, "New profile name", { signal: flow.signal })
2354
- );
2355
- flow.ensure(document);
2356
- if (name === void 0) return document;
2357
- return renameProfile(options.settingsPath, document.name, name, document);
2358
- }
2359
- if (action === "duplicate" || action === "save-as" && document.rawDocument !== void 0) {
2360
- const saved = await saveNamedCopy(ctx, options, flow, document.rawDocument, document);
2361
- flow.ensure(document);
2362
- return action === "duplicate" || document.kind === "history" ? document : saved ?? document;
2363
- }
2364
- if (action === "delete" && !(document.kind === "history" && document.legacy)) {
2365
- const confirmed = await flow.dialog(
2366
- () => ctx.ui.confirm(
2367
- `Delete ${profile ? "profile" : "recovery copy"}: ${safe(document.name)}?`,
2368
- `Path: ${safe(document.path)}
2369
- ${profile ? "This deletes only the saved profile. The active settings copy remains unchanged." : "This permanently deletes only this recovery copy. Active settings remain unchanged."}`,
2370
- { signal: flow.signal }
2371
- )
2372
- );
2373
- flow.ensure(document);
2374
- if (confirmed) {
2375
- if (document.kind === "profile") deleteProfile(options.settingsPath, document.name, document);
2376
- else deleteHistory(options.settingsPath, document.name, document);
2377
- }
2378
- }
2379
- return void 0;
2380
- }
2381
- async function editProfile(ctx, options, flow, original, applyCandidate) {
2382
- let draft = original.rawDocument ?? "";
2383
- if (original.rawDocument === void 0) {
2384
- const repair = await flow.dialog(
2385
- () => ctx.ui.confirm(
2386
- `Repair invalid UTF-8 profile: ${safe(original.name)}?`,
2387
- `Path: ${safe(original.path)}
2388
- The original bytes cannot be edited as TOML text. Open an empty repair draft? Saving replaces these invalid bytes; the saved copy stays unchanged until you select Save profile. Duplicate it first to keep the original bytes.`,
2389
- { signal: flow.signal }
2390
- )
2391
- );
2392
- flow.ensure(original);
2393
- if (!repair) return original;
2394
- }
2395
- while (flow.current()) {
2396
- const edited = await flow.dialog(() => ctx.ui.editor(`Edit profile: ${safe(original.name)}`, draft));
2397
- flow.ensure(original);
2398
- if (edited === void 0) return original;
2399
- draft = edited;
2400
- const candidate = candidateFor(options, draft);
2401
- flow.preview(candidate.loaded);
2402
- const action = await actionScreen(ctx, flow, {
2403
- title: candidate.loaded ? "Profile draft preview" : "Profile draft needs attention",
2404
- lines: [
2405
- "Save profile changes only the saved copy, even when it matches active settings.",
2406
- ...candidate.lines,
2407
- PREVIEW_NOTICE
2408
- ],
2409
- raw: draft,
2410
- actions: [
2411
- {
2412
- id: "save",
2413
- label: "Save profile",
2414
- disabled: !candidate.loaded,
2415
- disabledReason: "Repair the draft before saving"
2416
- },
2417
- {
2418
- id: "save-apply",
2419
- label: "Save profile and apply\u2026",
2420
- description: "Two operations: a failed apply retains the saved profile",
2421
- disabled: !candidate.loaded,
2422
- disabledReason: "Repair the draft before saving"
2423
- },
2424
- { id: "continue", label: "Continue editing" },
2425
- { id: "discard", label: "Discard draft" }
2426
- ]
2427
- });
2428
- flow.ensure(original);
2429
- if (action === "close") return "close";
2430
- if (action === "discard") return original;
2431
- if (action === "continue" || action === "back") continue;
2432
- if (!candidate.loaded || action !== "save" && action !== "save-apply") continue;
2433
- const saved = saveProfile(options.settingsPath, original.name, draft, original);
2434
- ctx.ui.notify(`Profile saved: ${safe(saved.name)}. Active settings are unchanged.`, "info");
2435
- if (action === "save-apply") {
2436
- try {
2437
- const result = await applyReviewedCandidate(flow, candidate.loaded, applyCandidate, saved);
2438
- flow.ensure(saved);
2439
- if (result === "close") return "close";
2440
- if (result !== "applied")
2441
- ctx.ui.notify(
2442
- "The profile was saved. Application did not complete; review the configuration result before retrying.",
2443
- "warning"
2444
- );
2445
- } catch (error) {
2446
- if (!flow.current()) throw error;
2447
- ctx.ui.notify(
2448
- `The saved profile was retained, but application did not complete: ${safeError3(error)}. Review active settings before retrying.`,
2449
- "error"
2450
- );
2451
- }
2452
- }
2453
- return saved;
2454
- }
2455
- throw new FlowEnded();
2456
- }
2457
- async function applyReviewedCandidate(flow, loaded, applyCandidate, document) {
2458
- flow.ensure(document);
2459
- const result = await applyCandidate(
2460
- loaded,
2461
- {
2462
- signal: flow.signal,
2463
- // The shared commit policy captures the active revision before applying.
2464
- // A successful apply changes it; session ownership must remain valid after it.
2465
- isCurrent: () => !flow.signal.aborted && flow.sessionCurrent(),
2466
- isSessionCurrent: flow.sessionCurrent
2467
- },
2468
- () => flow.ensure(document),
2469
- document.name
2470
- );
2471
- if (result === "applied") flow.adoptAppliedRevision();
2472
- flow.ensure(document);
2473
- flow.preview(void 0);
2474
- return result;
2475
- }
2476
- async function saveNamedCopy(ctx, options, flow, raw, source) {
2477
- while (flow.current()) {
2478
- const name = await flow.dialog(
2479
- () => ctx.ui.input("Save as a profile", "Profile name (without .toml)", { signal: flow.signal })
2480
- );
2481
- flow.ensure(source);
2482
- if (name === void 0) return void 0;
2483
- try {
2484
- const saved = source?.kind === "profile" ? duplicateProfile(options.settingsPath, source.name, name, source) : createProfile(options.settingsPath, name, requireText(raw));
2485
- ctx.ui.notify(`Profile saved: ${safe(saved.name)}. Active settings are unchanged.`, "info");
2486
- return saved;
2487
- } catch (error) {
2488
- report(ctx, flow, error);
2489
- }
2490
- }
2491
- throw new FlowEnded();
2492
- }
2493
- async function actionScreen(ctx, flow, screen) {
2494
- let selected;
2495
- const menu = defineMenu2({
2496
- start: "actions",
2497
- screens: {
2498
- actions: () => ({
2499
- kind: "actions",
2500
- title: screen.title,
2501
- lines: screen.lines,
2502
- items: [
2503
- {
2504
- id: "review",
2505
- label: "Review TOML",
2506
- to: "document",
2507
- disabled: screen.raw === void 0,
2508
- disabledReason: "The document is not valid UTF-8"
2509
- },
2510
- ...screen.actions.map((action) => ({ ...action, action: "select" }))
2511
- ],
2512
- hint: "back"
2513
- }),
2514
- document: () => ({
2515
- kind: "review",
2516
- title: screen.title,
2517
- lines: ["Exact UTF-8 text \xB7 display controls sanitized \xB7 read-only"],
2518
- content: screen.raw ?? "The document is not valid UTF-8; no decoded fallback is shown.",
2519
- format: { kind: "code", language: "toml" },
2520
- enableSearch: true,
2521
- viewportSize: "adaptive",
2522
- hint: "back"
2523
- })
2524
- },
2525
- actions: {
2526
- select: ({ itemId }) => {
2527
- flow.ensure();
2528
- selected = itemId;
2529
- return { kind: "close" };
2530
- }
2531
- }
2532
- });
2533
- const result = await runMenu2(ctx, menu, { getState: () => void 0, signal: flow.signal, isCurrent: flow.current });
2534
- flow.ensure();
2535
- return selected ?? (result.kind === "closed" && result.reason === "back" ? "back" : "close");
2536
- }
2537
- function createFlow(ctx, options, owner) {
2538
- const controller = new AbortController();
2539
- const signal = AbortSignal.any([controller.signal, owner.signal]);
2540
- let revision = options.getLoadedRevision?.();
2541
- let activeDocument = activeFingerprint(options.getLoaded());
2542
- let previewOwned = false;
2543
- const isCurrent = () => !signal.aborted && owner.isCurrent() && (revision === void 0 ? activeFingerprint(options.getLoaded()) === activeDocument : options.getLoadedRevision?.() === revision);
2544
- const clearPreview = () => {
2545
- if (!previewOwned) return;
2546
- previewOwned = false;
2547
- if (owner.isSessionCurrent?.() ?? owner.isCurrent()) {
2548
- try {
2549
- options.preview?.(void 0, ctx);
2550
- } catch (error) {
2551
- ctx.ui.notify(`Could not clear the footer preview: ${safeError3(error)}`, "error");
2552
- }
2553
- }
2554
- };
2555
- const matches = (expected) => {
2556
- if (!isCurrent()) return false;
2557
- if (!expected) return true;
2558
- try {
2559
- const fresh = expected.kind === "profile" ? readProfile(options.settingsPath, expected.name) : readHistory(options.settingsPath, expected.name);
2560
- return fresh.rawDocument === expected.rawDocument && fresh.identity.dev === expected.identity.dev && fresh.identity.ino === expected.identity.ino && fresh.identity.size === expected.identity.size && fresh.identity.mtimeNs === expected.identity.mtimeNs && fresh.identity.ctimeNs === expected.identity.ctimeNs && fresh.rawBytes.equals(expected.rawBytes);
2561
- } catch {
2562
- return false;
2563
- }
2564
- };
2565
- const ensure = (expected) => {
2566
- if (!isCurrent()) throw new FlowEnded();
2567
- if (!matches(expected))
2568
- throw new Error("The selected document changed or was removed. Review the latest copy before trying again.");
2569
- };
2570
- signal.addEventListener("abort", clearPreview, { once: true });
2571
- return {
2572
- signal,
2573
- current: isCurrent,
2574
- sessionCurrent: () => owner.isSessionCurrent?.() ?? owner.isCurrent(),
2575
- ensure,
2576
- preview(loaded) {
2577
- ensure();
2578
- if (!loaded) {
2579
- clearPreview();
2580
- return;
2581
- }
2582
- previewOwned = true;
2583
- try {
2584
- options.preview?.(loaded, ctx);
2585
- } catch (error) {
2586
- clearPreview();
2587
- throw error;
2588
- }
2589
- },
2590
- async dialog(run) {
2591
- ensure();
2592
- const unsubscribe = ctx.ui.onTerminalInput((data) => {
2593
- if (!isKeyRelease(data) && matchesKey2(data, Key2.ctrl("c"))) {
2594
- queueMicrotask(() => controller.abort());
2595
- }
2596
- return void 0;
2597
- });
2598
- let released = false;
2599
- const release = () => {
2600
- if (released) return;
2601
- released = true;
2602
- unsubscribe();
2603
- };
2604
- signal.addEventListener("abort", release, { once: true });
2605
- try {
2606
- if (signal.aborted) release();
2607
- ensure();
2608
- const result = await run();
2609
- ensure();
2610
- return result;
2611
- } finally {
2612
- signal.removeEventListener("abort", release);
2613
- release();
2614
- }
2615
- },
2616
- adoptAppliedRevision() {
2617
- if (signal.aborted || !(owner.isSessionCurrent?.() ?? owner.isCurrent())) throw new FlowEnded();
2618
- revision = options.getLoadedRevision?.();
2619
- activeDocument = activeFingerprint(options.getLoaded());
2620
- },
2621
- dispose() {
2622
- try {
2623
- clearPreview();
2624
- } finally {
2625
- signal.removeEventListener("abort", clearPreview);
2626
- controller.abort();
2627
- }
2628
- }
2629
- };
2630
- }
2631
- function candidateFor(options, raw, required = false) {
2632
- try {
2633
- if (raw === void 0) throw new Error("The document is not valid UTF-8; no decoded fallback is shown.");
2634
- const loaded = (options.validate ?? validateConfigDocument)(options.settingsPath, raw);
2635
- if (loaded.diagnostics.some((item) => item.severity === "error"))
2636
- throw new Error(loaded.diagnostics.map((item) => item.message).join("; "));
2637
- return {
2638
- loaded,
2639
- lines: loaded.diagnostics.length === 0 ? ["No configuration warnings."] : loaded.diagnostics.map((item) => `${safe(item.path || "root")}: ${safe(item.message)}`)
2640
- };
2641
- } catch (error) {
2642
- if (required) throw error;
2643
- return { lines: [`Invalid TOML: ${safeError3(error)}`, "No candidate footer preview is shown."] };
2644
- }
2645
- }
2646
- function requireText(raw) {
2647
- if (raw === void 0) throw new Error("The document is not valid UTF-8; no decoded fallback can be saved.");
2648
- return raw;
2649
- }
2650
- function activeFingerprint(loaded) {
2651
- return JSON.stringify([loaded.source, loaded.rawDocument, loaded.diagnostics]);
2652
- }
2653
- function current2(owner) {
2654
- return !owner.signal.aborted && owner.isCurrent();
2655
- }
2656
- function interactive(ctx) {
2657
- if (ctx.mode === "tui" && ctx.hasUI) return true;
2658
- if (ctx.hasUI) ctx.ui.notify("Profiles and History require TUI mode.", "info");
2659
- return false;
2660
- }
2661
- function documentId(document) {
2662
- return `${document.kind}:${document.name}`;
2663
- }
2664
- function report(ctx, flow, error) {
2665
- if (!(error instanceof FlowEnded) && flow.current()) ctx.ui.notify(safeError3(error), "error");
2666
- }
2667
- function safeError3(error) {
2668
- return safe(error instanceof Error ? error.message : String(error));
2669
- }
2670
- function safe(value) {
2671
- return sanitizeTerminalText3(value);
2672
- }
2673
-
2674
- // src/commands.ts
2675
- var MAIN_ACTIONS = {
2676
- customize: "customize",
2677
- presets: "presets",
2678
- explain: "explain",
2679
- modules: "modules",
2680
- configuration: "configuration",
2681
- help: "help",
2682
- restore: "restore",
2683
- profiles: "profiles"
2684
- };
2685
- var PREVIEW_ACTIONS = {
2686
- continue: "continue",
2687
- edit: "edit",
2688
- cancel: "cancel",
2689
- saveProfile: "save-profile"
2690
- };
2691
- function registerStarshipCommand(pi, options) {
2692
- pi.registerCommand("starship", {
2693
- description: "Customize or inspect the native Starship-style footer",
2694
- getArgumentCompletions: completeStarshipArguments,
2695
- handler: (args, ctx) => handleStarshipCommand(args, ctx, options)
2696
- });
2697
- }
2698
- async function handleStarshipCommand(args, ctx, options) {
2699
- if (ctx.mode !== "tui") return runStarshipCommand(args, ctx, options);
2700
- const base = workflowOwner(options);
2701
- if (!isCurrentOwner2(base)) return;
2702
- const controller = new AbortController();
2703
- const signal = AbortSignal.any([base.signal, controller.signal]);
2704
- const owner = {
2705
- signal,
2706
- isCurrent: () => !signal.aborted && base.isCurrent(),
2707
- isSessionCurrent: () => base.isSessionCurrent?.() ?? base.isCurrent()
2708
- };
2709
- const unsubscribe = ctx.ui.onTerminalInput((data) => {
2710
- if (!isKeyRelease2(data) && matchesKey3(data, Key3.ctrl("c"))) {
2711
- queueMicrotask(() => controller.abort());
2712
- }
2713
- return void 0;
2714
- });
2715
- let listening = true;
2716
- const release = () => {
2717
- if (!listening) return;
2718
- listening = false;
2719
- unsubscribe();
2720
- };
2721
- signal.addEventListener("abort", release, { once: true });
2722
- try {
2723
- return await runStarshipCommand(args, ctx, { ...options, getMenuOwner: () => owner });
2724
- } finally {
2725
- signal.removeEventListener("abort", release);
2726
- release();
2727
- controller.abort();
2728
- }
2729
- }
2730
- async function runStarshipCommand(args, ctx, options) {
2731
- const normalized = args.trim();
2732
- if (!normalized) {
2733
- if (ctx.mode === "tui") await showMainMenu(ctx, options);
2734
- else showHelp(ctx, options.settingsPath);
2735
- return;
2736
- }
2737
- const [subcommand = "", ...trailing] = normalized.split(/\s+/u);
2738
- const route = subcommand.toLowerCase();
2739
- if (trailing.length > 0 || !STARSHIP_SUBCOMMANDS.some((item) => item.value === route)) {
2740
- if (canNotify(ctx)) {
2741
- const reason = trailing.length > 0 ? `Unexpected arguments for /starship ${safeText(route)}.` : `Unknown /starship subcommand: ${safeText(route)}.`;
2742
- ctx.ui.notify(`${reason} Usage: /starship [settings|status|help]`, "warning");
2743
- }
2744
- return;
2745
- }
2746
- switch (route) {
2747
- case "settings":
2748
- await editSettings(ctx, options);
2749
- return;
2750
- case "status":
2751
- showStatus(ctx, options);
2752
- return;
2753
- case "help":
2754
- showHelp(ctx, options.settingsPath);
2755
- return;
2756
- }
2757
- }
2758
- async function showMainMenu(ctx, options) {
2759
- const fallbackController = new AbortController();
2760
- const owner = options.getMenuOwner?.() ?? {
2761
- signal: fallbackController.signal,
2762
- isCurrent: () => !fallbackController.signal.aborted
2763
- };
2764
- const menu = defineMenu3({
2765
- start: "main",
2766
- screens: {
2767
- main: () => {
2768
- const loaded = options.getLoaded();
2769
- const presentation = configurationPresentation(loaded);
2770
- return {
2771
- kind: "actions",
2772
- title: "pi-starship",
2773
- lines: [`${presentation.state} \xB7 ${presentation.health}`],
2774
- items: [
2775
- {
2776
- id: MAIN_ACTIONS.customize,
2777
- label: "Customize footer",
2778
- description: `${presentation.state} \xB7 preview before applying`,
2779
- action: "customize"
2780
- },
2781
- {
2782
- id: MAIN_ACTIONS.presets,
2783
- label: "Presets",
2784
- description: "Browse and live-preview bundled footer starting points",
2785
- action: "presets"
2786
- },
2787
- {
2788
- id: MAIN_ACTIONS.explain,
2789
- label: "Explain footer",
2790
- description: "Why each visible module appears",
2791
- to: "explain"
2792
- },
2793
- {
2794
- id: MAIN_ACTIONS.modules,
2795
- label: "Modules",
2796
- description: "Browse supported modules and current states",
2797
- to: "modules"
2798
- },
2799
- {
2800
- id: MAIN_ACTIONS.configuration,
2801
- label: "Configuration",
2802
- description: presentation.health,
2803
- to: "configuration"
2804
- },
2805
- {
2806
- id: MAIN_ACTIONS.help,
2807
- label: "Help",
2808
- description: "Formats, modules, and commands",
2809
- to: "help"
2810
- },
2811
- {
2812
- id: MAIN_ACTIONS.restore,
2813
- label: "Restore built-in\u2026",
2814
- description: presentation.restoreDescription,
2815
- disabled: presentation.restoreDisabled,
2816
- action: "restore"
2817
- },
2818
- {
2819
- id: MAIN_ACTIONS.profiles,
2820
- label: "Profiles",
2821
- description: "Save, edit, manage, and live-preview named TOML documents",
2822
- action: "profiles"
2823
- }
2824
- ],
2825
- hint: "close"
2826
- };
2827
- },
2828
- explain: () => ({
2829
- kind: "review",
2830
- title: "Explain footer",
2831
- content: formatFooterExplanation(options.getInspection?.()),
2832
- format: { kind: "text" },
2833
- viewportSize: "adaptive",
2834
- hint: "back"
2835
- }),
2836
- modules: () => {
2837
- const inspection = options.getInspection?.() ?? inspectUnavailableModules(options.getLoaded().config);
2838
- return {
2839
- kind: "browse",
2840
- title: "Modules",
2841
- items: inspection.modules.map((module) => ({
2842
- id: module.name,
2843
- label: module.name,
2844
- statusText: module.state,
2845
- description: module.description,
2846
- searchText: [...module.variables, ...module.styleFields, ...module.displayRules].join(" "),
2847
- details: [
2848
- `Root: ${module.rootReferenced ? "Referenced" : "Not referenced"}`,
2849
- `Reachable: ${module.reachable ? "Yes" : "No"}`,
2850
- ...modulePreviewDetails(module.preview),
2851
- `Reason: ${module.reason}`,
2852
- `Variables: ${module.variables.join(", ") || "none"}`,
2853
- `Style fields: ${module.styleFields.join(", ") || "none"}`,
2854
- `Style-rule selectors: ${module.styleRuleSelectors.join(", ") || "none"}`,
2855
- `Style rules: ${module.styleRuleCount} configured`,
2856
- `Display rules: ${module.displayRules.join(" \xB7 ") || "none"}`
2857
- ]
2858
- })),
2859
- viewportSize: "adaptive",
2860
- hint: "back"
2861
- };
2862
- },
2863
- configuration: () => configurationMenuScreen(options.getLoaded()),
2864
- "configuration-overview": () => configurationOverviewScreen(options.getLoaded(), options.settingsPath),
2865
- "configuration-effective": () => effectiveConfigurationScreen(options.getLoaded()),
2866
- "configuration-document": () => settingsDocumentScreen(options.getLoaded(), options.settingsPath),
2867
- help: () => ({
2868
- kind: "detail",
2869
- title: "pi-starship help",
2870
- lines: [
2871
- "Customize footer opens the TOML editor, then previews and confirms before saving.",
2872
- "Presets live-previews the cursor in the footer; Enter confirms apply, e customizes, and s saves a profile when available.",
2873
- "Profiles manages named TOML copies; selecting a document previews it without saving.",
2874
- "Configuration History reviews and restores recovery copies; external edits are not fully tracked.",
2875
- "Explain footer breaks down the modules currently showing from the existing snapshot.",
2876
- "Modules searches every supported module and explains its current read-only state.",
2877
- "Configuration includes disk reload plus unlisted Gist sharing and reviewed Gist import through gh.",
2878
- `Settings: ${safeText(options.settingsPath)}`,
2879
- "Docs: https://github.com/narumiruna/pi-extensions/tree/main/packages/pi-starship"
2880
- ],
2881
- hint: "back"
2882
- })
2883
- },
2884
- actions: {
2885
- customize: async () => {
2886
- const result = await editSettings(ctx, options);
2887
- return result === "applied" || result === "close" ? { kind: "close" } : { kind: "stay" };
2888
- },
2889
- presets: async () => {
2890
- const result = await choosePreset(ctx, options, owner);
2891
- return result === "applied" || result === "close" ? { kind: "close" } : { kind: "stay" };
2892
- },
2893
- profiles: async () => {
2894
- const result = await showProfiles(ctx, options, owner, async (loaded, guardedOwner, checkCandidate, name) => {
2895
- const applied = await reviewAndApply(
2896
- ctx,
2897
- options,
2898
- loaded,
2899
- { kind: "profile", name },
2900
- guardedOwner,
2901
- false,
2902
- checkCandidate
2903
- );
2904
- return applied === "applied" ? "applied" : applied === "close" ? "close" : "stay";
2905
- });
2906
- return result === "close" ? { kind: "close" } : { kind: "stay" };
2907
- },
2908
- history: async () => {
2909
- const result = await showHistory(ctx, options, owner, async (loaded, guardedOwner, checkCandidate, name) => {
2910
- const applied = await reviewAndApply(
2911
- ctx,
2912
- options,
2913
- loaded,
2914
- { kind: "history", name },
2915
- guardedOwner,
2916
- false,
2917
- checkCandidate
2918
- );
2919
- return applied === "applied" ? "applied" : applied === "close" ? "close" : "stay";
2920
- });
2921
- return result === "close" ? { kind: "close" } : { kind: "stay" };
2922
- },
2923
- "gist-share": async () => {
2924
- const result = await shareSettingsGist(ctx, options, owner, options.gistApi);
2925
- return result === "close" ? { kind: "close" } : { kind: "stay" };
2926
- },
2927
- "gist-import": async () => {
2928
- const result = await importSettingsGist(
2929
- ctx,
2930
- options,
2931
- owner,
2932
- async (loaded, guardedOptions, guardedOwner) => {
2933
- const applied = await reviewAndApply(ctx, guardedOptions, loaded, { kind: "import" }, guardedOwner);
2934
- return applied === "edit" ? "cancel" : applied;
2935
- },
2936
- options.gistApi
2937
- );
2938
- return result === "applied" || result === "close" ? { kind: "close" } : { kind: "stay" };
2939
- },
2940
- "configuration-reload": async () => {
2941
- const result = await reloadConfiguration(ctx, options, owner);
2942
- return result === "close" ? { kind: "close" } : { kind: "stay" };
2943
- },
2944
- restore: async () => {
2945
- const presentation = configurationPresentation(options.getLoaded());
2946
- if (presentation.restoreDisabled) {
2947
- ctx.ui.notify(presentation.restoreDescription, "info");
2948
- return { kind: "stay" };
2949
- }
2950
- const result = await restoreBuiltIn(ctx, options);
2951
- return result === "applied" || result === "close" ? { kind: "close" } : { kind: "stay" };
2952
- }
2953
- }
2954
- });
2955
- try {
2956
- await runMenu3(ctx, menu, {
2957
- getState: () => void 0,
2958
- signal: owner.signal,
2959
- isCurrent: owner.isCurrent
2960
- });
2961
- } finally {
2962
- fallbackController.abort(new DOMException("Starship menu closed", "AbortError"));
2963
- }
2964
- }
2965
- async function editSettings(ctx, options) {
2966
- const owner = workflowOwner(options);
2967
- if (!isCurrentOwner2(owner)) return "cancel";
2968
- if (ctx.mode !== "tui") {
2969
- if (ctx.hasUI) ctx.ui.notify(`Edit settings manually: ${options.settingsPath}`, "info");
2970
- return "cancel";
2971
- }
2972
- const expected = captureExpectation(ctx, options);
2973
- if (!expected) return "cancel";
2974
- let draft = expected.previous.rawDocument ?? BUILT_IN_EXAMPLE;
2975
- while (true) {
2976
- const edited = await ctx.ui.editor("Customize footer \u2014 close to preview", draft);
2977
- if (!commitOwnerCurrent(options, owner, expected) || edited === void 0) return "cancel";
2978
- draft = edited;
2979
- let validated;
2980
- try {
2981
- validated = (options.validate ?? validateConfigDocument)(options.settingsPath, draft);
2982
- } catch (error) {
2983
- ctx.ui.notify(`Footer draft is invalid: ${safeText(formatError2(error))}`, "error");
2984
- const action = await showPreviewActionMenu(
2985
- ctx,
2986
- "Configuration needs attention",
2987
- () => [safeText(formatError2(error)), "The current footer has not changed."],
2988
- [
2989
- { value: PREVIEW_ACTIONS.edit, label: "Continue editing" },
2990
- { value: PREVIEW_ACTIONS.cancel, label: "Discard draft" }
2991
- ],
2992
- owner.signal,
2993
- owner.isCurrent
2994
- );
2995
- if (!commitOwnerCurrent(options, owner, expected)) return "cancel";
2996
- if (action?.kind === "closed") return "close";
2997
- if (selectedPreviewAction(action) === PREVIEW_ACTIONS.edit) continue;
2998
- return "cancel";
2999
- }
3000
- const result = await reviewAndApply(
3001
- ctx,
3002
- options,
3003
- validated,
3004
- { kind: "customize" },
3005
- owner,
3006
- false,
3007
- void 0,
3008
- expected
3009
- );
3010
- if (result === "edit") continue;
3011
- return result;
3012
- }
3013
- }
3014
- async function choosePreset(ctx, options, owner) {
3015
- const expected = captureExpectation(ctx, options);
3016
- if (!expected) return "cancel";
3017
- const activePreset = presetForDocument(expected.previous.rawDocument);
3018
- const selection = await showPresetPicker(ctx, {
3019
- presets: STARSHIP_PRESETS,
3020
- activePresetId: activePreset?.id,
3021
- initialPresetId: activePreset?.id ?? STARSHIP_PRESETS[0]?.id,
3022
- signal: owner.signal,
3023
- isCurrent: owner.isCurrent,
3024
- preview(preset2) {
3025
- const loaded = (options.validate ?? validateConfigDocument)(options.settingsPath, preset2.rawDocument);
3026
- options.preview?.(loaded, ctx);
3027
- }
3028
- });
3029
- if (!commitOwnerCurrent(options, owner, expected)) {
3030
- clearSessionPreview(ctx, options, owner);
3031
- return "cancel";
3032
- }
3033
- if (selection.kind === "back" || selection.kind === "close") {
3034
- clearSessionPreview(ctx, options, owner);
3035
- return selection.kind === "close" ? "close" : "cancel";
3036
- }
3037
- const preset = getStarshipPreset(selection.presetId);
3038
- try {
3039
- if (selection.kind === "save-profile") {
3040
- const saved = await saveAsProfile(ctx, options, owner, preset.rawDocument);
3041
- return saved === "close" ? "close" : "cancel";
3042
- }
3043
- return await applyPreset(
3044
- ctx,
3045
- options,
3046
- preset,
3047
- selection.kind === "customize" ? "customize" : "confirm",
3048
- expected,
3049
- owner
3050
- );
3051
- } finally {
3052
- clearSessionPreview(ctx, options, owner);
3053
- }
3054
- }
3055
- async function applyPreset(ctx, options, preset, start = "review", captured, capturedOwner) {
3056
- const owner = capturedOwner ?? workflowOwner(options);
3057
- if (!isCurrentOwner2(owner)) return "cancel";
3058
- const expected = captured ?? captureExpectation(ctx, options);
3059
- if (!expected) return "cancel";
3060
- let draft = preset.rawDocument;
3061
- if (start === "customize") {
3062
- const edited = await ctx.ui.editor(`Customize ${preset.label} preset`, draft);
3063
- if (!commitOwnerCurrent(options, owner, expected) || edited === void 0) return "cancel";
3064
- draft = edited;
3065
- }
3066
- while (true) {
3067
- let validated;
3068
- try {
3069
- validated = (options.validate ?? validateConfigDocument)(options.settingsPath, draft);
3070
- } catch (error) {
3071
- ctx.ui.notify(`Preset draft is invalid: ${safeText(formatError2(error))}`, "error");
3072
- const action = await showPreviewActionMenu(
3073
- ctx,
3074
- "Preset needs attention",
3075
- () => [safeText(formatError2(error)), "The current footer has not changed."],
3076
- [
3077
- { value: PREVIEW_ACTIONS.edit, label: "Continue editing" },
3078
- { value: PREVIEW_ACTIONS.cancel, label: "Choose another preset" }
3079
- ],
3080
- owner.signal,
3081
- owner.isCurrent
3082
- );
3083
- if (!commitOwnerCurrent(options, owner, expected)) return "cancel";
3084
- if (action?.kind === "closed") return "close";
3085
- if (selectedPreviewAction(action) !== PREVIEW_ACTIONS.edit) return "cancel";
3086
- const edited2 = await ctx.ui.editor(`Customize ${preset.label} preset`, draft);
3087
- if (!commitOwnerCurrent(options, owner, expected) || edited2 === void 0) return "cancel";
3088
- draft = edited2;
3089
- continue;
3090
- }
3091
- const result = await reviewAndApply(
3092
- ctx,
3093
- options,
3094
- validated,
3095
- { kind: "preset", preset },
3096
- owner,
3097
- start === "confirm",
3098
- void 0,
3099
- expected
3100
- );
3101
- if (result !== "edit") return result;
3102
- const edited = await ctx.ui.editor(`Customize ${preset.label} preset`, draft);
3103
- if (!commitOwnerCurrent(options, owner, expected) || edited === void 0) return "cancel";
3104
- draft = edited;
3105
- }
3106
- }
3107
- async function restoreBuiltIn(ctx, options) {
3108
- const owner = workflowOwner(options);
3109
- if (!isCurrentOwner2(owner)) return "cancel";
3110
- const validated = (options.validate ?? validateConfigDocument)(options.settingsPath, BUILT_IN_EXAMPLE);
3111
- const result = await reviewAndApply(ctx, options, validated, { kind: "restore" }, owner);
3112
- return result === "edit" ? "cancel" : result;
3113
- }
3114
- async function reviewAndApply(ctx, options, validated, intent, owner, skipReview = false, checkCandidate, captured) {
3115
- if (ctx.mode !== "tui" || !isCurrentOwner2(owner)) return "cancel";
3116
- const expected = captured ?? captureExpectation(ctx, options);
3117
- if (!expected) return "cancel";
3118
- let reviewRequired = !skipReview;
3119
- while (true) {
3120
- const directAttempt = !reviewRequired;
3121
- if (reviewRequired) {
3122
- const selection = await showPreviewActionMenu(
3123
- ctx,
3124
- reviewTitle(intent),
3125
- (width) => reviewPreviewBody(ctx, options, validated, width, intent),
3126
- [
3127
- { value: PREVIEW_ACTIONS.continue, label: continueLabel(intent) },
3128
- ...intent.kind !== "customize" && intent.kind !== "preset" ? [] : [
3129
- {
3130
- value: PREVIEW_ACTIONS.edit,
3131
- label: intent.kind === "preset" ? "Customize before applying" : "Continue editing"
3132
- }
3133
- ],
3134
- {
3135
- value: PREVIEW_ACTIONS.cancel,
3136
- label: intent.kind === "restore" ? "Cancel" : intent.kind === "preset" ? "Choose another preset" : "Discard draft"
3137
- },
3138
- ...intent.kind === "customize" || intent.kind === "preset" || intent.kind === "import" ? [{ value: PREVIEW_ACTIONS.saveProfile, label: "Save as profile\u2026" }] : []
3139
- ],
3140
- owner.signal,
3141
- owner.isCurrent
3142
- );
3143
- if (!commitOwnerCurrent(options, owner, expected)) return "cancel";
3144
- if (selection?.kind === "closed") return "close";
3145
- const selected = selectedPreviewAction(selection);
3146
- if (selected === PREVIEW_ACTIONS.edit) return "edit";
3147
- if (selected === PREVIEW_ACTIONS.saveProfile) {
3148
- const saved = await saveAsProfile(ctx, options, owner, validated.rawDocument ?? BUILT_IN_EXAMPLE);
3149
- if (saved === "close") return "close";
3150
- if (!commitOwnerCurrent(options, owner, expected)) return "cancel";
3151
- continue;
3152
- }
3153
- if (selected !== PREVIEW_ACTIONS.continue) return "cancel";
3154
- }
3155
- reviewRequired = true;
3156
- const confirmed = await ctx.ui.confirm(
3157
- confirmationTitle(intent),
3158
- confirmationMessage(options.settingsPath, intent, expected.previous),
3159
- { signal: owner.signal }
3160
- );
3161
- if (!commitOwnerCurrent(options, owner, expected)) return "cancel";
3162
- if (!confirmed) {
3163
- if (directAttempt) return "cancel";
3164
- continue;
3165
- }
3166
- try {
3167
- const result = await commitActiveDocument(
3168
- ctx,
3169
- options,
3170
- validated,
3171
- owner,
3172
- expected,
3173
- intent.kind === "restore" || intent.kind === "history" || intent.kind === "customize",
3174
- checkCandidate
3175
- );
3176
- if (!isSessionOwnerCurrent(owner) || result === "cancel") return "cancel";
3177
- } catch (error) {
3178
- if (!isSessionOwnerCurrent(owner)) return "cancel";
3179
- ctx.ui.notify(safeText(formatError2(error)), "error");
3180
- if (directAttempt) return "cancel";
3181
- continue;
3182
- }
3183
- const warningSuffix = validated.diagnostics.length > 0 ? ` (${validated.diagnostics.length} warning${validated.diagnostics.length === 1 ? "" : "s"})` : "";
3184
- ctx.ui.notify(`${successMessage(intent)}${warningSuffix}.`, "info");
3185
- return "applied";
3186
- }
3187
- }
3188
- function reviewTitle(intent) {
3189
- switch (intent.kind) {
3190
- case "customize":
3191
- return "Footer preview";
3192
- case "restore":
3193
- return "Restore preview";
3194
- case "import":
3195
- return "Gist footer preview";
3196
- case "profile":
3197
- return `${safeText(intent.name)} profile preview`;
3198
- case "history":
3199
- return "History recovery preview";
3200
- case "preset":
3201
- return `${intent.preset.label} preset preview`;
3202
- }
3203
- }
3204
- function continueLabel(intent) {
3205
- switch (intent.kind) {
3206
- case "customize":
3207
- return "Apply changes\u2026";
3208
- case "restore":
3209
- return "Replace with built-in\u2026";
3210
- case "import":
3211
- return "Replace with Gist settings\u2026";
3212
- case "profile":
3213
- return `Apply ${safeText(intent.name)} profile\u2026`;
3214
- case "history":
3215
- return "Restore history document\u2026";
3216
- case "preset":
3217
- return `Apply ${intent.preset.label} preset\u2026`;
3218
- }
3219
- }
3220
- function confirmationTitle(intent) {
3221
- switch (intent.kind) {
3222
- case "customize":
3223
- return "Apply footer changes?";
3224
- case "restore":
3225
- return "Restore built-in footer?";
3226
- case "import":
3227
- return "Replace settings with Gist?";
3228
- case "profile":
3229
- return `Apply ${safeText(intent.name)} profile?`;
3230
- case "history":
3231
- return "Restore settings from history?";
3232
- case "preset":
3233
- return `Apply ${intent.preset.label} preset?`;
3234
- }
3235
- }
3236
- function confirmationMessage(settingsPath, intent, previous) {
3237
- if (previous.diagnostics.some((item) => item.severity === "error")) {
3238
- return `Explicit recovery: replace the invalid settings file ${safeText(settingsPath)} entirely with the reviewed document? Its exact original bytes will be kept in History before replacement.`;
3239
- }
3240
- if (intent.kind === "customize")
3241
- return "Replace the entire settings document and apply it immediately? Its previous bytes will be kept in History.";
3242
- const replacement = intent.kind === "restore" ? "the built-in configuration" : intent.kind === "import" ? "the reviewed Gist settings" : intent.kind === "profile" ? `the ${safeText(intent.name)} profile` : intent.kind === "history" ? "the reviewed history document" : `the ${intent.preset.label} preset`;
3243
- return `Replace ${safeText(settingsPath)} entirely with ${replacement}? All custom settings, unknown fields, and comments will be replaced. The previous document will be kept in History.`;
3244
- }
3245
- function successMessage(intent) {
3246
- switch (intent.kind) {
3247
- case "customize":
3248
- return "Footer settings saved and applied";
3249
- case "restore":
3250
- return "Built-in footer restored and applied";
3251
- case "import":
3252
- return "Gist settings saved and applied";
3253
- case "profile":
3254
- return `${safeText(intent.name)} profile applied`;
3255
- case "history":
3256
- return "History document restored and applied";
3257
- case "preset":
3258
- return `${intent.preset.label} preset saved and applied`;
3259
- }
3260
- }
3261
- function modulePreviewDetails(preview) {
3262
- const lines = preview ? preview.split("\n") : ["(no current preview)"];
3263
- return lines.map((line, index) => `${index === 0 ? "Preview: " : " "}${line}`);
3264
- }
3265
- function workflowOwner(options) {
3266
- if (options.getMenuOwner) return options.getMenuOwner();
3267
- const controller = new AbortController();
3268
- return { signal: controller.signal, isCurrent: () => true };
3269
- }
3270
- function isCurrentOwner2(owner) {
3271
- return !owner.signal.aborted && owner.isCurrent();
3272
- }
3273
- function isSessionOwnerCurrent(owner) {
3274
- return !owner.signal.aborted && (owner.isSessionCurrent?.() ?? owner.isCurrent());
3275
- }
3276
- function clearSessionPreview(ctx, options, owner) {
3277
- if (owner.isSessionCurrent?.() ?? owner.isCurrent()) options.preview?.(void 0, ctx);
3278
- }
3279
- function captureExpectation(ctx, options) {
3280
- try {
3281
- return captureCommitExpectation(options);
3282
- } catch (error) {
3283
- ctx.ui.notify(`Footer settings were not saved: ${safeText(formatError2(error))}`, "error");
3284
- return void 0;
3285
- }
3286
- }
3287
- function reviewPreviewBody(ctx, options, loaded, width, intent) {
3288
- if (intent.kind === "restore") return restorePreviewBody(ctx, options, loaded, width);
3289
- if (intent.kind !== "preset") return previewBody(ctx, options, loaded, width);
3290
- const current3 = configurationPresentation(options.getLoaded());
3291
- return [
3292
- `Preset: ${intent.preset.label}`,
3293
- `Requirement: ${intent.preset.requiresNerdFont ? "Nerd Font" : "No special font"}`,
3294
- `Current: ${current3.state}`,
3295
- `Path: ${safeText(options.settingsPath)}`,
3296
- "Applying replaces the entire settings document, including custom settings, unknown fields, and comments.",
3297
- "The previous document will be kept in History before replacement.",
3298
- "",
3299
- ...previewBody(ctx, options, loaded, width)
3300
- ];
3301
- }
3302
- function restorePreviewBody(ctx, options, loaded, width) {
3303
- const current3 = configurationPresentation(options.getLoaded());
3304
- return [
3305
- `Current: ${current3.state}`,
3306
- `Path: ${safeText(options.settingsPath)}`,
3307
- "The entire settings document will be replaced, including custom settings, unknown fields, and comments.",
3308
- "The previous document will be kept in History before replacement.",
3309
- "",
3310
- ...previewBody(ctx, options, loaded, width)
3311
- ];
3312
- }
3313
- function previewBody(ctx, options, loaded, width) {
3314
- let lines;
3315
- try {
3316
- lines = options.renderPreview?.(loaded, width, ctx) ?? [
3317
- "Live preview is unavailable until the footer is ready.",
3318
- "The draft is valid and can still be applied."
3319
- ];
3320
- } catch (error) {
3321
- lines = [`Preview unavailable: ${safeText(formatError2(error))}`];
3322
- }
3323
- const warning = loaded.diagnostics.length === 0 ? "Draft validation: Healthy" : `Draft validation: ${loaded.diagnostics.length} warning${loaded.diagnostics.length === 1 ? "" : "s"}`;
3324
- return [...lines, "", warning];
3325
- }
3326
- function selectedPreviewAction(result) {
3327
- return result?.kind === "selected" ? result.value : null;
3328
- }
3329
- function showStatus(ctx, options) {
3330
- if (!canNotify(ctx)) return;
3331
- const loaded = options.getLoaded();
3332
- const diagnostics = loaded.diagnostics.slice(0, 5).map((item) => `${safeText(item.path || "root")}: ${safeText(item.message)}`).join("; ");
3333
- ctx.ui.notify(
3334
- [
3335
- `pi-starship source: ${loaded.source}`,
3336
- `path: ${options.settingsPath}`,
3337
- diagnostics ? `warnings: ${diagnostics}` : "warnings: none"
3338
- ].join("\n"),
3339
- loaded.diagnostics.length > 0 ? "warning" : "info"
3340
- );
3341
- }
3342
- function showHelp(ctx, settingsPath) {
3343
- if (!canNotify(ctx)) return;
3344
- ctx.ui.notify(
3345
- [
3346
- "/starship \u2014 manage profiles, live-preview presets, recover history, explain, or inspect the footer in TUI mode",
3347
- "/starship settings \u2014 customize, preview, and apply TOML",
3348
- "/starship status \u2014 show source, path, and warnings",
3349
- "/starship help \u2014 show this help",
3350
- `Settings: ${settingsPath}`,
3351
- "Format/module docs: https://github.com/narumiruna/pi-extensions/tree/main/packages/pi-starship"
3352
- ].join("\n"),
3353
- "info"
3354
- );
3355
- }
3356
- function canNotify(ctx) {
3357
- return ctx.mode === "tui" || ctx.hasUI;
3358
- }
3359
- function safeText(value) {
3360
- return Array.from(value, (character) => {
3361
- const codePoint = character.codePointAt(0) ?? 0;
3362
- const unsafe = codePoint <= 8 || codePoint >= 11 && codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
3363
- return unsafe ? `\\u${codePoint.toString(16).padStart(4, "0")}` : character;
3364
- }).join("");
3365
- }
3366
- function formatError2(error) {
3367
- return error instanceof Error ? error.message : String(error);
3368
- }
3369
- export {
3370
- handleStarshipCommand,
3371
- registerStarshipCommand,
3372
- reviewAndApply
3373
- };
3374
- //# sourceMappingURL=commands-C2VJ6ZBN.ts.map