@narumitw/pi-starship 0.22.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.
@@ -0,0 +1,79 @@
1
+ import type { StyledChunk } from "../format/style.js";
2
+
3
+ export interface GitStatusSnapshot {
4
+ ahead: number;
5
+ behind: number;
6
+ staged: number;
7
+ modified: number;
8
+ untracked: number;
9
+ conflicted: number;
10
+ }
11
+
12
+ export interface GitWorktreeSnapshot {
13
+ name: string;
14
+ path: string;
15
+ }
16
+
17
+ export type ExtensionStatusIconAliasMap = ReadonlyMap<string, readonly string[]>;
18
+
19
+ export interface StarshipRuntimeSnapshot {
20
+ cwd: string;
21
+ model?: { provider: string; id: string };
22
+ thinkingLevel: string;
23
+ turnCount: number;
24
+ activeTools: ReadonlyMap<string, number>;
25
+ isStreaming: boolean;
26
+ lastCompletedTool?: string;
27
+ contextUsage?: {
28
+ percent?: number | null;
29
+ tokens?: number | null;
30
+ contextWindow?: number | null;
31
+ };
32
+ tokenTotals: { input: number; output: number; cost: number };
33
+ gitBranch: string | null;
34
+ gitStatus?: GitStatusSnapshot;
35
+ gitWorktree?: GitWorktreeSnapshot;
36
+ extensionStatuses: ReadonlyMap<string, string>;
37
+ extensionStatusIconAliases: ExtensionStatusIconAliasMap;
38
+ now: Date;
39
+ }
40
+
41
+ export interface ExtensionStatusPresentation {
42
+ separator: string;
43
+ maxStatuses: number;
44
+ icons: Readonly<Record<string, string>>;
45
+ }
46
+
47
+ export interface ModuleValueContext {
48
+ runtime: StarshipRuntimeSnapshot;
49
+ symbol: string;
50
+ extensionStatus: ExtensionStatusPresentation;
51
+ hiddenExtensionStatusKeys: ReadonlySet<string>;
52
+ }
53
+
54
+ export interface ModuleDefaults {
55
+ format: string;
56
+ symbol: string;
57
+ style: string;
58
+ disabled: boolean;
59
+ }
60
+
61
+ export interface ModuleDefinition<Name extends string> {
62
+ name: Name;
63
+ variables: readonly string[];
64
+ defaults: ModuleDefaults;
65
+ values(context: ModuleValueContext): Record<string, string> | undefined;
66
+ }
67
+
68
+ export function defineModule<const Name extends string>(
69
+ definition: ModuleDefinition<Name>,
70
+ ): ModuleDefinition<Name> {
71
+ return definition;
72
+ }
73
+
74
+ export interface RenderedStatusline<Name extends string = string> {
75
+ ansi: string;
76
+ chunks: StyledChunk[];
77
+ modules: Record<Name, StyledChunk[]>;
78
+ consumedExtensionStatusKeys: ReadonlySet<string>;
79
+ }
@@ -0,0 +1,325 @@
1
+ import {
2
+ type ExtensionAPI,
3
+ type ExtensionContext,
4
+ getAgentDir,
5
+ type ReadonlyFooterDataProvider,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import { wrapTextWithAnsi } from "@earendil-works/pi-tui";
8
+ import { registerStarshipCommand } from "./commands.js";
9
+ import {
10
+ type LoadedStarshipConfig,
11
+ loadOrCreateStarshipConfig,
12
+ loadStarshipConfig,
13
+ settingsFilePath,
14
+ } from "./config.js";
15
+ import { readInstalledPackageInfo } from "./installed-packages.js";
16
+ import { gitStatusEqual, readGitStatus, readGitWorktree } from "./modules/git/runtime.js";
17
+ import {
18
+ type ExtensionStatusIconAliasMap,
19
+ type GitStatusSnapshot,
20
+ type GitWorktreeSnapshot,
21
+ renderStatusline,
22
+ type StarshipRuntimeSnapshot,
23
+ } from "./modules/index.js";
24
+
25
+ const GIT_REFRESH_INTERVAL_MS = 30_000;
26
+ const GIT_EVENT_DEBOUNCE_MS = 250;
27
+ const EMPTY_ALIASES: ExtensionStatusIconAliasMap = new Map();
28
+
29
+ interface RuntimeState {
30
+ activeTools: Map<string, number>;
31
+ isStreaming: boolean;
32
+ thinkingLevel: string;
33
+ lastCompletedTool?: string;
34
+ gitStatus?: GitStatusSnapshot;
35
+ gitWorktree?: GitWorktreeSnapshot;
36
+ extensionStatusIconAliases: ExtensionStatusIconAliasMap;
37
+ requestRender?: () => void;
38
+ }
39
+
40
+ export default function piStarship(pi: ExtensionAPI) {
41
+ let loaded: LoadedStarshipConfig | undefined;
42
+ const runtime: RuntimeState = {
43
+ activeTools: new Map(),
44
+ isStreaming: false,
45
+ thinkingLevel: "off",
46
+ extensionStatusIconAliases: EMPTY_ALIASES,
47
+ };
48
+ let conflictWarningShown = false;
49
+ let sessionGeneration = 0;
50
+ let gitRequestId = 0;
51
+ let activeGitTarget: { cwd: string; generation: number } | undefined;
52
+ let gitRefreshInFlight = false;
53
+ let gitDebounceTimer: ReturnType<typeof setTimeout> | undefined;
54
+ let pendingGitRefresh: { cwd: string; generation: number; requestId: number } | undefined;
55
+
56
+ const refresh = () => runtime.requestRender?.();
57
+ const clearDebounce = () => {
58
+ if (!gitDebounceTimer) return;
59
+ clearTimeout(gitDebounceTimer);
60
+ gitDebounceTimer = undefined;
61
+ };
62
+ const isActiveTarget = (cwd: string, generation: number) =>
63
+ activeGitTarget?.cwd === cwd &&
64
+ activeGitTarget.generation === generation &&
65
+ generation === sessionGeneration;
66
+ const isCurrentRequest = (cwd: string, generation: number, requestId: number) =>
67
+ isActiveTarget(cwd, generation) && requestId === gitRequestId;
68
+
69
+ const setGitStatus = (status: GitStatusSnapshot | undefined) => {
70
+ if (gitStatusEqual(runtime.gitStatus, status)) return;
71
+ runtime.gitStatus = status;
72
+ refresh();
73
+ };
74
+
75
+ const refreshGitWorktree = (cwd: string, generation: number) => {
76
+ void (async () => {
77
+ let worktree: GitWorktreeSnapshot | undefined;
78
+ try {
79
+ worktree = await readGitWorktree(pi, cwd);
80
+ } catch {
81
+ worktree = undefined;
82
+ }
83
+ if (!isActiveTarget(cwd, generation)) return;
84
+ if (
85
+ runtime.gitWorktree?.name === worktree?.name &&
86
+ runtime.gitWorktree?.path === worktree?.path
87
+ ) {
88
+ return;
89
+ }
90
+ runtime.gitWorktree = worktree;
91
+ refresh();
92
+ })();
93
+ };
94
+
95
+ const runGitRefresh = (cwd: string, generation: number, requestId: number) => {
96
+ if (!isCurrentRequest(cwd, generation, requestId)) return;
97
+ if (gitRefreshInFlight) {
98
+ pendingGitRefresh = { cwd, generation, requestId };
99
+ return;
100
+ }
101
+ gitRefreshInFlight = true;
102
+ void (async () => {
103
+ try {
104
+ const status = await readGitStatus(pi, cwd);
105
+ if (isCurrentRequest(cwd, generation, requestId)) setGitStatus(status);
106
+ } catch {
107
+ if (isCurrentRequest(cwd, generation, requestId)) setGitStatus(undefined);
108
+ } finally {
109
+ gitRefreshInFlight = false;
110
+ const pending = pendingGitRefresh;
111
+ pendingGitRefresh = undefined;
112
+ if (pending) runGitRefresh(pending.cwd, pending.generation, pending.requestId);
113
+ }
114
+ })();
115
+ };
116
+
117
+ const refreshGit = (cwd: string, generation = sessionGeneration) => {
118
+ if (!isActiveTarget(cwd, generation)) return;
119
+ runGitRefresh(cwd, generation, ++gitRequestId);
120
+ };
121
+ const scheduleGit = (ctx: ExtensionContext) => {
122
+ if (!activeGitTarget || activeGitTarget.cwd !== ctx.cwd) return;
123
+ const { cwd, generation } = activeGitTarget;
124
+ const requestId = ++gitRequestId;
125
+ clearDebounce();
126
+ gitDebounceTimer = setTimeout(() => {
127
+ gitDebounceTimer = undefined;
128
+ runGitRefresh(cwd, generation, requestId);
129
+ }, GIT_EVENT_DEBOUNCE_MS);
130
+ };
131
+
132
+ const installFooter = (ctx: ExtensionContext) => {
133
+ const generation = ++sessionGeneration;
134
+ const cwd = ctx.cwd;
135
+ clearDebounce();
136
+ pendingGitRefresh = undefined;
137
+ runtime.gitStatus = undefined;
138
+ runtime.gitWorktree = undefined;
139
+ runtime.requestRender = undefined;
140
+ activeGitTarget = ctx.mode === "tui" ? { cwd, generation } : undefined;
141
+ ctx.ui.setStatus("starship", undefined);
142
+ if (!activeGitTarget || !loaded) return;
143
+
144
+ const installed = readInstalledPackageInfo(getAgentDir(), cwd, ctx.isProjectTrusted());
145
+ runtime.extensionStatusIconAliases = installed.aliases;
146
+ if (installed.hasStatuslineConflict && !conflictWarningShown) {
147
+ conflictWarningShown = true;
148
+ ctx.ui.notify(
149
+ "pi-starship and pi-statusline both replace Pi's footer; disable one to avoid a footer conflict.",
150
+ "warning",
151
+ );
152
+ }
153
+
154
+ ctx.ui.setFooter((tui, _theme, footerData) => {
155
+ runtime.requestRender = () => tui.requestRender();
156
+ const unsubscribe = footerData.onBranchChange(() => {
157
+ runtime.gitStatus = undefined;
158
+ clearDebounce();
159
+ refreshGit(cwd, generation);
160
+ tui.requestRender();
161
+ });
162
+ const timer = setInterval(() => {
163
+ clearDebounce();
164
+ refreshGit(cwd, generation);
165
+ tui.requestRender();
166
+ }, GIT_REFRESH_INTERVAL_MS);
167
+ let disposed = false;
168
+
169
+ return {
170
+ dispose() {
171
+ if (disposed) return;
172
+ disposed = true;
173
+ unsubscribe();
174
+ clearInterval(timer);
175
+ if (isActiveTarget(cwd, generation)) {
176
+ activeGitTarget = undefined;
177
+ clearDebounce();
178
+ pendingGitRefresh = undefined;
179
+ runtime.gitStatus = undefined;
180
+ runtime.gitWorktree = undefined;
181
+ runtime.requestRender = undefined;
182
+ }
183
+ },
184
+ invalidate() {},
185
+ render(width: number): string[] {
186
+ if (!loaded) return [];
187
+ const snapshot = runtimeSnapshot(ctx, footerData, runtime);
188
+ return wrapFormattedStatusline(renderStatusline(loaded.config, snapshot).ansi, width);
189
+ },
190
+ };
191
+ });
192
+ refreshGit(cwd, generation);
193
+ refreshGitWorktree(cwd, generation);
194
+ };
195
+
196
+ const configPath = settingsFilePath(getAgentDir());
197
+ registerStarshipCommand(pi, {
198
+ settingsPath: configPath,
199
+ getLoaded: () => loaded ?? loadStarshipConfig(configPath),
200
+ apply(next) {
201
+ loaded = next;
202
+ refresh();
203
+ },
204
+ });
205
+
206
+ pi.on("session_start", (_event, ctx) => {
207
+ loaded = loadOrCreateStarshipConfig(configPath);
208
+ if (loaded.diagnostics.length > 0 && (ctx.mode === "tui" || ctx.hasUI)) {
209
+ ctx.ui.notify(formatDiagnostics(loaded), "warning");
210
+ }
211
+ runtime.thinkingLevel = pi.getThinkingLevel();
212
+ installFooter(ctx);
213
+ });
214
+
215
+ pi.on("session_tree", (_event, ctx) => {
216
+ installFooter(ctx);
217
+ refresh();
218
+ });
219
+
220
+ pi.on("session_shutdown", (_event, ctx) => {
221
+ sessionGeneration += 1;
222
+ activeGitTarget = undefined;
223
+ clearDebounce();
224
+ pendingGitRefresh = undefined;
225
+ runtime.gitStatus = undefined;
226
+ runtime.gitWorktree = undefined;
227
+ runtime.extensionStatusIconAliases = EMPTY_ALIASES;
228
+ runtime.requestRender = undefined;
229
+ ctx.ui.setFooter(undefined);
230
+ ctx.ui.setStatus("starship", undefined);
231
+ });
232
+
233
+ pi.on("model_select", () => refresh());
234
+ pi.on("thinking_level_select", (event) => {
235
+ runtime.thinkingLevel = event.level;
236
+ refresh();
237
+ });
238
+ pi.on("agent_start", () => {
239
+ runtime.isStreaming = true;
240
+ refresh();
241
+ });
242
+ pi.on("agent_end", (_event, ctx) => {
243
+ runtime.isStreaming = false;
244
+ scheduleGit(ctx);
245
+ refresh();
246
+ });
247
+ pi.on("turn_start", () => {
248
+ runtime.isStreaming = true;
249
+ refresh();
250
+ });
251
+ pi.on("turn_end", (_event, ctx) => {
252
+ scheduleGit(ctx);
253
+ refresh();
254
+ });
255
+ pi.on("tool_execution_start", (event) => {
256
+ runtime.activeTools.set(event.toolName, (runtime.activeTools.get(event.toolName) ?? 0) + 1);
257
+ refresh();
258
+ });
259
+ pi.on("tool_execution_end", (event, ctx) => {
260
+ const count = runtime.activeTools.get(event.toolName) ?? 0;
261
+ if (count <= 1) runtime.activeTools.delete(event.toolName);
262
+ else runtime.activeTools.set(event.toolName, count - 1);
263
+ runtime.lastCompletedTool = event.toolName;
264
+ scheduleGit(ctx);
265
+ refresh();
266
+ });
267
+ }
268
+
269
+ function runtimeSnapshot(
270
+ ctx: ExtensionContext,
271
+ footerData: ReadonlyFooterDataProvider,
272
+ runtime: RuntimeState,
273
+ ): StarshipRuntimeSnapshot {
274
+ return {
275
+ cwd: ctx.cwd,
276
+ model: ctx.model ? { provider: ctx.model.provider, id: ctx.model.id } : undefined,
277
+ thinkingLevel: runtime.thinkingLevel,
278
+ turnCount: userTurnCount(ctx),
279
+ activeTools: runtime.activeTools,
280
+ isStreaming: runtime.isStreaming,
281
+ lastCompletedTool: runtime.lastCompletedTool,
282
+ contextUsage: ctx.getContextUsage() ?? undefined,
283
+ tokenTotals: tokenTotals(ctx),
284
+ gitBranch: footerData.getGitBranch(),
285
+ gitStatus: runtime.gitStatus,
286
+ gitWorktree: runtime.gitWorktree,
287
+ extensionStatuses: footerData.getExtensionStatuses(),
288
+ extensionStatusIconAliases: runtime.extensionStatusIconAliases,
289
+ now: new Date(),
290
+ };
291
+ }
292
+
293
+ function userTurnCount(ctx: ExtensionContext): number {
294
+ return ctx.sessionManager
295
+ .getBranch()
296
+ .filter((entry) => entry.type === "message" && entry.message.role === "user").length;
297
+ }
298
+
299
+ function tokenTotals(ctx: ExtensionContext): { input: number; output: number; cost: number } {
300
+ const totals = { input: 0, output: 0, cost: 0 };
301
+ for (const entry of ctx.sessionManager.getBranch()) {
302
+ if (entry.type !== "message" || entry.message.role !== "assistant") continue;
303
+ const usage = entry.message.usage;
304
+ totals.input += usage.input ?? 0;
305
+ totals.output += usage.output ?? 0;
306
+ totals.cost += usage.cost?.total ?? 0;
307
+ }
308
+ return totals;
309
+ }
310
+
311
+ function formatDiagnostics(loaded: LoadedStarshipConfig): string {
312
+ const details = loaded.diagnostics.slice(0, 5).map((item) => item.message);
313
+ const remaining = loaded.diagnostics.length - details.length;
314
+ return [
315
+ `pi-starship settings: ${details.join("; ")}`,
316
+ ...(remaining > 0 ? [`+${remaining} more`] : []),
317
+ ].join(" ");
318
+ }
319
+
320
+ export function wrapFormattedStatusline(format: string, width: number): string[] {
321
+ if (width <= 0) return [];
322
+ return wrapTextWithAnsi(format, width);
323
+ }
324
+
325
+ export { parseGitStatusPorcelain, parseGitWorktree } from "./modules/git/runtime.js";