@narumitw/pi-starship 0.58.0 → 0.59.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,208 @@
1
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+ import { defineMenu, runMenu, runTask } from "@narumitw/pi-tui-kit";
3
+ import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
4
+ import type { WorkflowOwner } from "./command-configuration.js";
5
+ import type { StarshipCommandOptions } from "./commands.js";
6
+ import {
7
+ atomicSaveConfigDocument,
8
+ BUILT_IN_EXAMPLE,
9
+ type LoadedStarshipConfig,
10
+ loadStarshipConfig,
11
+ validateConfigDocument,
12
+ } from "./config.js";
13
+ import { checkGistDocument, createSettingsGist, fetchSettingsGist, type GhApi, gistId } from "./gist.js";
14
+
15
+ export type GistWorkflowResult = "applied" | "cancel" | "close";
16
+ export type ReviewImport = (
17
+ loaded: LoadedStarshipConfig,
18
+ options: StarshipCommandOptions,
19
+ owner: WorkflowOwner,
20
+ ) => Promise<GistWorkflowResult>;
21
+
22
+ export async function shareSettingsGist(
23
+ ctx: ExtensionCommandContext,
24
+ options: StarshipCommandOptions,
25
+ owner: WorkflowOwner,
26
+ api?: GhApi,
27
+ ): Promise<GistWorkflowResult> {
28
+ if (ctx.mode !== "tui" || !current(owner)) return "cancel";
29
+ const loaded = options.getLoaded();
30
+ if (loaded.diagnostics.some((item) => item.severity === "error")) {
31
+ ctx.ui.notify("Fix configuration errors before sharing settings.", "warning");
32
+ return "cancel";
33
+ }
34
+ const raw = loaded.rawDocument ?? BUILT_IN_EXAMPLE;
35
+ try {
36
+ checkGistDocument(raw);
37
+ } catch (error) {
38
+ ctx.ui.notify(safeError(error), "error");
39
+ return "cancel";
40
+ }
41
+ const review = await reviewDocument(
42
+ ctx,
43
+ owner,
44
+ "Share settings as Gist",
45
+ raw,
46
+ [
47
+ "Review the entire loaded document, including comments and unknown fields, for secrets and local paths.",
48
+ "No settings file is created when sharing built-in defaults.",
49
+ ],
50
+ "Share unlisted Gist…",
51
+ );
52
+ if (!current(owner)) return "cancel";
53
+ if (!review) return "close";
54
+ const confirmed = await ctx.ui.confirm(
55
+ "Upload settings to GitHub?",
56
+ [
57
+ "Send the reviewed pi-starship.toml to github.com as a new unlisted Gist?",
58
+ "Unlisted is not private: anyone with the link can read it. Comments and unknown fields are included.",
59
+ "Cancellation or a network error cannot undo an upload already accepted by GitHub; check your Gists before retrying.",
60
+ ].join("\n"),
61
+ { signal: owner.signal },
62
+ );
63
+ if (!current(owner) || !confirmed) return "cancel";
64
+ const result = await runTask(ctx, {
65
+ label: "Sharing settings with GitHub…",
66
+ signal: owner.signal,
67
+ isCurrent: owner.isCurrent,
68
+ task: ({ signal }) => createSettingsGist(raw, signal, api),
69
+ onError: () =>
70
+ ctx.ui.notify(
71
+ "Gist upload failed. Check gh auth status, Gist access, connectivity, and your Gists before retrying. The upload may already exist.",
72
+ "error",
73
+ ),
74
+ });
75
+ if (!current(owner)) return "cancel";
76
+ if (result.kind === "completed") {
77
+ ctx.ui.notify(`Settings Gist: ${result.value}`, "info");
78
+ return "cancel";
79
+ }
80
+ return result.kind === "error" ? "cancel" : "close";
81
+ }
82
+
83
+ export async function importSettingsGist(
84
+ ctx: ExtensionCommandContext,
85
+ options: StarshipCommandOptions,
86
+ owner: WorkflowOwner,
87
+ reviewImport: ReviewImport,
88
+ api?: GhApi,
89
+ ): Promise<GistWorkflowResult> {
90
+ if (ctx.mode !== "tui" || !current(owner)) return "cancel";
91
+ const previous = options.getLoaded();
92
+ const revision = options.getLoadedRevision?.();
93
+ const disk = diskSnapshot(options);
94
+ const guardedOwner: WorkflowOwner = {
95
+ signal: owner.signal,
96
+ isCurrent: () =>
97
+ current(owner) &&
98
+ options.getLoadedRevision?.() === revision &&
99
+ options.getLoaded().rawDocument === previous.rawDocument &&
100
+ options.getLoaded().source === previous.source,
101
+ };
102
+ const value = await ctx.ui.input("Import pi-starship settings from Gist", "https://gist.github.com/<owner>/<id>", {
103
+ signal: owner.signal,
104
+ });
105
+ if (!current(guardedOwner) || value === undefined) return "cancel";
106
+ let id: string;
107
+ try {
108
+ id = gistId(value);
109
+ } catch (error) {
110
+ ctx.ui.notify(safeError(error), "error");
111
+ return "cancel";
112
+ }
113
+ const result = await runTask(ctx, {
114
+ label: "Reading settings from GitHub…",
115
+ signal: owner.signal,
116
+ isCurrent: guardedOwner.isCurrent,
117
+ task: ({ signal }) => fetchSettingsGist(id, signal, api),
118
+ onError: () =>
119
+ ctx.ui.notify(
120
+ "Gist import failed. Check the Gist ID, gh auth status, connectivity, and a complete pi-starship.toml file (up to 64 KiB).",
121
+ "error",
122
+ ),
123
+ });
124
+ if (!current(guardedOwner)) return "cancel";
125
+ if (result.kind !== "completed") return result.kind === "error" ? "cancel" : "close";
126
+ let validated: LoadedStarshipConfig;
127
+ try {
128
+ validated = (options.validate ?? validateConfigDocument)(options.settingsPath, result.value);
129
+ } catch (error) {
130
+ ctx.ui.notify(`Gist settings are invalid: ${safeError(error)}`, "error");
131
+ return "cancel";
132
+ }
133
+ const reviewed = await reviewDocument(
134
+ ctx,
135
+ guardedOwner,
136
+ "Review Gist settings",
137
+ result.value,
138
+ [
139
+ `Source: https://gist.github.com/${id}`,
140
+ "Untrusted settings can enable local commands and network requests. Review the complete TOML before applying.",
141
+ "Import replaces the entire local document, including comments and unknown fields; no backup is kept after success.",
142
+ ],
143
+ "Preview imported footer…",
144
+ );
145
+ if (!current(guardedOwner)) return "cancel";
146
+ if (!reviewed) return "close";
147
+ return reviewImport(
148
+ validated,
149
+ {
150
+ ...options,
151
+ save(path, raw) {
152
+ if (!current(guardedOwner) || diskSnapshot(options) !== disk) {
153
+ throw new Error("Settings changed during import. Start a new import to review the latest state.");
154
+ }
155
+ return (options.save ?? atomicSaveConfigDocument)(path, raw);
156
+ },
157
+ },
158
+ guardedOwner,
159
+ );
160
+ }
161
+
162
+ async function reviewDocument(
163
+ ctx: ExtensionCommandContext,
164
+ owner: WorkflowOwner,
165
+ title: string,
166
+ content: string,
167
+ lines: string[],
168
+ label: string,
169
+ ): Promise<boolean> {
170
+ let approved = false;
171
+ const menu = defineMenu<undefined, "document", "continue", ExtensionCommandContext>({
172
+ start: "document",
173
+ screens: {
174
+ document: () => ({
175
+ kind: "review",
176
+ title,
177
+ lines,
178
+ content,
179
+ format: { kind: "code", language: "toml" },
180
+ viewportSize: "adaptive",
181
+ enableSearch: true,
182
+ confirm: { id: "continue", label, action: "continue" },
183
+ hint: "close",
184
+ }),
185
+ },
186
+ actions: {
187
+ continue: () => {
188
+ approved = true;
189
+ return { kind: "close" };
190
+ },
191
+ },
192
+ });
193
+ await runMenu(ctx, menu, { getState: () => undefined, signal: owner.signal, isCurrent: owner.isCurrent });
194
+ return current(owner) && approved;
195
+ }
196
+
197
+ function diskSnapshot(options: StarshipCommandOptions): string {
198
+ const loaded = (options.read ?? loadStarshipConfig)(options.settingsPath);
199
+ return JSON.stringify([loaded.rawDocument, loaded.source, loaded.diagnostics]);
200
+ }
201
+
202
+ function current(owner: WorkflowOwner): boolean {
203
+ return !owner.signal.aborted && owner.isCurrent();
204
+ }
205
+
206
+ function safeError(error: unknown): string {
207
+ return sanitizeTerminalText(error instanceof Error ? error.message : String(error));
208
+ }
package/src/commands.ts CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  type WorkflowOwner,
12
12
  } from "./command-configuration.js";
13
13
  import { completeStarshipArguments, STARSHIP_SUBCOMMANDS } from "./command-contract.js";
14
+ import { importSettingsGist, shareSettingsGist } from "./command-gist.js";
14
15
  import { formatFooterExplanation } from "./command-inspector.js";
15
16
  import { showPresetPicker } from "./command-preset-picker.js";
16
17
  import { type PreviewMenuResult, showPreviewActionMenu } from "./command-preview.js";
@@ -22,6 +23,7 @@ import {
22
23
  removeConfigDocumentIfMatches,
23
24
  validateConfigDocument,
24
25
  } from "./config.js";
26
+ import type { GhApi } from "./gist.js";
25
27
  import { inspectUnavailableModules, type StatuslineInspection } from "./modules/inspection.js";
26
28
  import { getStarshipPreset, presetForDocument, STARSHIP_PRESETS, type StarshipPreset } from "./presets/catalog.js";
27
29
 
@@ -48,9 +50,14 @@ export interface StarshipCommandOptions extends ConfigurationCommandOptions {
48
50
  restore?: (settingsPath: string, rawDocument: string) => void;
49
51
  validate?: (settingsPath: string, rawDocument: string) => LoadedStarshipConfig;
50
52
  getMenuOwner?(): WorkflowOwner;
53
+ gistApi?: GhApi;
51
54
  }
52
55
 
53
- type ReviewIntent = { kind: "customize" } | { kind: "restore" } | { kind: "preset"; preset: StarshipPreset };
56
+ type ReviewIntent =
57
+ | { kind: "customize" }
58
+ | { kind: "restore" }
59
+ | { kind: "import" }
60
+ | { kind: "preset"; preset: StarshipPreset };
54
61
 
55
62
  export function registerStarshipCommand(pi: ExtensionAPI, options: StarshipCommandOptions) {
56
63
  pi.registerCommand("starship", {
@@ -112,7 +119,7 @@ async function showMainMenu(ctx: ExtensionCommandContext, options: StarshipComma
112
119
  | "configuration-effective"
113
120
  | "configuration-document"
114
121
  | "help";
115
- type Action = "customize" | "presets" | "configuration-reload" | "restore";
122
+ type Action = "customize" | "presets" | "configuration-reload" | "restore" | "gist-share" | "gist-import";
116
123
  const menu = defineMenu<undefined, Screen, Action, ExtensionCommandContext>({
117
124
  start: "main",
118
125
  screens: {
@@ -218,7 +225,7 @@ async function showMainMenu(ctx: ExtensionCommandContext, options: StarshipComma
218
225
  "Presets live-previews the cursor in the footer; Enter confirms apply and e customizes first.",
219
226
  "Explain footer breaks down the modules currently showing from the existing snapshot.",
220
227
  "Modules searches every supported module and explains its current read-only state.",
221
- "Configuration separates overview, effective TOML, loaded settings text, and safe disk reload.",
228
+ "Configuration includes disk reload plus unlisted Gist sharing and reviewed Gist import through gh.",
222
229
  `Settings: ${safeText(options.settingsPath)}`,
223
230
  "Docs: https://github.com/narumiruna/pi-extensions/tree/main/packages/pi-starship",
224
231
  ],
@@ -234,6 +241,23 @@ async function showMainMenu(ctx: ExtensionCommandContext, options: StarshipComma
234
241
  const result = await choosePreset(ctx, options, owner);
235
242
  return result === "applied" || result === "close" ? { kind: "close" } : { kind: "stay" };
236
243
  },
244
+ "gist-share": async () => {
245
+ const result = await shareSettingsGist(ctx, options, owner, options.gistApi);
246
+ return result === "close" ? { kind: "close" } : { kind: "stay" };
247
+ },
248
+ "gist-import": async () => {
249
+ const result = await importSettingsGist(
250
+ ctx,
251
+ options,
252
+ owner,
253
+ async (loaded, guardedOptions, guardedOwner) => {
254
+ const applied = await reviewAndApply(ctx, guardedOptions, loaded, { kind: "import" }, guardedOwner);
255
+ return applied === "edit" ? "cancel" : applied;
256
+ },
257
+ options.gistApi,
258
+ );
259
+ return result === "applied" || result === "close" ? { kind: "close" } : { kind: "stay" };
260
+ },
237
261
  "configuration-reload": async () => {
238
262
  const result = await reloadConfiguration(ctx, options, owner);
239
263
  return result === "close" ? { kind: "close" } : { kind: "stay" };
@@ -421,7 +445,7 @@ async function reviewAndApply(
421
445
  (width) => reviewPreviewBody(ctx, options, validated, width, intent),
422
446
  [
423
447
  { value: PREVIEW_ACTIONS.continue, label: continueLabel(intent) },
424
- ...(intent.kind === "restore"
448
+ ...(intent.kind === "restore" || intent.kind === "import"
425
449
  ? []
426
450
  : [
427
451
  {
@@ -453,6 +477,7 @@ async function reviewAndApply(
453
477
  const confirmed = await ctx.ui.confirm(
454
478
  confirmationTitle(intent),
455
479
  confirmationMessage(options.settingsPath, intent),
480
+ { signal: owner.signal },
456
481
  );
457
482
  if (!isCurrentOwner(owner)) return "cancel";
458
483
  if (!confirmed) {
@@ -503,6 +528,8 @@ function reviewTitle(intent: ReviewIntent): string {
503
528
  return "Footer preview";
504
529
  case "restore":
505
530
  return "Restore preview";
531
+ case "import":
532
+ return "Gist footer preview";
506
533
  case "preset":
507
534
  return `${intent.preset.label} preset preview`;
508
535
  }
@@ -514,6 +541,8 @@ function continueLabel(intent: ReviewIntent): string {
514
541
  return "Apply changes…";
515
542
  case "restore":
516
543
  return "Replace with built-in…";
544
+ case "import":
545
+ return "Replace with Gist settings…";
517
546
  case "preset":
518
547
  return `Apply ${intent.preset.label} preset…`;
519
548
  }
@@ -525,6 +554,8 @@ function confirmationTitle(intent: ReviewIntent): string {
525
554
  return "Apply footer changes?";
526
555
  case "restore":
527
556
  return "Restore built-in footer?";
557
+ case "import":
558
+ return "Replace settings with Gist?";
528
559
  case "preset":
529
560
  return `Apply ${intent.preset.label} preset?`;
530
561
  }
@@ -532,7 +563,12 @@ function confirmationTitle(intent: ReviewIntent): string {
532
563
 
533
564
  function confirmationMessage(settingsPath: string, intent: ReviewIntent): string {
534
565
  if (intent.kind === "customize") return "Save this configuration and apply it immediately?";
535
- const replacement = intent.kind === "restore" ? "the built-in configuration" : `the ${intent.preset.label} preset`;
566
+ const replacement =
567
+ intent.kind === "restore"
568
+ ? "the built-in configuration"
569
+ : intent.kind === "import"
570
+ ? "the reviewed Gist settings"
571
+ : `the ${intent.preset.label} preset`;
536
572
  return `Replace ${safeText(settingsPath)} entirely with ${replacement}? All custom settings, unknown fields, and comments will be removed. No backup is kept after success.`;
537
573
  }
538
574
 
@@ -542,6 +578,8 @@ function successMessage(intent: ReviewIntent): string {
542
578
  return "Footer settings saved and applied";
543
579
  case "restore":
544
580
  return "Built-in footer restored and applied";
581
+ case "import":
582
+ return "Gist settings saved and applied";
545
583
  case "preset":
546
584
  return `${intent.preset.label} preset saved and applied`;
547
585
  }
@@ -591,7 +629,7 @@ function reviewPreviewBody(
591
629
  intent: ReviewIntent,
592
630
  ): string[] {
593
631
  if (intent.kind === "restore") return restorePreviewBody(ctx, options, loaded, width);
594
- if (intent.kind === "customize") return previewBody(ctx, options, loaded, width);
632
+ if (intent.kind === "customize" || intent.kind === "import") return previewBody(ctx, options, loaded, width);
595
633
  const current = configurationPresentation(options.getLoaded());
596
634
  return [
597
635
  `Preset: ${intent.preset.label}`,
package/src/gist.ts ADDED
@@ -0,0 +1,133 @@
1
+ import { spawn } from "node:child_process";
2
+
3
+ export const GIST_FILENAME = "pi-starship.toml";
4
+ export const MAX_GIST_DOCUMENT_BYTES = 64 * 1024;
5
+ const MAX_RESPONSE_BYTES = 512 * 1024;
6
+ const REQUEST_TIMEOUT_MS = 30_000;
7
+
8
+ export type GhApi = (args: string[], input: string | undefined, signal: AbortSignal) => Promise<string>;
9
+
10
+ /** Gists are intentionally limited to github.com; never forward auth to a pasted host. */
11
+ export function gistId(value: string): string {
12
+ const text = value.trim();
13
+ if (/^[a-f\d]{5,64}$/iu.test(text)) return text;
14
+ try {
15
+ const url = new URL(text);
16
+ const match = /^\/(?:[\w-]+\/)?([a-f\d]{5,64})\/?$/iu.exec(url.pathname);
17
+ if (
18
+ url.protocol === "https:" &&
19
+ url.hostname === "gist.github.com" &&
20
+ !url.port &&
21
+ !url.username &&
22
+ !url.password &&
23
+ !url.search &&
24
+ match?.[1]
25
+ )
26
+ return match[1];
27
+ } catch {
28
+ // Report one fixed error without echoing untrusted input.
29
+ }
30
+ throw new Error("Enter a github.com Gist ID or https://gist.github.com/<owner>/<id> URL.");
31
+ }
32
+
33
+ export function checkGistDocument(rawDocument: string): void {
34
+ if (!rawDocument.trim()) throw new Error("The Gist settings document is empty.");
35
+ if (Buffer.byteLength(rawDocument, "utf8") > MAX_GIST_DOCUMENT_BYTES) {
36
+ throw new Error("The Gist settings document exceeds 64 KiB.");
37
+ }
38
+ }
39
+
40
+ export async function createSettingsGist(
41
+ rawDocument: string,
42
+ signal: AbortSignal,
43
+ api: GhApi = executeGhApi,
44
+ ): Promise<string> {
45
+ checkGistDocument(rawDocument);
46
+ const response = JSON.parse(
47
+ await api(
48
+ ["/gists", "--method", "POST", "--input", "-"],
49
+ JSON.stringify({
50
+ description: "pi-starship footer settings",
51
+ public: false,
52
+ files: { [GIST_FILENAME]: { content: rawDocument } },
53
+ }),
54
+ signal,
55
+ ),
56
+ ) as unknown;
57
+ signal.throwIfAborted();
58
+ if (!isRecord(response) || response.public !== false || typeof response.html_url !== "string") {
59
+ throw new Error("GitHub returned an invalid Gist response. Check your Gists before retrying.");
60
+ }
61
+ return `https://gist.github.com/${gistId(response.html_url)}`;
62
+ }
63
+
64
+ export async function fetchSettingsGist(
65
+ value: string,
66
+ signal: AbortSignal,
67
+ api: GhApi = executeGhApi,
68
+ ): Promise<string> {
69
+ const id = gistId(value);
70
+ const response = JSON.parse(await api([`/gists/${id}`, "--method", "GET"], undefined, signal)) as unknown;
71
+ signal.throwIfAborted();
72
+ const file = isRecord(response) && isRecord(response.files) ? response.files[GIST_FILENAME] : undefined;
73
+ if (!isRecord(file) || typeof file.content !== "string" || file.truncated !== false) {
74
+ throw new Error(`The Gist must contain a complete ${GIST_FILENAME} file. Truncated files are not supported.`);
75
+ }
76
+ checkGistDocument(file.content);
77
+ return file.content;
78
+ }
79
+
80
+ function isRecord(value: unknown): value is Record<string, unknown> {
81
+ return value !== null && typeof value === "object" && !Array.isArray(value);
82
+ }
83
+
84
+ /** Bound output and lifetime, keep request bodies on stdin, and never expose gh stderr. */
85
+ export const executeGhApi: GhApi = (args, input, signal) => {
86
+ signal.throwIfAborted();
87
+ return new Promise((resolve, reject) => {
88
+ const child = spawn(process.platform === "win32" ? "gh.exe" : "gh", ["api", "--hostname", "github.com", ...args], {
89
+ env: { ...process.env, GH_PROMPT_DISABLED: "1", GH_PAGER: "", GH_DEBUG: "" },
90
+ stdio: ["pipe", "pipe", "ignore"],
91
+ windowsHide: true,
92
+ });
93
+ const chunks: Buffer[] = [];
94
+ let bytes = 0;
95
+ let failure: Error | undefined;
96
+ const stop = (error: Error) => {
97
+ failure ??= error;
98
+ child.kill("SIGKILL");
99
+ };
100
+ const onAbort = () => stop(new Error("Gist request cancelled."));
101
+ const timer = setTimeout(
102
+ () => stop(new Error("Gist request timed out. Check GitHub before retrying an upload.")),
103
+ REQUEST_TIMEOUT_MS,
104
+ );
105
+ timer.unref();
106
+ signal.addEventListener("abort", onAbort, { once: true });
107
+ child.stdout.on("data", (chunk: Buffer) => {
108
+ bytes += chunk.length;
109
+ if (bytes > MAX_RESPONSE_BYTES) stop(new Error("GitHub Gist response exceeds 512 KiB."));
110
+ else chunks.push(chunk);
111
+ });
112
+ child.stdin.on("error", () => {
113
+ stop(new Error("Unable to send settings to gh."));
114
+ });
115
+ child.on("error", () => {
116
+ failure ??= new Error("Unable to start gh. Install GitHub CLI and run gh auth login with Gist access.");
117
+ });
118
+ child.on("close", (code) => {
119
+ clearTimeout(timer);
120
+ signal.removeEventListener("abort", onAbort);
121
+ if (failure) reject(failure);
122
+ else if (code !== 0)
123
+ reject(
124
+ new Error(
125
+ "Gist request failed. Check gh auth status, Gist access, and connectivity. An upload may already exist.",
126
+ ),
127
+ );
128
+ else resolve(Buffer.concat(chunks).toString("utf8"));
129
+ });
130
+ if (signal.aborted) onAbort();
131
+ child.stdin.end(input);
132
+ });
133
+ };