@narumitw/pi-starship 0.43.0 → 0.44.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.
@@ -22,13 +22,9 @@ export function renderStatusline(
22
22
  modules[name] = [];
23
23
  layoutModules[name] = [];
24
24
  }
25
- const consumedExtensionStatusKeys = new Set<string>();
26
-
27
25
  for (const definition of MODULE_DEFINITIONS) {
28
26
  const name = definition.name;
29
- const values = definition.values(
30
- valueContext(config, name, runtime, consumedExtensionStatusKeys),
31
- );
27
+ const values = definition.values(valueContext(config, name, runtime));
32
28
  if (!values) continue;
33
29
  const rendered = renderModule(config.modules[name], values, palette);
34
30
  modules[name] = rendered;
@@ -36,14 +32,6 @@ export function renderStatusline(
36
32
  definition.layout === "fill" && !config.modules[name].disabled
37
33
  ? [{ type: "fill", pattern: rendered }]
38
34
  : rendered;
39
- if (
40
- name === "git_branch" &&
41
- values.pr &&
42
- formatVariables(config.modules.git_branch.formatAst).has("pr") &&
43
- rendered.some((chunk) => chunk.text.includes(values.pr ?? ""))
44
- ) {
45
- consumedExtensionStatusKeys.add("github-pr");
46
- }
47
35
  }
48
36
 
49
37
  const explicitModules = formatVariables(config.formatAst);
@@ -58,7 +46,6 @@ export function renderStatusline(
58
46
  ansi: renderChunksToAnsi(chunks),
59
47
  chunks,
60
48
  modules,
61
- consumedExtensionStatusKeys,
62
49
  };
63
50
  }
64
51
 
@@ -66,14 +53,12 @@ function valueContext(
66
53
  config: StarshipConfig,
67
54
  name: ModuleName,
68
55
  runtime: StarshipRuntimeSnapshot,
69
- hiddenExtensionStatusKeys: ReadonlySet<string>,
70
56
  ): ModuleValueContext {
71
57
  return {
72
58
  runtime,
73
59
  symbol: config.modules[name].symbol,
74
60
  options: config.modules[name].options,
75
61
  extensionStatus: config.extensionStatus,
76
- hiddenExtensionStatusKeys,
77
62
  };
78
63
  }
79
64
 
@@ -50,6 +50,18 @@ export interface GitWorktreeSnapshot {
50
50
  path: string;
51
51
  }
52
52
 
53
+ export type GithubPrState = "open" | "draft" | "merged" | "closed";
54
+
55
+ export interface GithubPrSnapshot {
56
+ readonly number: string;
57
+ readonly link: string;
58
+ readonly state: GithubPrState;
59
+ readonly checks: string;
60
+ readonly review: string;
61
+ readonly status: string;
62
+ readonly expiresAt?: number;
63
+ }
64
+
53
65
  export interface GitSnapshot {
54
66
  branch?: GitBranchSnapshot;
55
67
  commit?: GitCommitSnapshot;
@@ -59,8 +71,6 @@ export interface GitSnapshot {
59
71
  worktree?: GitWorktreeSnapshot;
60
72
  }
61
73
 
62
- export type ExtensionStatusIconAliasMap = ReadonlyMap<string, readonly string[]>;
63
-
64
74
  export interface WorkspaceSnapshot {
65
75
  modules: Readonly<Record<string, Readonly<Record<string, string>>>>;
66
76
  }
@@ -94,8 +104,8 @@ export interface StarshipRuntimeSnapshot {
94
104
  gitMetrics?: GitMetricsSnapshot;
95
105
  gitStatus?: GitStatusSnapshot;
96
106
  gitWorktree?: GitWorktreeSnapshot;
107
+ githubPr?: GithubPrSnapshot;
97
108
  extensionStatuses: ReadonlyMap<string, string>;
98
- extensionStatusIconAliases: ExtensionStatusIconAliasMap;
99
109
  now: Date;
100
110
  workspace?: WorkspaceSnapshot;
101
111
  }
@@ -118,7 +128,6 @@ export interface ModuleValueContext {
118
128
  symbol: string;
119
129
  options: Readonly<Record<string, ModuleOptionValue>>;
120
130
  extensionStatus: ExtensionStatusPresentation;
121
- hiddenExtensionStatusKeys: ReadonlySet<string>;
122
131
  }
123
132
 
124
133
  export type ModuleOptionSchema =
@@ -155,5 +164,4 @@ export interface RenderedStatusline<Name extends string = string> {
155
164
  ansi: string;
156
165
  chunks: StyledChunk[];
157
166
  modules: Record<Name, StyledChunk[]>;
158
- consumedExtensionStatusKeys: ReadonlySet<string>;
159
167
  }
@@ -13,10 +13,9 @@ import {
13
13
  type StarshipConfig,
14
14
  settingsFilePath,
15
15
  } from "./config.js";
16
- import { readInstalledPackageInfo } from "./installed-packages.js";
17
16
  import { gitSnapshotEqual, readGitSnapshot } from "./modules/git/runtime.js";
18
17
  import {
19
- type ExtensionStatusIconAliasMap,
18
+ type GithubPrSnapshot,
20
19
  type GitSnapshot,
21
20
  reachableModuleRequirements,
22
21
  renderStatusline,
@@ -24,17 +23,20 @@ import {
24
23
  type WorkspaceSnapshot,
25
24
  } from "./modules/index.js";
26
25
  import { execWorkspaceCommand } from "./runtime/command.js";
26
+ import { githubPrSnapshotEqual, queryGithubPr } from "./runtime/github-pr.js";
27
27
  import { AsyncRefreshController } from "./runtime/refresh-controller.js";
28
28
  import {
29
29
  collectWorkspaceSnapshot,
30
+ type WorkspaceExec,
30
31
  type WorkspaceRefreshInput,
31
32
  workspaceSnapshotEqual,
32
33
  } from "./runtime/workspace.js";
33
34
  import { summarizeFooterUsage } from "./usage.js";
34
35
 
35
36
  const REFRESH_INTERVAL_MS = 30_000;
37
+ const GITHUB_PR_REFRESH_INTERVAL_MS = 60_000;
36
38
  const EVENT_DEBOUNCE_MS = 250;
37
- const EMPTY_ALIASES: ExtensionStatusIconAliasMap = new Map();
39
+ const MAX_TIMER_DELAY_MS = 2_147_483_647;
38
40
 
39
41
  interface RuntimeState {
40
42
  activeTools: Map<string, number>;
@@ -42,8 +44,8 @@ interface RuntimeState {
42
44
  thinkingLevel: string;
43
45
  lastCompletedTool?: string;
44
46
  git?: GitSnapshot;
47
+ githubPr?: GithubPrSnapshot;
45
48
  workspace?: WorkspaceSnapshot;
46
- extensionStatusIconAliases: ExtensionStatusIconAliasMap;
47
49
  requestRender?: () => void;
48
50
  renderPreview?: (loaded: LoadedStarshipConfig, width: number) => string[];
49
51
  }
@@ -51,6 +53,7 @@ interface RuntimeState {
51
53
  interface RefreshTarget {
52
54
  cwd: string;
53
55
  generation: number;
56
+ sessionManager: ExtensionContext["sessionManager"];
54
57
  }
55
58
 
56
59
  interface GitRefreshInput {
@@ -58,23 +61,30 @@ interface GitRefreshInput {
58
61
  config: StarshipConfig;
59
62
  }
60
63
 
61
- export default function piStarship(pi: ExtensionAPI) {
64
+ interface PiStarshipOptions {
65
+ githubPrExec?: WorkspaceExec;
66
+ }
67
+
68
+ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions = {}) {
62
69
  let loaded: LoadedStarshipConfig | undefined;
63
70
  const runtime: RuntimeState = {
64
71
  activeTools: new Map(),
65
72
  isStreaming: false,
66
73
  thinkingLevel: "off",
67
- extensionStatusIconAliases: EMPTY_ALIASES,
68
74
  };
69
- let conflictWarningShown = false;
70
75
  let sessionGeneration = 0;
71
76
  let menuController = new AbortController();
77
+ let sessionOwner: ExtensionContext["sessionManager"] | undefined;
72
78
  let activeTarget: RefreshTarget | undefined;
73
79
  let eventDebounceTimer: ReturnType<typeof setTimeout> | undefined;
80
+ let githubPrRefreshTimer: ReturnType<typeof setInterval> | undefined;
81
+ let githubPrExpiryTimer: ReturnType<typeof setTimeout> | undefined;
82
+ let githubPrGeneration = 0;
74
83
 
75
84
  const refresh = () => runtime.requestRender?.();
85
+ const githubPrExec = options.githubPrExec ?? execWorkspaceCommand;
76
86
  const gitController = new AsyncRefreshController<GitRefreshInput, GitSnapshot | undefined>({
77
- async read(input) {
87
+ async read(input, signal) {
78
88
  const requirements = reachableModuleRequirements(input.config);
79
89
  const gitReachable = [...requirements.keys()].some((name) => name.startsWith("git_"));
80
90
  if (!gitReachable) return undefined;
@@ -82,6 +92,7 @@ export default function piStarship(pi: ExtensionAPI) {
82
92
  return await readGitSnapshot(pi, input.cwd, {
83
93
  includeMetrics: requirements.has("git_metrics"),
84
94
  includeTag: requirements.get("git_commit")?.has("tag") ?? false,
95
+ signal,
85
96
  });
86
97
  } catch {
87
98
  return undefined;
@@ -93,10 +104,22 @@ export default function piStarship(pi: ExtensionAPI) {
93
104
  refresh();
94
105
  },
95
106
  });
107
+ const githubPrController = new AsyncRefreshController<
108
+ Pick<RefreshTarget, "cwd">,
109
+ GithubPrSnapshot | undefined
110
+ >({
111
+ read: (input, signal) => queryGithubPr(githubPrExec, input.cwd, signal),
112
+ equal: githubPrSnapshotEqual,
113
+ publish(snapshot) {
114
+ runtime.githubPr = snapshot;
115
+ scheduleGithubPrExpiry(snapshot);
116
+ refresh();
117
+ },
118
+ });
96
119
  const workspaceController = new AsyncRefreshController<WorkspaceRefreshInput, WorkspaceSnapshot>({
97
- async read(input) {
120
+ async read(input, signal) {
98
121
  try {
99
- return await collectWorkspaceSnapshot(input);
122
+ return await collectWorkspaceSnapshot({ ...input, signal });
100
123
  } catch {
101
124
  return { modules: {} };
102
125
  }
@@ -116,6 +139,7 @@ export default function piStarship(pi: ExtensionAPI) {
116
139
  const isActiveTarget = (target: RefreshTarget) =>
117
140
  activeTarget?.cwd === target.cwd &&
118
141
  activeTarget.generation === target.generation &&
142
+ activeTarget.sessionManager === target.sessionManager &&
119
143
  target.generation === sessionGeneration;
120
144
 
121
145
  const requestRefresh = (
@@ -130,7 +154,9 @@ export default function piStarship(pi: ExtensionAPI) {
130
154
  };
131
155
  const scheduleRefresh = (ctx: ExtensionContext) => {
132
156
  const target = activeTarget;
133
- if (!target || target.cwd !== ctx.cwd) return;
157
+ if (!target || target.cwd !== ctx.cwd || target.sessionManager !== ctx.sessionManager) {
158
+ return;
159
+ }
134
160
  clearDebounce();
135
161
  eventDebounceTimer = setTimeout(() => {
136
162
  eventDebounceTimer = undefined;
@@ -138,14 +164,80 @@ export default function piStarship(pi: ExtensionAPI) {
138
164
  }, EVENT_DEBOUNCE_MS);
139
165
  };
140
166
 
167
+ function restartLocalControllers(target: RefreshTarget) {
168
+ if (!isActiveTarget(target)) return;
169
+ gitController.start(target.generation);
170
+ workspaceController.start(target.generation);
171
+ }
172
+
173
+ function clearGithubPrTimers() {
174
+ if (githubPrRefreshTimer) clearInterval(githubPrRefreshTimer);
175
+ if (githubPrExpiryTimer) clearTimeout(githubPrExpiryTimer);
176
+ githubPrRefreshTimer = undefined;
177
+ githubPrExpiryTimer = undefined;
178
+ }
179
+
180
+ function stopGithubPr() {
181
+ clearGithubPrTimers();
182
+ githubPrController.stop();
183
+ runtime.githubPr = undefined;
184
+ }
185
+
186
+ function githubPrReachable(): boolean {
187
+ return Boolean(loaded && reachableModuleRequirements(loaded.config).has("github_pr"));
188
+ }
189
+
190
+ function startGithubPr(target: RefreshTarget): boolean {
191
+ if (!isActiveTarget(target)) return false;
192
+ stopGithubPr();
193
+ if (!githubPrReachable()) return false;
194
+ githubPrController.start(++githubPrGeneration);
195
+ githubPrRefreshTimer = setInterval(() => {
196
+ requestGithubPr(target);
197
+ }, GITHUB_PR_REFRESH_INTERVAL_MS);
198
+ githubPrRefreshTimer.unref?.();
199
+ return true;
200
+ }
201
+
202
+ function requestGithubPr(target: RefreshTarget) {
203
+ if (!isActiveTarget(target) || !githubPrReachable()) return;
204
+ githubPrController.request({ cwd: target.cwd });
205
+ }
206
+
207
+ function scheduleGithubPrExpiry(snapshot: GithubPrSnapshot | undefined) {
208
+ if (githubPrExpiryTimer) clearTimeout(githubPrExpiryTimer);
209
+ githubPrExpiryTimer = undefined;
210
+ if (snapshot?.expiresAt === undefined) return;
211
+ const target = activeTarget;
212
+ if (!target) return;
213
+ const delay = snapshot.expiresAt - Date.now();
214
+ if (delay <= 0) {
215
+ runtime.githubPr = undefined;
216
+ githubPrController.clear();
217
+ refresh();
218
+ return;
219
+ }
220
+ githubPrExpiryTimer = setTimeout(
221
+ () => {
222
+ githubPrExpiryTimer = undefined;
223
+ if (!isActiveTarget(target) || runtime.githubPr !== snapshot) return;
224
+ scheduleGithubPrExpiry(snapshot);
225
+ },
226
+ Math.min(delay, MAX_TIMER_DELAY_MS),
227
+ );
228
+ githubPrExpiryTimer.unref?.();
229
+ }
230
+
141
231
  const installFooter = (ctx: ExtensionContext) => {
142
232
  const generation = ++sessionGeneration;
233
+ sessionOwner = ctx.sessionManager;
143
234
  menuController.abort(new DOMException("Starship session context replaced", "AbortError"));
144
235
  menuController = new AbortController();
145
- const target = { cwd: ctx.cwd, generation };
236
+ const target: RefreshTarget = { cwd: ctx.cwd, generation, sessionManager: ctx.sessionManager };
146
237
  clearDebounce();
147
238
  gitController.stop();
148
239
  workspaceController.stop();
240
+ stopGithubPr();
149
241
  runtime.git = undefined;
150
242
  runtime.workspace = undefined;
151
243
  runtime.requestRender = undefined;
@@ -155,16 +247,7 @@ export default function piStarship(pi: ExtensionAPI) {
155
247
  if (!activeTarget || !loaded) return;
156
248
  gitController.start(generation);
157
249
  workspaceController.start(generation);
158
-
159
- const installed = readInstalledPackageInfo(getAgentDir(), target.cwd, ctx.isProjectTrusted());
160
- runtime.extensionStatusIconAliases = installed.aliases;
161
- if (installed.hasStatuslineConflict && !conflictWarningShown) {
162
- conflictWarningShown = true;
163
- ctx.ui.notify(
164
- "pi-starship and pi-statusline both replace Pi's footer; disable one to avoid a footer conflict.",
165
- "warning",
166
- );
167
- }
250
+ startGithubPr(target);
168
251
 
169
252
  ctx.ui.setFooter((tui, _theme, footerData) => {
170
253
  runtime.requestRender = () => tui.requestRender();
@@ -176,13 +259,17 @@ export default function piStarship(pi: ExtensionAPI) {
176
259
  );
177
260
  };
178
261
  const unsubscribe = footerData.onBranchChange(() => {
262
+ if (!isActiveTarget(target)) return;
179
263
  runtime.git = undefined;
180
- gitController.clear();
264
+ restartLocalControllers(target);
181
265
  clearDebounce();
266
+ startGithubPr(target);
182
267
  requestRefresh(target);
268
+ requestGithubPr(target);
183
269
  tui.requestRender();
184
270
  });
185
271
  const timer = setInterval(() => {
272
+ if (!isActiveTarget(target)) return;
186
273
  clearDebounce();
187
274
  requestRefresh(target, "periodic");
188
275
  tui.requestRender();
@@ -200,6 +287,7 @@ export default function piStarship(pi: ExtensionAPI) {
200
287
  clearDebounce();
201
288
  gitController.stop();
202
289
  workspaceController.stop();
290
+ stopGithubPr();
203
291
  runtime.git = undefined;
204
292
  runtime.workspace = undefined;
205
293
  runtime.requestRender = undefined;
@@ -218,6 +306,7 @@ export default function piStarship(pi: ExtensionAPI) {
218
306
  };
219
307
  });
220
308
  requestRefresh(target, "initial");
309
+ requestGithubPr(target);
221
310
  };
222
311
 
223
312
  const configPath = settingsFilePath(getAgentDir());
@@ -231,10 +320,18 @@ export default function piStarship(pi: ExtensionAPI) {
231
320
  isCurrent: () => generation === sessionGeneration && !menuController.signal.aborted,
232
321
  };
233
322
  },
234
- apply(next) {
323
+ apply(next, ctx) {
324
+ if (sessionOwner !== ctx.sessionManager) {
325
+ throw new Error("Starship session context was replaced");
326
+ }
235
327
  loaded = next;
236
328
  const target = activeTarget;
237
- if (target) requestRefresh(target);
329
+ if (target) {
330
+ restartLocalControllers(target);
331
+ startGithubPr(target);
332
+ requestRefresh(target);
333
+ requestGithubPr(target);
334
+ }
238
335
  refresh();
239
336
  },
240
337
  renderPreview(preview, width) {
@@ -261,15 +358,17 @@ export default function piStarship(pi: ExtensionAPI) {
261
358
  });
262
359
 
263
360
  pi.on("session_shutdown", (_event, ctx) => {
361
+ if (sessionOwner !== ctx.sessionManager) return;
362
+ sessionOwner = undefined;
264
363
  sessionGeneration += 1;
265
364
  menuController.abort(new DOMException("Starship session shut down", "AbortError"));
266
365
  activeTarget = undefined;
267
366
  clearDebounce();
268
367
  gitController.stop();
269
368
  workspaceController.stop();
369
+ stopGithubPr();
270
370
  runtime.git = undefined;
271
371
  runtime.workspace = undefined;
272
- runtime.extensionStatusIconAliases = EMPTY_ALIASES;
273
372
  runtime.requestRender = undefined;
274
373
  runtime.renderPreview = undefined;
275
374
  ctx.ui.setFooter(undefined);
@@ -288,6 +387,8 @@ export default function piStarship(pi: ExtensionAPI) {
288
387
  pi.on("agent_end", (_event, ctx) => {
289
388
  runtime.isStreaming = false;
290
389
  scheduleRefresh(ctx);
390
+ const target = activeTarget;
391
+ if (target?.sessionManager === ctx.sessionManager) requestGithubPr(target);
291
392
  refresh();
292
393
  });
293
394
  pi.on("turn_start", () => {
@@ -415,9 +516,9 @@ function runtimeSnapshot(
415
516
  gitMetrics: runtime.git?.metrics,
416
517
  gitStatus: runtime.git?.status,
417
518
  gitWorktree: runtime.git?.worktree,
519
+ githubPr: runtime.githubPr,
418
520
  workspace: runtime.workspace,
419
521
  extensionStatuses: footerData.getExtensionStatuses(),
420
- extensionStatusIconAliases: runtime.extensionStatusIconAliases,
421
522
  now: new Date(),
422
523
  };
423
524
  }
@@ -5,10 +5,16 @@ const FORCE_KILL_DELAY_MS = 250;
5
5
 
6
6
  export const execWorkspaceCommand: WorkspaceExec = async (command, args, options) =>
7
7
  new Promise((resolve) => {
8
+ if (options.signal?.aborted) {
9
+ resolve({ stdout: "", stderr: "", code: 1, killed: true });
10
+ return;
11
+ }
12
+
8
13
  let child: ReturnType<typeof spawn>;
9
14
  try {
10
15
  child = spawn(command, args, {
11
16
  cwd: options.cwd,
17
+ detached: process.platform !== "win32",
12
18
  env: explicitEnvironment(options.environment),
13
19
  shell: false,
14
20
  stdio: ["ignore", "pipe", "pipe"],
@@ -25,12 +31,14 @@ export const execWorkspaceCommand: WorkspaceExec = async (command, args, options
25
31
  let killed = false;
26
32
  let settled = false;
27
33
  let forceKillTimer: NodeJS.Timeout | undefined;
34
+ let timeoutTimer: NodeJS.Timeout | undefined;
28
35
 
29
36
  const finish = (code: number) => {
30
37
  if (settled) return;
31
38
  settled = true;
32
- clearTimeout(timeoutTimer);
39
+ if (timeoutTimer) clearTimeout(timeoutTimer);
33
40
  if (forceKillTimer) clearTimeout(forceKillTimer);
41
+ options.signal?.removeEventListener("abort", terminate);
34
42
  resolve({
35
43
  stdout: Buffer.concat(stdout).toString("utf8"),
36
44
  stderr: Buffer.concat(stderr).toString("utf8"),
@@ -39,17 +47,41 @@ export const execWorkspaceCommand: WorkspaceExec = async (command, args, options
39
47
  });
40
48
  };
41
49
 
42
- const terminate = () => {
50
+ const signalProcessTree = (signal: NodeJS.Signals) => {
51
+ const pid = child.pid;
52
+ if (pid === undefined) return;
53
+ if (process.platform !== "win32") {
54
+ try {
55
+ process.kill(-pid, signal);
56
+ return;
57
+ } catch {
58
+ child.kill(signal);
59
+ return;
60
+ }
61
+ }
62
+ try {
63
+ const killer = spawn("taskkill.exe", ["/pid", String(pid), "/t", "/f"], {
64
+ stdio: "ignore",
65
+ windowsHide: true,
66
+ });
67
+ killer.once("error", () => child.kill(signal));
68
+ killer.unref();
69
+ } catch {
70
+ child.kill(signal);
71
+ }
72
+ };
73
+
74
+ function terminate() {
43
75
  if (killed || settled) return;
44
76
  killed = true;
45
- child.kill("SIGTERM");
77
+ signalProcessTree("SIGTERM");
46
78
  forceKillTimer = setTimeout(() => {
47
- child.kill("SIGKILL");
79
+ signalProcessTree("SIGKILL");
48
80
  child.stdout?.destroy();
49
81
  child.stderr?.destroy();
50
82
  finish(1);
51
83
  }, FORCE_KILL_DELAY_MS);
52
- };
84
+ }
53
85
 
54
86
  const collect = (target: Buffer[]) => (data: Buffer | string) => {
55
87
  const chunk = Buffer.isBuffer(data) ? data : Buffer.from(data);
@@ -61,9 +93,15 @@ export const execWorkspaceCommand: WorkspaceExec = async (command, args, options
61
93
 
62
94
  child.stdout?.on("data", collect(stdout));
63
95
  child.stderr?.on("data", collect(stderr));
64
- child.once("error", () => finish(1));
65
- child.once("close", (code) => finish(code ?? 1));
66
- const timeoutTimer = setTimeout(terminate, options.timeout);
96
+ child.once("error", () => {
97
+ if (!killed) finish(1);
98
+ });
99
+ child.once("close", (code) => {
100
+ if (!killed) finish(code ?? 1);
101
+ });
102
+ options.signal?.addEventListener("abort", terminate, { once: true });
103
+ if (options.signal?.aborted) terminate();
104
+ timeoutTimer = setTimeout(terminate, options.timeout);
67
105
  });
68
106
 
69
107
  function explicitEnvironment(