@narumitw/pi-starship 0.60.0 → 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 (115) 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 +29 -1
  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/skills/configure-pi-starship/scripts/config-path.mjs +63 -3
  51. package/src/command-configuration-menu.ts +155 -0
  52. package/src/command-configuration.ts +9 -84
  53. package/src/command-preview.ts +3 -3
  54. package/src/command-settings-chat.ts +210 -0
  55. package/src/commands.ts +54 -98
  56. package/src/config/module-options.ts +112 -0
  57. package/src/config.ts +17 -53
  58. package/src/effective-config.ts +5 -4
  59. package/src/format/bounded-regex.ts +66 -0
  60. package/src/format/version.ts +24 -0
  61. package/src/modules/catalog.ts +10 -0
  62. package/src/modules/cloud.ts +1 -0
  63. package/src/modules/deployment.ts +8 -0
  64. package/src/modules/development.ts +20 -2
  65. package/src/modules/directory.ts +171 -51
  66. package/src/modules/execution.ts +2 -0
  67. package/src/modules/git/branch.ts +19 -4
  68. package/src/modules/git/commit.ts +9 -2
  69. package/src/modules/git/metrics.ts +9 -4
  70. package/src/modules/git/runtime.ts +122 -33
  71. package/src/modules/git/state.ts +23 -2
  72. package/src/modules/git/status-templates.ts +58 -0
  73. package/src/modules/git/status.ts +96 -30
  74. package/src/modules/jujutsu.ts +225 -0
  75. package/src/modules/languages.ts +26 -2
  76. package/src/modules/package.ts +1 -0
  77. package/src/modules/render.ts +42 -16
  78. package/src/modules/system.ts +54 -0
  79. package/src/modules/time-format.ts +188 -0
  80. package/src/modules/time.ts +11 -5
  81. package/src/modules/types.ts +42 -4
  82. package/src/pi-starship.ts +56 -12
  83. package/src/profile-store.ts +5 -0
  84. package/src/runtime/cloud.ts +3 -0
  85. package/src/runtime/command.ts +1 -1
  86. package/src/runtime/deployment.ts +120 -4
  87. package/src/runtime/development.ts +86 -13
  88. package/src/runtime/directory.ts +33 -0
  89. package/src/runtime/execution.ts +12 -2
  90. package/src/runtime/helpers.ts +57 -8
  91. package/src/runtime/jujutsu.ts +225 -0
  92. package/src/runtime/languages.ts +106 -19
  93. package/src/runtime/package.ts +3 -0
  94. package/src/runtime/system.ts +202 -0
  95. package/src/runtime/types.ts +3 -0
  96. package/src/runtime/version-requirements.ts +30 -0
  97. package/src/runtime/workspace.ts +12 -1
  98. package/src/settings-agent.ts +80 -0
  99. package/src/settings-chat-transcript.ts +140 -0
  100. package/src/settings-chat-ui.ts +426 -0
  101. package/src/settings-draft.ts +260 -0
  102. package/src/settings-snapshots.ts +41 -0
  103. package/dist/chunks/chunk-ADX4CY27.ts.map +0 -7
  104. package/dist/chunks/chunk-KZZKGGFW.ts.map +0 -7
  105. package/dist/chunks/chunk-PD457PX5.ts.map +0 -7
  106. package/dist/chunks/cloud-EPAEV4ZB.ts.map +0 -7
  107. package/dist/chunks/commands-C2VJ6ZBN.ts +0 -3374
  108. package/dist/chunks/commands-C2VJ6ZBN.ts.map +0 -7
  109. package/dist/chunks/deployment-7J54EHNR.ts.map +0 -7
  110. package/dist/chunks/development-IWJAAAEV.ts.map +0 -7
  111. package/dist/chunks/execution-P4WZALW2.ts.map +0 -7
  112. package/dist/chunks/languages-JO6R2PHL.ts +0 -168
  113. package/dist/chunks/languages-JO6R2PHL.ts.map +0 -7
  114. package/dist/chunks/package-H24VJEX3.ts.map +0 -7
  115. package/src/command-inspector.ts +0 -41
@@ -0,0 +1,646 @@
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
+ archiveConfigDocument,
5
+ createProfile,
6
+ deleteHistory,
7
+ deleteProfile,
8
+ duplicateProfile,
9
+ listHistory,
10
+ listProfiles,
11
+ readHistory,
12
+ readProfile,
13
+ renameProfile,
14
+ saveProfile
15
+ } from "./chunk-43VIENBN.ts";
16
+ import {
17
+ BUILT_IN_EXAMPLE,
18
+ ConfigPublicationError,
19
+ assertConfigDocumentUnchanged,
20
+ atomicRestoreConfigDocument,
21
+ atomicSaveConfigDocument,
22
+ readConfigDocumentSnapshot,
23
+ removeConfigDocumentIfMatches,
24
+ validateConfigDocument
25
+ } from "./chunk-PWTSHSP3.ts";
26
+
27
+ // src/command-commit.ts
28
+ import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
29
+ function captureCommitExpectation(options) {
30
+ return {
31
+ previous: options.getLoaded(),
32
+ revision: options.getLoadedRevision?.(),
33
+ disk: readConfigDocumentSnapshot(options.settingsPath)
34
+ };
35
+ }
36
+ function commitOwnerCurrent(options, owner, expected) {
37
+ const loaded = options.getLoaded();
38
+ 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;
39
+ }
40
+ async function commitActiveDocument(ctx, options, candidate, owner, expected, allowInvalid = false, checkCandidate) {
41
+ const raw = candidate.rawDocument;
42
+ if (raw === void 0) throw new Error("The candidate settings document is unavailable");
43
+ return withFileMutationQueue(options.settingsPath, async () => {
44
+ if (!commitOwnerCurrent(options, owner, expected)) return "cancel";
45
+ checkCandidate?.();
46
+ assertConfigDocumentUnchanged(options.settingsPath, expected.disk);
47
+ const previousBytes = expected.disk.rawBytes;
48
+ if (expected.previous.rawDocument !== previousBytes?.toString("utf8")) {
49
+ throw new Error(
50
+ "The active file differs from the loaded document. Reload and review it before replacing settings."
51
+ );
52
+ }
53
+ const invalid = expected.previous.diagnostics.some((item) => item.severity === "error");
54
+ if (invalid && !allowInvalid)
55
+ throw new Error("The active settings document is invalid. Use explicit repair or recovery before replacing it.");
56
+ validateConfigDocument(options.settingsPath, raw);
57
+ if (previousBytes?.equals(Buffer.from(raw))) return "applied";
58
+ let recoveryPath;
59
+ if (previousBytes !== void 0) {
60
+ recoveryPath = (options.archive ?? archiveConfigDocument)(options.settingsPath, previousBytes).path;
61
+ }
62
+ try {
63
+ assertConfigDocumentUnchanged(options.settingsPath, expected.disk);
64
+ if (!commitOwnerCurrent(options, owner, expected)) return "cancel";
65
+ checkCandidate?.();
66
+ } catch (error) {
67
+ throw new Error(`${message(error)}.${recoveryNote(recoveryPath)}`);
68
+ }
69
+ let saved;
70
+ try {
71
+ saved = options.save ? options.save(options.settingsPath, raw) : atomicSaveConfigDocument(options.settingsPath, raw, {}, expected.disk);
72
+ } catch (error) {
73
+ if (error instanceof ConfigPublicationError) {
74
+ const rollback = restorePrevious(ctx, options, owner, expected, raw, error.fileIdentity, false);
75
+ throw new Error(`Footer settings were not saved: ${message(error)}. ${rollback}${recoveryNote(recoveryPath)}`);
76
+ }
77
+ throw new Error(
78
+ `Footer settings were not saved: ${message(error)}. The previous footer remains active.${recoveryNote(recoveryPath)}`
79
+ );
80
+ }
81
+ try {
82
+ if (owner.signal.aborted || !(owner.isSessionCurrent?.() ?? owner.isCurrent()) || options.getLoadedRevision?.() !== expected.revision) {
83
+ throw new Error("The configuration owner changed during publication");
84
+ }
85
+ options.apply(saved, ctx);
86
+ } catch (error) {
87
+ const rollback = restorePrevious(ctx, options, owner, expected, raw, saved.fileIdentity, true);
88
+ throw new Error(
89
+ `Footer settings could not be applied: ${message(error)}. ${rollback}${recoveryNote(recoveryPath)}`
90
+ );
91
+ }
92
+ return "applied";
93
+ });
94
+ }
95
+ function restorePrevious(ctx, options, owner, expected, raw, identity, restoreRuntime) {
96
+ try {
97
+ if (owner.signal.aborted || !(owner.isSessionCurrent?.() ?? owner.isCurrent()))
98
+ throw new Error("The session owner changed; stale restoration was blocked");
99
+ const current2 = options.getLoaded();
100
+ if (current2.rawDocument !== expected.previous.rawDocument && current2.rawDocument !== raw) {
101
+ throw new Error("The active runtime changed; stale restoration was blocked");
102
+ }
103
+ if (!identity) throw new Error("The saved settings document identity is unavailable");
104
+ assertConfigDocumentUnchanged(options.settingsPath, { rawBytes: Buffer.from(raw), fileIdentity: identity });
105
+ if (expected.disk.rawBytes === void 0) {
106
+ removeConfigDocumentIfMatches(options.settingsPath, raw, identity);
107
+ } else if (options.restore && expected.disk.rawBytes.equals(Buffer.from(expected.previous.rawDocument ?? ""))) {
108
+ options.restore(options.settingsPath, expected.previous.rawDocument ?? "");
109
+ } else {
110
+ atomicRestoreConfigDocument(
111
+ options.settingsPath,
112
+ expected.disk.rawBytes,
113
+ {},
114
+ { rawBytes: Buffer.from(raw), fileIdentity: identity }
115
+ );
116
+ }
117
+ if (restoreRuntime) options.apply(expected.previous, ctx);
118
+ return "The previous configuration was restored.";
119
+ } catch (error) {
120
+ return `Restoring the previous configuration also failed: ${message(error)}. Active path: ${options.settingsPath}.`;
121
+ }
122
+ }
123
+ function recoveryNote(path) {
124
+ return path ? ` Recovery copy retained: ${path}.` : "";
125
+ }
126
+ function message(error) {
127
+ return error instanceof Error ? error.message : String(error);
128
+ }
129
+
130
+ // src/command-profiles.ts
131
+ import { isKeyRelease, Key, matchesKey } from "@earendil-works/pi-tui";
132
+ import { defineMenu, runLiveChoice, runMenu } from "@narumitw/pi-tui-kit";
133
+ import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
134
+ var PREVIEW_NOTICE = "Preview uses the current runtime snapshot only; unavailable module data can be empty.";
135
+ var SAVE_CURRENT = "save-current";
136
+ var FlowEnded = class extends Error {
137
+ };
138
+ async function showProfiles(ctx, options, owner, applyCandidate) {
139
+ return browseDocuments(ctx, options, owner, applyCandidate, "profile");
140
+ }
141
+ async function showHistory(ctx, options, owner, applyCandidate) {
142
+ return browseDocuments(ctx, options, owner, applyCandidate, "history");
143
+ }
144
+ async function saveAsProfile(ctx, options, owner, raw) {
145
+ if (!interactive(ctx) || !current(owner)) return void 0;
146
+ const flow = createFlow(ctx, options, owner);
147
+ try {
148
+ candidateFor(options, raw, true);
149
+ const saved = await saveNamedCopy(ctx, options, flow, raw);
150
+ flow.ensure();
151
+ return saved;
152
+ } catch (error) {
153
+ if (flow.signal.aborted || !flow.sessionCurrent()) return "close";
154
+ report(ctx, flow, error);
155
+ return void 0;
156
+ } finally {
157
+ flow.dispose();
158
+ }
159
+ }
160
+ async function browseDocuments(ctx, options, owner, applyCandidate, kind) {
161
+ if (!interactive(ctx) || !current(owner)) return "close";
162
+ const flow = createFlow(ctx, options, owner);
163
+ let selectedId;
164
+ try {
165
+ while (flow.current()) {
166
+ let interacted = false;
167
+ try {
168
+ const documents = kind === "profile" ? listProfiles(options.settingsPath) : listHistory(options.settingsPath);
169
+ const active = options.getLoaded();
170
+ const matches = documents.filter(
171
+ (document2) => document2.rawDocument !== void 0 && document2.rawDocument === active.rawDocument
172
+ );
173
+ const candidates = new Map(
174
+ documents.map((document2) => [documentId(document2), candidateFor(options, document2.rawDocument)])
175
+ );
176
+ const selection = await runLiveChoice(ctx, {
177
+ title: kind === "profile" ? "Profiles" : "History",
178
+ lines: [
179
+ 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",
180
+ ...kind === "profile" && matches.length === 0 ? ["Current settings are not saved as a profile"] : [],
181
+ PREVIEW_NOTICE
182
+ ],
183
+ items: [
184
+ ...kind === "profile" ? [
185
+ {
186
+ id: SAVE_CURRENT,
187
+ label: "Save current as\u2026",
188
+ description: "Copy exact loaded TOML; keep active settings unchanged"
189
+ }
190
+ ] : [],
191
+ ...documents.map((document2) => ({
192
+ id: documentId(document2),
193
+ label: safe(document2.name),
194
+ description: [
195
+ ...document2.kind === "history" ? [safe(document2.createdAt), ...document2.legacy ? ["Legacy \xB7 read-only"] : []] : [],
196
+ ...document2.rawDocument !== void 0 && document2.rawDocument === active.rawDocument ? ["Matches active settings"] : [],
197
+ ...!candidates.get(documentId(document2))?.loaded ? ["Invalid document \xB7 review or repair"] : []
198
+ ].join(" \xB7 "),
199
+ details: [
200
+ `Selected: ${safe(document2.name)}`,
201
+ `Path: ${safe(document2.path)}`,
202
+ ...candidates.get(documentId(document2))?.lines ?? []
203
+ ]
204
+ }))
205
+ ],
206
+ initialItemId: selectedId,
207
+ enableSearch: true,
208
+ viewportSize: 10,
209
+ hint: "back",
210
+ confirmLabel: "actions",
211
+ navigationLabel: "live preview",
212
+ signal: flow.signal,
213
+ isCurrent: flow.current,
214
+ onSelectionChange: ({ item, signal }) => {
215
+ if (signal.aborted || !flow.current()) return;
216
+ selectedId = item.id;
217
+ flow.preview(candidates.get(item.id)?.loaded);
218
+ }
219
+ });
220
+ flow.ensure();
221
+ interacted = true;
222
+ if (selection.kind !== "selected") {
223
+ return selection.kind === "closed" && selection.reason === "back" ? "back" : "close";
224
+ }
225
+ selectedId = selection.itemId;
226
+ if (selectedId === SAVE_CURRENT) {
227
+ flow.preview(void 0);
228
+ const loaded = options.getLoaded();
229
+ if (loaded.diagnostics.some((item) => item.severity === "error")) {
230
+ throw new Error(
231
+ "Cannot save unreadable or malformed active settings as a profile. Repair the settings document first."
232
+ );
233
+ }
234
+ const raw = loaded.rawDocument ?? BUILT_IN_EXAMPLE;
235
+ candidateFor(options, raw, true);
236
+ const saved = await saveNamedCopy(ctx, options, flow, raw);
237
+ flow.ensure();
238
+ if (saved) selectedId = documentId(saved);
239
+ continue;
240
+ }
241
+ const document = documents.find((item) => documentId(item) === selectedId);
242
+ if (!document) continue;
243
+ flow.ensure(document);
244
+ const outcome = await documentActions(ctx, options, flow, document, applyCandidate);
245
+ flow.ensure();
246
+ if (outcome === "close") return "close";
247
+ if (outcome) selectedId = documentId(outcome);
248
+ } catch (error) {
249
+ if (error instanceof FlowEnded || !flow.current()) return "close";
250
+ flow.preview(void 0);
251
+ report(ctx, flow, error);
252
+ if (!interacted) return "close";
253
+ }
254
+ }
255
+ return "close";
256
+ } finally {
257
+ flow.dispose();
258
+ }
259
+ }
260
+ async function documentActions(ctx, options, flow, document, applyCandidate) {
261
+ const candidate = candidateFor(options, document.rawDocument);
262
+ const profile = document.kind === "profile";
263
+ const activeInvalid = profile && options.getLoaded().diagnostics.some((item) => item.severity === "error");
264
+ const action = await actionScreen(ctx, flow, {
265
+ title: `${profile ? "Profile" : "Recovery copy"}: ${safe(document.name)}`,
266
+ lines: [
267
+ `Path: ${safe(document.path)}`,
268
+ ...document.kind === "history" ? [`Recovery time: ${safe(document.createdAt)}`, "A recovery copy is not proof that an application succeeded."] : [],
269
+ ...document.kind === "history" && document.legacy ? ["Legacy backup \xB7 read-only; restore copies bytes without changing this backup."] : [],
270
+ ...document.readError ? [safe(document.readError)] : [],
271
+ ...candidate.lines,
272
+ PREVIEW_NOTICE
273
+ ],
274
+ raw: document.rawDocument,
275
+ actions: [
276
+ {
277
+ id: "apply",
278
+ label: profile ? "Apply\u2026" : "Restore\u2026",
279
+ disabled: !candidate.loaded || activeInvalid,
280
+ disabledReason: activeInvalid ? "Repair active settings or use explicit recovery first" : "Invalid TOML cannot be applied"
281
+ },
282
+ ...profile ? [
283
+ { id: "edit", label: "Edit TOML\u2026" },
284
+ { id: "rename", label: "Rename\u2026" },
285
+ { id: "duplicate", label: "Duplicate\u2026" }
286
+ ] : [
287
+ {
288
+ id: "save-as",
289
+ label: "Save as a profile\u2026",
290
+ disabled: !candidate.loaded,
291
+ disabledReason: "Invalid TOML cannot be saved as a validated profile"
292
+ }
293
+ ],
294
+ {
295
+ id: "delete",
296
+ label: "Delete\u2026",
297
+ disabled: document.kind === "history" && document.legacy,
298
+ disabledReason: "Legacy backups are read-only"
299
+ }
300
+ ]
301
+ });
302
+ flow.ensure(document);
303
+ if (action === "close") return "close";
304
+ if (action === "back") return void 0;
305
+ if (action === "apply" && candidate.loaded) {
306
+ const result = await applyReviewedCandidate(flow, candidate.loaded, applyCandidate, document);
307
+ flow.ensure(document);
308
+ return result === "close" ? "close" : document;
309
+ }
310
+ if (action === "edit" && profile) {
311
+ const result = await editProfile(ctx, options, flow, document, applyCandidate);
312
+ flow.ensure();
313
+ return result;
314
+ }
315
+ if (action === "rename" && profile) {
316
+ const name = await flow.dialog(
317
+ () => ctx.ui.input(`Rename profile: ${safe(document.name)}`, "New profile name", { signal: flow.signal })
318
+ );
319
+ flow.ensure(document);
320
+ if (name === void 0) return document;
321
+ return renameProfile(options.settingsPath, document.name, name, document);
322
+ }
323
+ if (action === "duplicate" || action === "save-as" && document.rawDocument !== void 0) {
324
+ const saved = await saveNamedCopy(ctx, options, flow, document.rawDocument, document);
325
+ flow.ensure(document);
326
+ return action === "duplicate" || document.kind === "history" ? document : saved ?? document;
327
+ }
328
+ if (action === "delete" && !(document.kind === "history" && document.legacy)) {
329
+ const confirmed = await flow.dialog(
330
+ () => ctx.ui.confirm(
331
+ `Delete ${profile ? "profile" : "recovery copy"}: ${safe(document.name)}?`,
332
+ `Path: ${safe(document.path)}
333
+ ${profile ? "This deletes only the saved profile. The active settings copy remains unchanged." : "This permanently deletes only this recovery copy. Active settings remain unchanged."}`,
334
+ { signal: flow.signal }
335
+ )
336
+ );
337
+ flow.ensure(document);
338
+ if (confirmed) {
339
+ if (document.kind === "profile") deleteProfile(options.settingsPath, document.name, document);
340
+ else deleteHistory(options.settingsPath, document.name, document);
341
+ }
342
+ }
343
+ return void 0;
344
+ }
345
+ async function editProfile(ctx, options, flow, original, applyCandidate) {
346
+ let draft = original.rawDocument ?? "";
347
+ if (original.rawDocument === void 0) {
348
+ const repair = await flow.dialog(
349
+ () => ctx.ui.confirm(
350
+ `Repair invalid UTF-8 profile: ${safe(original.name)}?`,
351
+ `Path: ${safe(original.path)}
352
+ 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.`,
353
+ { signal: flow.signal }
354
+ )
355
+ );
356
+ flow.ensure(original);
357
+ if (!repair) return original;
358
+ }
359
+ while (flow.current()) {
360
+ const edited = await flow.dialog(() => ctx.ui.editor(`Edit profile: ${safe(original.name)}`, draft));
361
+ flow.ensure(original);
362
+ if (edited === void 0) return original;
363
+ draft = edited;
364
+ const candidate = candidateFor(options, draft);
365
+ flow.preview(candidate.loaded);
366
+ const action = await actionScreen(ctx, flow, {
367
+ title: candidate.loaded ? "Profile draft preview" : "Profile draft needs attention",
368
+ lines: [
369
+ "Save profile changes only the saved copy, even when it matches active settings.",
370
+ ...candidate.lines,
371
+ PREVIEW_NOTICE
372
+ ],
373
+ raw: draft,
374
+ actions: [
375
+ {
376
+ id: "save",
377
+ label: "Save profile",
378
+ disabled: !candidate.loaded,
379
+ disabledReason: "Repair the draft before saving"
380
+ },
381
+ {
382
+ id: "save-apply",
383
+ label: "Save profile and apply\u2026",
384
+ description: "Two operations: a failed apply retains the saved profile",
385
+ disabled: !candidate.loaded,
386
+ disabledReason: "Repair the draft before saving"
387
+ },
388
+ { id: "continue", label: "Continue editing" },
389
+ { id: "discard", label: "Discard draft" }
390
+ ]
391
+ });
392
+ flow.ensure(original);
393
+ if (action === "close") return "close";
394
+ if (action === "discard") return original;
395
+ if (action === "continue" || action === "back") continue;
396
+ if (!candidate.loaded || action !== "save" && action !== "save-apply") continue;
397
+ const saved = saveProfile(options.settingsPath, original.name, draft, original);
398
+ ctx.ui.notify(`Profile saved: ${safe(saved.name)}. Active settings are unchanged.`, "info");
399
+ if (action === "save-apply") {
400
+ try {
401
+ const result = await applyReviewedCandidate(flow, candidate.loaded, applyCandidate, saved);
402
+ flow.ensure(saved);
403
+ if (result === "close") return "close";
404
+ if (result !== "applied")
405
+ ctx.ui.notify(
406
+ "The profile was saved. Application did not complete; review the configuration result before retrying.",
407
+ "warning"
408
+ );
409
+ } catch (error) {
410
+ if (!flow.current()) throw error;
411
+ ctx.ui.notify(
412
+ `The saved profile was retained, but application did not complete: ${safeError(error)}. Review active settings before retrying.`,
413
+ "error"
414
+ );
415
+ }
416
+ }
417
+ return saved;
418
+ }
419
+ throw new FlowEnded();
420
+ }
421
+ async function applyReviewedCandidate(flow, loaded, applyCandidate, document) {
422
+ flow.ensure(document);
423
+ const result = await applyCandidate(
424
+ loaded,
425
+ {
426
+ signal: flow.signal,
427
+ // The shared commit policy captures the active revision before applying.
428
+ // A successful apply changes it; session ownership must remain valid after it.
429
+ isCurrent: () => !flow.signal.aborted && flow.sessionCurrent(),
430
+ isSessionCurrent: flow.sessionCurrent
431
+ },
432
+ () => flow.ensure(document),
433
+ document.name
434
+ );
435
+ if (result === "applied") flow.adoptAppliedRevision();
436
+ flow.ensure(document);
437
+ flow.preview(void 0);
438
+ return result;
439
+ }
440
+ async function saveNamedCopy(ctx, options, flow, raw, source) {
441
+ while (flow.current()) {
442
+ const name = await flow.dialog(
443
+ () => ctx.ui.input("Save as a profile", "Profile name (without .toml)", { signal: flow.signal })
444
+ );
445
+ flow.ensure(source);
446
+ if (name === void 0) return void 0;
447
+ try {
448
+ const saved = source?.kind === "profile" ? duplicateProfile(options.settingsPath, source.name, name, source) : createProfile(options.settingsPath, name, requireText(raw));
449
+ ctx.ui.notify(`Profile saved: ${safe(saved.name)}. Active settings are unchanged.`, "info");
450
+ return saved;
451
+ } catch (error) {
452
+ report(ctx, flow, error);
453
+ }
454
+ }
455
+ throw new FlowEnded();
456
+ }
457
+ async function actionScreen(ctx, flow, screen) {
458
+ let selected;
459
+ const menu = defineMenu({
460
+ start: "actions",
461
+ screens: {
462
+ actions: () => ({
463
+ kind: "actions",
464
+ title: screen.title,
465
+ lines: screen.lines,
466
+ items: [
467
+ {
468
+ id: "review",
469
+ label: "Review TOML",
470
+ to: "document",
471
+ disabled: screen.raw === void 0,
472
+ disabledReason: "The document is not valid UTF-8"
473
+ },
474
+ ...screen.actions.map((action) => ({ ...action, action: "select" }))
475
+ ],
476
+ hint: "back"
477
+ }),
478
+ document: () => ({
479
+ kind: "review",
480
+ title: screen.title,
481
+ lines: ["Exact UTF-8 text \xB7 display controls sanitized \xB7 read-only"],
482
+ content: screen.raw ?? "The document is not valid UTF-8; no decoded fallback is shown.",
483
+ format: { kind: "code", language: "toml" },
484
+ enableSearch: true,
485
+ viewportSize: "adaptive",
486
+ hint: "back"
487
+ })
488
+ },
489
+ actions: {
490
+ select: ({ itemId }) => {
491
+ flow.ensure();
492
+ selected = itemId;
493
+ return { kind: "close" };
494
+ }
495
+ }
496
+ });
497
+ const result = await runMenu(ctx, menu, { getState: () => void 0, signal: flow.signal, isCurrent: flow.current });
498
+ flow.ensure();
499
+ return selected ?? (result.kind === "closed" && result.reason === "back" ? "back" : "close");
500
+ }
501
+ function createFlow(ctx, options, owner) {
502
+ const controller = new AbortController();
503
+ const signal = AbortSignal.any([controller.signal, owner.signal]);
504
+ let revision = options.getLoadedRevision?.();
505
+ let activeDocument = activeFingerprint(options.getLoaded());
506
+ let previewOwned = false;
507
+ const isCurrent = () => !signal.aborted && owner.isCurrent() && (revision === void 0 ? activeFingerprint(options.getLoaded()) === activeDocument : options.getLoadedRevision?.() === revision);
508
+ const clearPreview = () => {
509
+ if (!previewOwned) return;
510
+ previewOwned = false;
511
+ if (owner.isSessionCurrent?.() ?? owner.isCurrent()) {
512
+ try {
513
+ options.preview?.(void 0, ctx);
514
+ } catch (error) {
515
+ ctx.ui.notify(`Could not clear the footer preview: ${safeError(error)}`, "error");
516
+ }
517
+ }
518
+ };
519
+ const matches = (expected) => {
520
+ if (!isCurrent()) return false;
521
+ if (!expected) return true;
522
+ try {
523
+ const fresh = expected.kind === "profile" ? readProfile(options.settingsPath, expected.name) : readHistory(options.settingsPath, expected.name);
524
+ 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);
525
+ } catch {
526
+ return false;
527
+ }
528
+ };
529
+ const ensure = (expected) => {
530
+ if (!isCurrent()) throw new FlowEnded();
531
+ if (!matches(expected))
532
+ throw new Error("The selected document changed or was removed. Review the latest copy before trying again.");
533
+ };
534
+ signal.addEventListener("abort", clearPreview, { once: true });
535
+ return {
536
+ signal,
537
+ current: isCurrent,
538
+ sessionCurrent: () => owner.isSessionCurrent?.() ?? owner.isCurrent(),
539
+ ensure,
540
+ preview(loaded) {
541
+ ensure();
542
+ if (!loaded) {
543
+ clearPreview();
544
+ return;
545
+ }
546
+ previewOwned = true;
547
+ try {
548
+ options.preview?.(loaded, ctx);
549
+ } catch (error) {
550
+ clearPreview();
551
+ throw error;
552
+ }
553
+ },
554
+ async dialog(run) {
555
+ ensure();
556
+ const unsubscribe = ctx.ui.onTerminalInput((data) => {
557
+ if (!isKeyRelease(data) && matchesKey(data, Key.ctrl("c"))) {
558
+ queueMicrotask(() => controller.abort());
559
+ }
560
+ return void 0;
561
+ });
562
+ let released = false;
563
+ const release = () => {
564
+ if (released) return;
565
+ released = true;
566
+ unsubscribe();
567
+ };
568
+ signal.addEventListener("abort", release, { once: true });
569
+ try {
570
+ if (signal.aborted) release();
571
+ ensure();
572
+ const result = await run();
573
+ ensure();
574
+ return result;
575
+ } finally {
576
+ signal.removeEventListener("abort", release);
577
+ release();
578
+ }
579
+ },
580
+ adoptAppliedRevision() {
581
+ if (signal.aborted || !(owner.isSessionCurrent?.() ?? owner.isCurrent())) throw new FlowEnded();
582
+ revision = options.getLoadedRevision?.();
583
+ activeDocument = activeFingerprint(options.getLoaded());
584
+ },
585
+ dispose() {
586
+ try {
587
+ clearPreview();
588
+ } finally {
589
+ signal.removeEventListener("abort", clearPreview);
590
+ controller.abort();
591
+ }
592
+ }
593
+ };
594
+ }
595
+ function candidateFor(options, raw, required = false) {
596
+ try {
597
+ if (raw === void 0) throw new Error("The document is not valid UTF-8; no decoded fallback is shown.");
598
+ const loaded = (options.validate ?? validateConfigDocument)(options.settingsPath, raw);
599
+ if (loaded.diagnostics.some((item) => item.severity === "error"))
600
+ throw new Error(loaded.diagnostics.map((item) => item.message).join("; "));
601
+ return {
602
+ loaded,
603
+ lines: loaded.diagnostics.length === 0 ? ["No configuration warnings."] : loaded.diagnostics.map((item) => `${safe(item.path || "root")}: ${safe(item.message)}`)
604
+ };
605
+ } catch (error) {
606
+ if (required) throw error;
607
+ return { lines: [`Invalid TOML: ${safeError(error)}`, "No candidate footer preview is shown."] };
608
+ }
609
+ }
610
+ function requireText(raw) {
611
+ if (raw === void 0) throw new Error("The document is not valid UTF-8; no decoded fallback can be saved.");
612
+ return raw;
613
+ }
614
+ function activeFingerprint(loaded) {
615
+ return JSON.stringify([loaded.source, loaded.rawDocument, loaded.diagnostics]);
616
+ }
617
+ function current(owner) {
618
+ return !owner.signal.aborted && owner.isCurrent();
619
+ }
620
+ function interactive(ctx) {
621
+ if (ctx.mode === "tui" && ctx.hasUI) return true;
622
+ if (ctx.hasUI) ctx.ui.notify("Profiles and History require TUI mode.", "info");
623
+ return false;
624
+ }
625
+ function documentId(document) {
626
+ return `${document.kind}:${document.name}`;
627
+ }
628
+ function report(ctx, flow, error) {
629
+ if (!(error instanceof FlowEnded) && flow.current()) ctx.ui.notify(safeError(error), "error");
630
+ }
631
+ function safeError(error) {
632
+ return safe(error instanceof Error ? error.message : String(error));
633
+ }
634
+ function safe(value) {
635
+ return sanitizeTerminalText(value);
636
+ }
637
+
638
+ export {
639
+ captureCommitExpectation,
640
+ commitOwnerCurrent,
641
+ commitActiveDocument,
642
+ showProfiles,
643
+ showHistory,
644
+ saveAsProfile
645
+ };
646
+ //# sourceMappingURL=chunk-HPZTMIZS.ts.map