@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
@@ -0,0 +1,155 @@
1
+ import { stripVTControlCharacters } from "node:util";
2
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
3
+ import { isKeyRelease, Key, matchesKey, SelectList } from "@earendil-works/pi-tui";
4
+ import {
5
+ formatInteractionHints,
6
+ HorizontalRule,
7
+ hardWrapTerminalDocument,
8
+ renderBoundedFrameLayout,
9
+ runCustomInteraction,
10
+ } from "@narumitw/pi-tui-kit";
11
+ import {
12
+ type ConfigurationCommandOptions,
13
+ configurationMenuScreen,
14
+ type WorkflowOwner,
15
+ } from "./command-configuration.js";
16
+
17
+ type ConfigurationAction = ReturnType<typeof configurationMenuScreen>["items"][number]["action"];
18
+
19
+ /** Kit action headers do not scroll. Keep this extension-owned summary viewport above a native SelectList. */
20
+ export function showConfigurationMenu(
21
+ ctx: ExtensionCommandContext,
22
+ options: ConfigurationCommandOptions,
23
+ owner: WorkflowOwner,
24
+ selected?: string,
25
+ ) {
26
+ return runCustomInteraction<ConfigurationAction | "back" | "close">(ctx, {
27
+ signal: owner.signal,
28
+ isCurrent: owner.isCurrent,
29
+ create: ({ tui, theme, keybindings, complete }) => {
30
+ const screen = configurationMenuScreen(options.getLoaded(), options.settingsPath);
31
+ const list = new SelectList(
32
+ screen.items.map((item) => ({ value: item.action, label: item.label, description: item.description })),
33
+ 4,
34
+ {
35
+ selectedPrefix: (text) => theme.fg("accent", text),
36
+ selectedText: (text) => theme.fg("accent", text),
37
+ description: (text) => theme.fg("muted", text),
38
+ scrollInfo: (text) => theme.fg("muted", text),
39
+ noMatch: (text) => theme.fg("muted", text),
40
+ },
41
+ );
42
+ let index = Math.max(
43
+ 0,
44
+ screen.items.findIndex((item) => item.action === selected),
45
+ );
46
+ list.setSelectedIndex(index);
47
+ let offset = 0;
48
+ let pageSize = 1;
49
+ let lastOffset = 0;
50
+ let disposed = false;
51
+ let layout: ReturnType<typeof renderBoundedFrameLayout> | undefined;
52
+ let listStart = 0;
53
+ let lastWidth = 0;
54
+ const rule = new HorizontalRule({ ruleStyle: (text) => theme.fg("border", text) });
55
+ const scroll = (direction: number) => {
56
+ offset = Math.max(0, Math.min(lastOffset, offset + direction * pageSize));
57
+ tui.requestRender();
58
+ };
59
+ return {
60
+ render(width) {
61
+ if (disposed) return [];
62
+ lastWidth = width;
63
+ const rows = Number.isFinite(tui.terminal.rows) ? Math.floor(tui.terminal.rows) : 24;
64
+ const maxRows = Math.max(1, rows - 3);
65
+ const summary = hardWrapTerminalDocument(screen.lines.join("\n"), width);
66
+ const listRows = list.render(width);
67
+ const description = screen.items[index]?.description;
68
+ const details =
69
+ description && !listRows.some((line) => stripVTControlCharacters(line).includes(description))
70
+ ? hardWrapTerminalDocument(description, width).map((line) => theme.fg("muted", line))
71
+ : [];
72
+ pageSize = Math.max(1, maxRows - 11 - (details.length ? details.length + 1 : 0));
73
+ lastOffset = Math.max(0, summary.length - pageSize);
74
+ offset = Math.min(offset, lastOffset);
75
+ const visibleSummary = summary.slice(offset, offset + pageSize).map((line) => theme.fg("muted", line));
76
+ const status =
77
+ lastOffset > 0
78
+ ? [
79
+ theme.fg(
80
+ "muted",
81
+ `Summary ${offset + 1}-${Math.min(summary.length, offset + pageSize)}/${summary.length} · Page navigation scrolls summary`,
82
+ ),
83
+ ]
84
+ : [];
85
+ listStart = visibleSummary.length + status.length + 1;
86
+ const detailStart = listStart + listRows.length + 1;
87
+ const content = [...visibleSummary, ...status, "", ...listRows, ...(details.length ? ["", ...details] : [])];
88
+ const hints = formatInteractionHints(keybindings, [
89
+ { bindings: ["tui.select.up", "tui.select.down"], label: "navigate" },
90
+ { bindings: ["tui.select.confirm"], label: "select" },
91
+ { bindings: ["tui.select.cancel"], label: "back" },
92
+ ]);
93
+ layout = renderBoundedFrameLayout({
94
+ width,
95
+ maxRows,
96
+ rule: rule.render(width)[0] ?? "",
97
+ title: [theme.fg("accent", theme.bold(screen.title))],
98
+ content,
99
+ hints: [theme.fg("muted", `${hints} • ctrl+c close`)],
100
+ compactHint: "",
101
+ focusedRow: listStart + index,
102
+ priorityRows: [listStart + index, ...details.map((_, index) => detailStart + index)],
103
+ });
104
+ return layout.lines;
105
+ },
106
+ invalidate() {
107
+ layout = undefined;
108
+ list.invalidate();
109
+ },
110
+ handleInput(data) {
111
+ if (disposed || isKeyRelease(data)) return;
112
+ // Standard selection and cancellation take priority over summary scrolling.
113
+ if (matchesKey(data, Key.ctrl("c"))) complete("close");
114
+ else if (keybindings.matches(data, "tui.select.cancel")) complete("back");
115
+ else if (keybindings.matches(data, "tui.select.up")) {
116
+ index = (index + screen.items.length - 1) % screen.items.length;
117
+ list.setSelectedIndex(index);
118
+ } else if (keybindings.matches(data, "tui.select.down")) {
119
+ index = (index + 1) % screen.items.length;
120
+ list.setSelectedIndex(index);
121
+ } else if (matchesKey(data, Key.home)) {
122
+ index = 0;
123
+ list.setSelectedIndex(index);
124
+ } else if (matchesKey(data, Key.end)) {
125
+ index = screen.items.length - 1;
126
+ list.setSelectedIndex(index);
127
+ } else if (keybindings.matches(data, "tui.select.confirm")) {
128
+ const item = screen.items[index];
129
+ if (item) complete(item.action);
130
+ } else if (keybindings.matches(data, "tui.select.pageUp")) scroll(-1);
131
+ else if (keybindings.matches(data, "tui.select.pageDown")) scroll(1);
132
+ tui.requestRender();
133
+ },
134
+ handleMouse(event) {
135
+ if (disposed || !layout || event.width !== lastWidth) return undefined;
136
+ const row = layout.contentRows.find((row) => row.frameIndex === event.y)?.contentIndex;
137
+ if (row === undefined) return undefined;
138
+ if (row < listStart) {
139
+ if (event.type !== "wheel" || !event.wheelDelta) return undefined;
140
+ scroll(event.wheelDelta < 0 ? -1 : 1);
141
+ return { handled: true, render: true };
142
+ }
143
+ const result = list.handleMouse({ ...event, y: row - listStart });
144
+ index = screen.items.findIndex((item) => item.action === list.getSelectedItem()?.value);
145
+ const item = screen.items[index];
146
+ if (event.type === "click" && result?.handled && item) complete(item.action);
147
+ return result;
148
+ },
149
+ dispose() {
150
+ disposed = true;
151
+ },
152
+ };
153
+ },
154
+ });
155
+ }
@@ -9,7 +9,6 @@ import {
9
9
  loadStarshipConfig,
10
10
  readConfigDocumentSnapshot,
11
11
  } from "./config.js";
12
- import { serializeEffectiveConfig } from "./effective-config.js";
13
12
  import { presetForDocument } from "./presets/catalog.js";
14
13
  import { archiveConfigDocument } from "./profile-store.js";
15
14
 
@@ -77,33 +76,18 @@ export function configurationPresentation(loaded: LoadedStarshipConfig): Configu
77
76
  };
78
77
  }
79
78
 
80
- export function configurationMenuScreen(loaded: LoadedStarshipConfig) {
79
+ export function configurationMenuScreen(loaded: LoadedStarshipConfig, settingsPath: string) {
81
80
  const presentation = configurationPresentation(loaded);
82
81
  return {
83
82
  kind: "actions" as const,
84
83
  title: "Configuration",
85
- lines: [`${presentation.state} · ${presentation.health}`],
84
+ lines: [
85
+ `State: ${presentation.state}`,
86
+ `Source: ${presentation.source}`,
87
+ `Path: ${sanitizeTerminalText(settingsPath)}`,
88
+ ...diagnosticLines(loaded, true, loaded.diagnostics.length),
89
+ ],
86
90
  items: [
87
- {
88
- id: "configuration-overview",
89
- label: "Overview",
90
- description: "State, source, path, health, and warnings",
91
- to: "configuration-overview" as const,
92
- },
93
- {
94
- id: "configuration-effective",
95
- label: "Effective configuration",
96
- description: "Normalized public TOML currently in use",
97
- to: "configuration-effective" as const,
98
- },
99
- {
100
- id: "configuration-document",
101
- label: "Settings document",
102
- description: isHealthyMissing(loaded)
103
- ? "No settings file · built-in defaults are active"
104
- : "Exact loaded UTF-8 text · read-only",
105
- to: "configuration-document" as const,
106
- },
107
91
  {
108
92
  id: "configuration-reload",
109
93
  label: "Reload from disk…",
@@ -133,65 +117,6 @@ export function configurationMenuScreen(loaded: LoadedStarshipConfig) {
133
117
  };
134
118
  }
135
119
 
136
- export function configurationOverviewScreen(loaded: LoadedStarshipConfig, settingsPath: string) {
137
- const presentation = configurationPresentation(loaded);
138
- return {
139
- kind: "detail" as const,
140
- title: "Configuration overview",
141
- lines: [
142
- `State: ${presentation.state}`,
143
- `Source: ${presentation.source}`,
144
- `Path: ${sanitizeTerminalText(settingsPath)}`,
145
- ...diagnosticLines(loaded, true),
146
- ],
147
- hint: "back" as const,
148
- };
149
- }
150
-
151
- export function effectiveConfigurationScreen(loaded: LoadedStarshipConfig) {
152
- const presentation = configurationPresentation(loaded);
153
- return {
154
- kind: "review" as const,
155
- title: "Effective configuration",
156
- lines: [
157
- `${presentation.state} · ${presentation.health}`,
158
- "Normalized public TOML; comments and unknown fields are intentionally excluded.",
159
- ],
160
- content: serializeEffectiveConfig(loaded.config),
161
- enableSearch: true,
162
- format: { kind: "code" as const, language: "toml" },
163
- viewportSize: "adaptive" as const,
164
- hint: "back" as const,
165
- };
166
- }
167
-
168
- export function settingsDocumentScreen(loaded: LoadedStarshipConfig, settingsPath: string) {
169
- const path = sanitizeTerminalText(settingsPath);
170
- if (loaded.rawDocument !== undefined) {
171
- return {
172
- kind: "review" as const,
173
- title: "Settings document",
174
- lines: ["Exact loaded UTF-8 text · display controls sanitized · read-only", `Path: ${path}`],
175
- content: loaded.rawDocument,
176
- enableSearch: true,
177
- format: { kind: "code" as const, language: "toml" },
178
- viewportSize: "adaptive" as const,
179
- hint: "back" as const,
180
- };
181
- }
182
- return {
183
- kind: "detail" as const,
184
- title: "Settings document",
185
- lines: [
186
- ...(isHealthyMissing(loaded)
187
- ? ["No settings document exists.", "Built-in defaults are active; this read created no file."]
188
- : ["The settings document could not be loaded.", ...diagnosticLines(loaded, false)]),
189
- `Path: ${path}`,
190
- ],
191
- hint: "back" as const,
192
- };
193
- }
194
-
195
120
  export async function reloadConfiguration(
196
121
  ctx: ExtensionCommandContext,
197
122
  options: ConfigurationCommandOptions,
@@ -348,9 +273,9 @@ function reloadPreviewBody(
348
273
  ];
349
274
  }
350
275
 
351
- export function diagnosticLines(loaded: LoadedStarshipConfig, includeSummary: boolean): string[] {
276
+ export function diagnosticLines(loaded: LoadedStarshipConfig, includeSummary: boolean, limit = 8): string[] {
352
277
  const diagnostics = loaded.diagnostics
353
- .slice(0, 8)
278
+ .slice(0, limit)
354
279
  .map((item) => `${sanitizeTerminalText(item.path || "root")}: ${sanitizeTerminalText(item.message)}`);
355
280
  const remaining = loaded.diagnostics.length - diagnostics.length;
356
281
  return [
@@ -1,5 +1,5 @@
1
1
  import { stripVTControlCharacters } from "node:util";
2
- import type { ExtensionCommandContext, KeybindingsManager } from "@earendil-works/pi-coding-agent";
2
+ import type { ExtensionCommandContext, KeybindingsManager, Theme } from "@earendil-works/pi-coding-agent";
3
3
  import { Key, matchesKey, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
4
4
  import { runCustomInteraction } from "@narumitw/pi-tui-kit";
5
5
 
@@ -18,7 +18,7 @@ export type PreviewMenuResult<Value extends string> =
18
18
  export async function showPreviewActionMenu<Value extends string>(
19
19
  ctx: ExtensionCommandContext,
20
20
  title: string,
21
- body: (width: number) => readonly string[],
21
+ body: (width: number, theme: Theme) => readonly string[],
22
22
  items: readonly PreviewMenuItem<Value>[],
23
23
  signal?: AbortSignal,
24
24
  isCurrent: () => boolean = () => !signal?.aborted,
@@ -52,7 +52,7 @@ export async function showPreviewActionMenu<Value extends string>(
52
52
  const safeWidth = Math.max(1, width);
53
53
  const terminalRows = Number.isFinite(tui.terminal.rows) ? Math.floor(tui.terminal.rows) : 24;
54
54
  const availableRows = Math.max(1, terminalRows - RESERVED_HOST_ROWS);
55
- const bodyLines = body(safeWidth).flatMap((line) => (line ? wrapTextWithAnsi(line, safeWidth) : [""]));
55
+ const bodyLines = body(safeWidth, theme).flatMap((line) => (line ? wrapTextWithAnsi(line, safeWidth) : [""]));
56
56
  const layout = allocateLayout(availableRows, items.length, bodyLines.length);
57
57
  lastViewportSize = layout.previewRows;
58
58
  lastMaximumScroll = Math.max(0, bodyLines.length - layout.previewRows);
@@ -0,0 +1,210 @@
1
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+ import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
3
+ import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
4
+ import { sanitizeTerminalDocument } from "@narumitw/pi-tui-kit/terminal-document";
5
+ import { captureCommitExpectation, commitActiveDocument, commitOwnerCurrent } from "./command-commit.js";
6
+ import type { WorkflowOwner } from "./command-configuration.js";
7
+ import { showPreviewActionMenu } from "./command-preview.js";
8
+ import { saveAsProfile } from "./command-profiles.js";
9
+ import type { StarshipCommandOptions } from "./commands.js";
10
+ import { assertProfileUnchanged } from "./profile-store.js";
11
+ import { createSettingsAgent, starshipPackageRoot } from "./settings-agent.js";
12
+ import {
13
+ type ChatViewState,
14
+ renderSettingsChatPreview,
15
+ settingsChatTranscript,
16
+ showSettingsChat,
17
+ } from "./settings-chat-ui.js";
18
+ import { createSettingsDraft } from "./settings-draft.js";
19
+ import { settingsSnapshots } from "./settings-snapshots.js";
20
+
21
+ export async function showSettingsAgentChat(
22
+ ctx: ExtensionCommandContext,
23
+ options: StarshipCommandOptions,
24
+ base: WorkflowOwner,
25
+ ): Promise<"applied" | "close"> {
26
+ if (ctx.mode !== "tui" || base.signal.aborted || !base.isCurrent()) return "close";
27
+ const expected = await withFileMutationQueue(options.settingsPath, async () => {
28
+ if (base.signal.aborted || !base.isCurrent()) return undefined;
29
+ return captureCommitExpectation(options);
30
+ });
31
+ if (!expected || base.signal.aborted || !base.isCurrent()) return "close";
32
+ const owner: WorkflowOwner = {
33
+ signal: base.signal,
34
+ isCurrent: () => commitOwnerCurrent(options, base, expected),
35
+ isSessionCurrent: base.isSessionCurrent ?? base.isCurrent,
36
+ };
37
+ const packageRoot = starshipPackageRoot();
38
+ const draft = createSettingsDraft({
39
+ settingsPath: options.settingsPath,
40
+ baseline: expected.disk.rawBytes,
41
+ snapshots: settingsSnapshots(expected.previous, options.settingsPath, options.getInspection?.()),
42
+ packageRoot,
43
+ isCurrent: owner.isCurrent,
44
+ onPreview: (loaded) => {
45
+ if (owner.isCurrent()) options.preview?.(loaded, ctx);
46
+ },
47
+ });
48
+ let agent: ReturnType<typeof createSettingsAgent> | undefined;
49
+ let closing: Promise<void> | undefined;
50
+ const cleanup = () => {
51
+ if (closing) return closing;
52
+ agent?.abort();
53
+ closing = (async () => {
54
+ try {
55
+ await agent?.waitForIdle();
56
+ } finally {
57
+ agent?.reset();
58
+ draft.dispose();
59
+ }
60
+ })();
61
+ return closing;
62
+ };
63
+ const abort = () => {
64
+ agent?.abort();
65
+ };
66
+ const unregister = options.registerChatCleanup?.(cleanup);
67
+ owner.signal.addEventListener("abort", abort, { once: true });
68
+ const state: ChatViewState = { input: "", error: "" };
69
+ const preview = (width: number) => {
70
+ const candidate = draft.candidate;
71
+ return candidate
72
+ ? (options.renderPreview?.(candidate, width, ctx) ?? ["Footer preview unavailable"])
73
+ : ["Invalid draft; the last valid footer preview is retained."];
74
+ };
75
+ try {
76
+ if (!owner.isCurrent()) return "close";
77
+ agent = createSettingsAgent(ctx, draft, packageRoot);
78
+ while (owner.isCurrent()) {
79
+ const action = await showSettingsChat(ctx, agent, draft, state, owner, preview);
80
+ if (!owner.isCurrent() || action === "discard") return "close";
81
+ const result =
82
+ action === "save"
83
+ ? { kind: "selected" as const, value: "save" as const }
84
+ : await showPreviewActionMenu(
85
+ ctx,
86
+ "Configuration chat — preview only",
87
+ (width, theme) => [
88
+ "The agent has not changed the active settings file.",
89
+ "Preview uses cached data; enabling modules here does not run commands or network requests.",
90
+ ...renderSettingsChatPreview(width, preview(width), theme),
91
+ ...sanitizeTerminalDocument(draft.diagnostics).split("\n"),
92
+ ],
93
+ [
94
+ { value: "continue", label: "Continue conversation" },
95
+ { value: "document", label: "Review exact draft…" },
96
+ { value: "transcript", label: "Review full conversation…" },
97
+ ...(draft.candidate ? [{ value: "save" as const, label: "Save draft as profile…" }] : []),
98
+ { value: "discard", label: "Discard preview and close" },
99
+ ],
100
+ owner.signal,
101
+ owner.isCurrent,
102
+ );
103
+ if (!owner.isCurrent() || !result || result.kind === "closed") return "close";
104
+ if (result?.kind !== "selected") continue;
105
+ if (result.value === "discard") return "close";
106
+ if (result.value === "document" || result.value === "transcript") {
107
+ const reviewed = await reviewText(
108
+ ctx,
109
+ owner,
110
+ result.value === "document" ? "Settings draft" : "Configuration conversation",
111
+ result.value === "document" ? draft.rawDocument : settingsChatTranscript(agent).join("\n\n"),
112
+ result.value === "document",
113
+ );
114
+ if (!owner.isCurrent() || !reviewed) return "close";
115
+ continue;
116
+ }
117
+ if (result.value !== "save" || !draft.candidate) continue;
118
+ const candidate = draft.candidate;
119
+ const revision = draft.revision;
120
+ const reviewed = await reviewText(ctx, owner, "Review draft before saving", candidate.rawDocument ?? "", true);
121
+ if (!owner.isCurrent() || !reviewed) return "close";
122
+ draft.assertRevision(revision);
123
+ const saved = await saveAsProfile(
124
+ ctx,
125
+ options,
126
+ { ...owner, isCurrent: () => owner.isCurrent() && draft.revision === revision },
127
+ candidate.rawDocument ?? "",
128
+ );
129
+ if (!owner.isCurrent() || saved === "close") return "close";
130
+ draft.assertRevision(revision);
131
+ if (!saved) continue;
132
+ const repair = expected.previous.diagnostics.some((item) => item.severity === "error");
133
+ const confirmed = await ctx.ui.confirm(
134
+ "Apply saved profile?",
135
+ [
136
+ `Profile saved: ${sanitizeTerminalDocument(saved.name)}. Apply it to the current footer without reload?`,
137
+ "This replaces the complete active settings document. Declining keeps the profile and leaves active settings unchanged.",
138
+ "Applying can run enabled module commands and network requests; review their configuration before accepting.",
139
+ "The previous file is retained in History. Detected concurrent edits block replacement.",
140
+ ...(repair ? ["The original settings document is invalid. Confirm only if you requested its repair."] : []),
141
+ ...candidate.diagnostics.map((item) => `${item.severity}: ${item.path}: ${item.message}`),
142
+ ].join("\n"),
143
+ { signal: owner.signal },
144
+ );
145
+ if (!owner.isCurrent()) return "close";
146
+ if (!confirmed) return "close";
147
+ try {
148
+ const result = await commitActiveDocument(ctx, options, candidate, owner, expected, repair, () => {
149
+ draft.assertRevision(revision);
150
+ assertProfileUnchanged(options.settingsPath, saved);
151
+ });
152
+ if (result === "applied") return "applied";
153
+ return "close";
154
+ } catch (error) {
155
+ if (!base.signal.aborted && base.isCurrent())
156
+ ctx.ui.notify(
157
+ `Profile was saved as ${sanitizeTerminalDocument(saved.name)}. Settings were not applied: ${sanitizeTerminalDocument(error instanceof Error ? error.message : String(error))}`,
158
+ "error",
159
+ );
160
+ }
161
+ }
162
+ return "close";
163
+ } finally {
164
+ owner.signal.removeEventListener("abort", abort);
165
+ try {
166
+ await cleanup();
167
+ } finally {
168
+ unregister?.();
169
+ // Hard cancellation ends the command owner, not its session. Clear the owned
170
+ // preview even after Ctrl+C, but never redraw a replaced or shut-down session.
171
+ if (base.isSessionCurrent?.() ?? base.isCurrent()) options.preview?.(undefined, ctx);
172
+ }
173
+ }
174
+ }
175
+
176
+ async function reviewText(
177
+ ctx: ExtensionCommandContext,
178
+ owner: WorkflowOwner,
179
+ title: string,
180
+ content: string,
181
+ toml: boolean,
182
+ ) {
183
+ let continued = false;
184
+ const menu = defineMenu<undefined, "review", "continue", ExtensionCommandContext>({
185
+ start: "review",
186
+ screens: {
187
+ review: () => ({
188
+ kind: "review",
189
+ title,
190
+ content,
191
+ enableSearch: true,
192
+ format: toml ? { kind: "code", language: "toml" } : { kind: "text" },
193
+ confirm: { id: "continue", label: "Continue", action: "continue" },
194
+ hint: "close",
195
+ }),
196
+ },
197
+ actions: {
198
+ continue: () => {
199
+ continued = true;
200
+ return { kind: "close" };
201
+ },
202
+ },
203
+ });
204
+ const result = await runMenu(ctx, menu, {
205
+ getState: () => undefined,
206
+ signal: owner.signal,
207
+ isCurrent: owner.isCurrent,
208
+ });
209
+ return result.kind === "closed" && continued;
210
+ }