@narumitw/pi-starship 0.49.0 → 0.49.3

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 (84) hide show
  1. package/README.md +6 -4
  2. package/dist/chunks/chunk-CKNSOLSW.ts +10 -0
  3. package/dist/chunks/chunk-CKNSOLSW.ts.map +7 -0
  4. package/dist/chunks/chunk-G2GG2V6Q.ts +218 -0
  5. package/dist/chunks/chunk-G2GG2V6Q.ts.map +7 -0
  6. package/dist/chunks/chunk-Q6DLIM7H.ts +2492 -0
  7. package/dist/chunks/chunk-Q6DLIM7H.ts.map +7 -0
  8. package/dist/chunks/cloud-JBSZWTB6.ts +142 -0
  9. package/dist/chunks/cloud-JBSZWTB6.ts.map +7 -0
  10. package/dist/chunks/commands-BSQZ2R4M.ts +757 -0
  11. package/dist/chunks/commands-BSQZ2R4M.ts.map +7 -0
  12. package/dist/chunks/deployment-ZNYM4B6W.ts +172 -0
  13. package/dist/chunks/deployment-ZNYM4B6W.ts.map +7 -0
  14. package/dist/chunks/development-TNWZ5SRC.ts +132 -0
  15. package/dist/chunks/development-TNWZ5SRC.ts.map +7 -0
  16. package/dist/chunks/execution-QHAP4U33.ts +132 -0
  17. package/dist/chunks/execution-QHAP4U33.ts.map +7 -0
  18. package/dist/chunks/languages-DPWDCH6Q.ts +184 -0
  19. package/dist/chunks/languages-DPWDCH6Q.ts.map +7 -0
  20. package/dist/chunks/package-MXN2YFLX.ts +104 -0
  21. package/dist/chunks/package-MXN2YFLX.ts.map +7 -0
  22. package/dist/pi-starship.ts +1350 -0
  23. package/dist/pi-starship.ts.map +7 -0
  24. package/package.json +10 -6
  25. package/src/index.ts +1 -1
  26. package/src/command-contract.ts +0 -13
  27. package/src/command-inspector.ts +0 -198
  28. package/src/command-preview.ts +0 -206
  29. package/src/commands.ts +0 -575
  30. package/src/config.ts +0 -794
  31. package/src/format/formatter.ts +0 -275
  32. package/src/format/style.ts +0 -278
  33. package/src/modules/activity.ts +0 -38
  34. package/src/modules/brand.ts +0 -13
  35. package/src/modules/cache.ts +0 -23
  36. package/src/modules/catalog.ts +0 -124
  37. package/src/modules/cloud.ts +0 -74
  38. package/src/modules/context.ts +0 -33
  39. package/src/modules/cost.ts +0 -31
  40. package/src/modules/deployment.ts +0 -61
  41. package/src/modules/development.ts +0 -112
  42. package/src/modules/directory.ts +0 -151
  43. package/src/modules/display.ts +0 -14
  44. package/src/modules/execution.ts +0 -84
  45. package/src/modules/extension-status.ts +0 -93
  46. package/src/modules/fill.ts +0 -14
  47. package/src/modules/git/branch.ts +0 -31
  48. package/src/modules/git/commit.ts +0 -29
  49. package/src/modules/git/metrics.ts +0 -26
  50. package/src/modules/git/runtime.ts +0 -415
  51. package/src/modules/git/state.ts +0 -21
  52. package/src/modules/git/status.ts +0 -87
  53. package/src/modules/git/worktree.ts +0 -16
  54. package/src/modules/github-pr.ts +0 -24
  55. package/src/modules/helpers.ts +0 -5
  56. package/src/modules/index.ts +0 -31
  57. package/src/modules/inspection.ts +0 -138
  58. package/src/modules/languages.ts +0 -87
  59. package/src/modules/model.ts +0 -85
  60. package/src/modules/package.ts +0 -17
  61. package/src/modules/provider.ts +0 -13
  62. package/src/modules/render.ts +0 -166
  63. package/src/modules/terminal.ts +0 -60
  64. package/src/modules/thinking.ts +0 -13
  65. package/src/modules/time.ts +0 -20
  66. package/src/modules/tokens.ts +0 -18
  67. package/src/modules/truncation.ts +0 -37
  68. package/src/modules/turn.ts +0 -13
  69. package/src/modules/types.ts +0 -189
  70. package/src/modules/workspace-helpers.ts +0 -10
  71. package/src/pi-starship.ts +0 -609
  72. package/src/runtime/cloud.ts +0 -166
  73. package/src/runtime/command.ts +0 -123
  74. package/src/runtime/deployment.ts +0 -201
  75. package/src/runtime/development.ts +0 -153
  76. package/src/runtime/execution.ts +0 -151
  77. package/src/runtime/github-pr.ts +0 -332
  78. package/src/runtime/helpers.ts +0 -274
  79. package/src/runtime/languages.ts +0 -205
  80. package/src/runtime/package.ts +0 -112
  81. package/src/runtime/refresh-controller.ts +0 -107
  82. package/src/runtime/types.ts +0 -63
  83. package/src/runtime/workspace.ts +0 -147
  84. package/src/usage.ts +0 -53
@@ -0,0 +1,1350 @@
1
+ // @generated by scripts/build-runtime.mjs; do not edit.
2
+ // @ts-nocheck -- generated JavaScript uses a .ts extension so Pi routes chunks through Jiti.
3
+ import {
4
+ PRIVATE_STYLE_SELECTOR
5
+ } from "./chunks/chunk-CKNSOLSW.js";
6
+ import {
7
+ createFileSystem
8
+ } from "./chunks/chunk-G2GG2V6Q.js";
9
+ import {
10
+ completeStarshipArguments,
11
+ inspectStatuslineModules,
12
+ loadStarshipConfig,
13
+ reachableModuleRequirements,
14
+ renderStatusline,
15
+ settingsFilePath
16
+ } from "./chunks/chunk-Q6DLIM7H.js";
17
+
18
+ // src/pi-starship.ts
19
+ import { homedir, hostname, userInfo } from "node:os";
20
+ import {
21
+ getAgentDir
22
+ } from "@earendil-works/pi-coding-agent";
23
+ import { wrapTextWithAnsi } from "@earendil-works/pi-tui";
24
+
25
+ // src/modules/git/runtime.ts
26
+ import { existsSync, readFileSync } from "node:fs";
27
+ import { basename, isAbsolute, join, resolve } from "node:path";
28
+ var GIT_TIMEOUT_MS = 3e3;
29
+ async function readGitSnapshot(pi, cwd, options) {
30
+ const statusPromise = pi.exec(
31
+ "git",
32
+ [
33
+ "--no-optional-locks",
34
+ "status",
35
+ "--porcelain=v2",
36
+ "--branch",
37
+ "--show-stash",
38
+ "--untracked-files=normal"
39
+ ],
40
+ { cwd, signal: options.signal, timeout: GIT_TIMEOUT_MS }
41
+ );
42
+ const metadataPromise = pi.exec(
43
+ "git",
44
+ ["rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir", "--git-dir"],
45
+ { cwd, signal: options.signal, timeout: GIT_TIMEOUT_MS }
46
+ );
47
+ const metricsPromise = options.includeMetrics ? pi.exec("git", ["--no-optional-locks", "diff", "--shortstat", "HEAD", "--"], {
48
+ cwd,
49
+ signal: options.signal,
50
+ timeout: GIT_TIMEOUT_MS
51
+ }) : Promise.resolve(void 0);
52
+ const tagPromise = options.includeTag ? pi.exec("git", ["describe", "--tags", "--exact-match", "HEAD"], {
53
+ cwd,
54
+ signal: options.signal,
55
+ timeout: GIT_TIMEOUT_MS
56
+ }) : Promise.resolve(void 0);
57
+ const [statusResult, metadataResult, metricsResult, tagResult] = await Promise.all([
58
+ statusPromise,
59
+ metadataPromise,
60
+ metricsPromise,
61
+ tagPromise
62
+ ]);
63
+ if (statusResult.code !== 0 || statusResult.killed) return void 0;
64
+ const parsed = parseGitStatusPorcelainV2(statusResult.stdout);
65
+ const metadata = metadataResult.code === 0 && !metadataResult.killed ? parseGitRepositoryMetadata(metadataResult.stdout) : void 0;
66
+ const commit = withTag(parsed.commit, tagResult);
67
+ const metrics = metricsResult && metricsResult.code === 0 && !metricsResult.killed ? parseGitDiffShortstat(metricsResult.stdout) : void 0;
68
+ return {
69
+ ...parsed,
70
+ root: metadata?.root,
71
+ commit,
72
+ state: metadata ? parseGitState(metadata.gitDirectory) : void 0,
73
+ metrics,
74
+ worktree: metadata?.worktree
75
+ };
76
+ }
77
+ function parseGitStatusPorcelainV2(output) {
78
+ const status = emptyGitStatus();
79
+ let branchName;
80
+ let commitHash;
81
+ let upstream;
82
+ for (const line of output.split(/\r?\n/u)) {
83
+ if (!line) continue;
84
+ if (line.startsWith("# branch.oid ")) {
85
+ const value = line.slice("# branch.oid ".length).trim();
86
+ if (value && value !== "(initial)") commitHash = value;
87
+ continue;
88
+ }
89
+ if (line.startsWith("# branch.head ")) {
90
+ branchName = line.slice("# branch.head ".length).trim();
91
+ continue;
92
+ }
93
+ if (line.startsWith("# branch.upstream ")) {
94
+ upstream = line.slice("# branch.upstream ".length).trim();
95
+ continue;
96
+ }
97
+ if (line.startsWith("# branch.ab ")) {
98
+ const match = /^# branch\.ab \+(\d+) -(\d+)$/u.exec(line);
99
+ status.ahead = match?.[1] ? Number(match[1]) : 0;
100
+ status.behind = match?.[2] ? Number(match[2]) : 0;
101
+ continue;
102
+ }
103
+ if (line.startsWith("# stash ")) {
104
+ const count = Number(line.slice("# stash ".length));
105
+ status.stashed = Number.isSafeInteger(count) && count > 0 ? count : 0;
106
+ continue;
107
+ }
108
+ addPorcelainV2Status(status, line);
109
+ }
110
+ finalizeStatus(status);
111
+ const detached = branchName === "(detached)";
112
+ const remote = splitUpstream(upstream);
113
+ const branch = branchName ? {
114
+ name: detached ? "HEAD" : branchName,
115
+ ...remote,
116
+ detached
117
+ } : void 0;
118
+ const commit = commitHash ? { hash: commitHash, detached } : void 0;
119
+ return { branch, commit, status };
120
+ }
121
+ function parseGitStatusPorcelain(output) {
122
+ const status = emptyGitStatus();
123
+ for (const line of output.split(/\r?\n/u)) {
124
+ if (!line) continue;
125
+ if (line.startsWith("## ")) {
126
+ const ahead = /\bahead (\d+)/u.exec(line);
127
+ const behind = /\bbehind (\d+)/u.exec(line);
128
+ status.ahead = ahead?.[1] ? Number(ahead[1]) : 0;
129
+ status.behind = behind?.[1] ? Number(behind[1]) : 0;
130
+ continue;
131
+ }
132
+ const indexStatus = line[0] ?? " ";
133
+ const worktreeStatus = line[1] ?? " ";
134
+ if (indexStatus === "?" && worktreeStatus === "?") {
135
+ status.untracked += 1;
136
+ continue;
137
+ }
138
+ if (isConflict(indexStatus, worktreeStatus)) {
139
+ status.conflicted += 1;
140
+ continue;
141
+ }
142
+ addNormalStatus(status, indexStatus, worktreeStatus);
143
+ if (indexStatus === "R" || indexStatus === "C") status.renamed += 1;
144
+ }
145
+ finalizeStatus(status);
146
+ return status;
147
+ }
148
+ function parseGitDiffShortstat(output) {
149
+ return {
150
+ added: parseShortstatMetric(output, "insertion(+)", "insertions(+)") ?? 0,
151
+ deleted: parseShortstatMetric(output, "deletion(-)", "deletions(-)") ?? 0
152
+ };
153
+ }
154
+ function parseShortstatMetric(output, singularLabel, pluralLabel) {
155
+ for (const field of output.split(",")) {
156
+ const trimmed = field.trim();
157
+ const separator = trimmed.indexOf(" ");
158
+ if (separator <= 0) continue;
159
+ const label = trimmed.slice(separator + 1).trimStart();
160
+ if (label !== singularLabel && label !== pluralLabel) continue;
161
+ const countText = trimmed.slice(0, separator);
162
+ for (const character of countText) {
163
+ if (character < "0" || character > "9") return void 0;
164
+ }
165
+ const count = Number(countText);
166
+ return Number.isSafeInteger(count) ? count : void 0;
167
+ }
168
+ return void 0;
169
+ }
170
+ function parseGitState(gitDirectory) {
171
+ const rebaseMerge = join(gitDirectory, "rebase-merge");
172
+ if (existsSync(rebaseMerge))
173
+ return operationWithProgress("REBASING", rebaseMerge, "msgnum", "end");
174
+ const rebaseApply = join(gitDirectory, "rebase-apply");
175
+ if (existsSync(rebaseApply)) {
176
+ const state = existsSync(join(rebaseApply, "applying")) ? "AM" : existsSync(join(rebaseApply, "rebasing")) ? "REBASING" : "AM/REBASE";
177
+ return operationWithProgress(state, rebaseApply, "next", "last");
178
+ }
179
+ if (existsSync(join(gitDirectory, "MERGE_HEAD"))) return { state: "MERGING" };
180
+ if (existsSync(join(gitDirectory, "REVERT_HEAD"))) return { state: "REVERTING" };
181
+ if (existsSync(join(gitDirectory, "CHERRY_PICK_HEAD"))) return { state: "CHERRY-PICKING" };
182
+ if (existsSync(join(gitDirectory, "BISECT_LOG"))) return { state: "BISECTING" };
183
+ return void 0;
184
+ }
185
+ function parseGitRepositoryMetadata(output) {
186
+ const lines = output.trimEnd().split(/\r?\n/u);
187
+ if (lines.length !== 3) return void 0;
188
+ const [path, commonDir, gitDirectory] = lines;
189
+ if (!path || !commonDir || !gitDirectory) return void 0;
190
+ if (![path, commonDir, gitDirectory].every(isAbsolute)) return void 0;
191
+ return {
192
+ root: path,
193
+ gitDirectory,
194
+ worktree: samePath(commonDir, gitDirectory) ? void 0 : { name: basename(path) || path, path }
195
+ };
196
+ }
197
+ function parseGitWorktree(output) {
198
+ return parseGitRepositoryMetadata(output)?.worktree;
199
+ }
200
+ function addPorcelainV2Status(status, line) {
201
+ const kind = line[0];
202
+ if (kind === "?") {
203
+ status.untracked += 1;
204
+ return;
205
+ }
206
+ if (kind === "u") {
207
+ status.conflicted += 1;
208
+ return;
209
+ }
210
+ if (kind !== "1" && kind !== "2") return;
211
+ const indexStatus = line[2] ?? ".";
212
+ const worktreeStatus = line[3] ?? ".";
213
+ addNormalStatus(status, indexStatus, worktreeStatus);
214
+ if (kind === "2") status.renamed += 1;
215
+ }
216
+ function addNormalStatus(status, indexStatus, worktreeStatus) {
217
+ if (indexStatus === "A") status.indexAdded += 1;
218
+ if (indexStatus === "D") status.indexDeleted += 1;
219
+ if (indexStatus === "M") status.indexModified += 1;
220
+ if (indexStatus === "T") status.indexTypechanged += 1;
221
+ if (worktreeStatus === "A") status.worktreeAdded += 1;
222
+ if (worktreeStatus === "D") status.worktreeDeleted += 1;
223
+ if (worktreeStatus === "M") status.worktreeModified += 1;
224
+ if (worktreeStatus === "T") status.worktreeTypechanged += 1;
225
+ }
226
+ function finalizeStatus(status) {
227
+ status.deleted = status.worktreeDeleted + status.indexDeleted;
228
+ status.modified = status.worktreeModified + status.worktreeAdded;
229
+ status.staged = status.indexModified + status.indexAdded + status.indexTypechanged;
230
+ status.typechanged = status.worktreeTypechanged;
231
+ }
232
+ function emptyGitStatus() {
233
+ return {
234
+ ahead: 0,
235
+ behind: 0,
236
+ stashed: 0,
237
+ conflicted: 0,
238
+ deleted: 0,
239
+ renamed: 0,
240
+ modified: 0,
241
+ staged: 0,
242
+ typechanged: 0,
243
+ untracked: 0,
244
+ worktreeAdded: 0,
245
+ worktreeDeleted: 0,
246
+ worktreeModified: 0,
247
+ worktreeTypechanged: 0,
248
+ indexAdded: 0,
249
+ indexDeleted: 0,
250
+ indexModified: 0,
251
+ indexTypechanged: 0
252
+ };
253
+ }
254
+ function splitUpstream(upstream) {
255
+ if (!upstream) return {};
256
+ const separator = upstream.indexOf("/");
257
+ if (separator <= 0 || separator === upstream.length - 1) return { remoteBranch: upstream };
258
+ return {
259
+ remoteName: upstream.slice(0, separator),
260
+ remoteBranch: upstream.slice(separator + 1)
261
+ };
262
+ }
263
+ function withTag(commit, result) {
264
+ if (!commit || !result || result.code !== 0 || result.killed) return commit;
265
+ const tag = result.stdout.trim();
266
+ return tag ? { ...commit, tag: tag.split(/\r?\n/u)[0] } : commit;
267
+ }
268
+ function operationWithProgress(state, directory, currentName, totalName) {
269
+ const progressCurrent = readPositiveInteger(join(directory, currentName));
270
+ const progressTotal = readPositiveInteger(join(directory, totalName));
271
+ return progressCurrent !== void 0 && progressTotal !== void 0 ? { state, progressCurrent, progressTotal } : { state };
272
+ }
273
+ function readPositiveInteger(path) {
274
+ try {
275
+ const value = Number(readFileSync(path, "utf8").trim());
276
+ return Number.isSafeInteger(value) && value > 0 ? value : void 0;
277
+ } catch {
278
+ return void 0;
279
+ }
280
+ }
281
+ function samePath(left, right) {
282
+ const normalizedLeft = resolve(left);
283
+ const normalizedRight = resolve(right);
284
+ return process.platform === "win32" ? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase() : normalizedLeft === normalizedRight;
285
+ }
286
+ function isConflict(indexStatus, worktreeStatus) {
287
+ return indexStatus === "D" && worktreeStatus === "D" || indexStatus === "A" && worktreeStatus === "A" || indexStatus === "U" || worktreeStatus === "U";
288
+ }
289
+ function gitSnapshotEqual(left, right) {
290
+ return JSON.stringify(left) === JSON.stringify(right);
291
+ }
292
+
293
+ // src/runtime/command.ts
294
+ import { spawn } from "node:child_process";
295
+ var FORCE_KILL_DELAY_MS = 250;
296
+ var execWorkspaceCommand = async (command, args, options) => new Promise((resolve2) => {
297
+ if (options.signal?.aborted) {
298
+ resolve2({ stdout: "", stderr: "", code: 1, killed: true });
299
+ return;
300
+ }
301
+ let child;
302
+ try {
303
+ child = spawn(command, args, {
304
+ cwd: options.cwd,
305
+ detached: process.platform !== "win32",
306
+ env: explicitEnvironment(options.environment),
307
+ shell: false,
308
+ stdio: ["ignore", "pipe", "pipe"],
309
+ windowsHide: true
310
+ });
311
+ } catch {
312
+ resolve2({ stdout: "", stderr: "", code: 1, killed: false });
313
+ return;
314
+ }
315
+ const stdout = [];
316
+ const stderr = [];
317
+ let outputBytes = 0;
318
+ let killed = false;
319
+ let settled = false;
320
+ let forceKillTimer;
321
+ let timeoutTimer;
322
+ const finish = (code) => {
323
+ if (settled) return;
324
+ settled = true;
325
+ if (timeoutTimer) clearTimeout(timeoutTimer);
326
+ if (forceKillTimer) clearTimeout(forceKillTimer);
327
+ options.signal?.removeEventListener("abort", terminate);
328
+ resolve2({
329
+ stdout: Buffer.concat(stdout).toString("utf8"),
330
+ stderr: Buffer.concat(stderr).toString("utf8"),
331
+ code,
332
+ killed
333
+ });
334
+ };
335
+ const signalProcessTree = (signal) => {
336
+ const pid = child.pid;
337
+ if (pid === void 0) return;
338
+ if (process.platform !== "win32") {
339
+ try {
340
+ process.kill(-pid, signal);
341
+ return;
342
+ } catch {
343
+ child.kill(signal);
344
+ return;
345
+ }
346
+ }
347
+ try {
348
+ const killer = spawn("taskkill.exe", ["/pid", String(pid), "/t", "/f"], {
349
+ stdio: "ignore",
350
+ windowsHide: true
351
+ });
352
+ killer.once("error", () => child.kill(signal));
353
+ killer.unref();
354
+ } catch {
355
+ child.kill(signal);
356
+ }
357
+ };
358
+ function terminate() {
359
+ if (killed || settled) return;
360
+ killed = true;
361
+ signalProcessTree("SIGTERM");
362
+ forceKillTimer = setTimeout(() => {
363
+ signalProcessTree("SIGKILL");
364
+ child.stdout?.destroy();
365
+ child.stderr?.destroy();
366
+ finish(1);
367
+ }, FORCE_KILL_DELAY_MS);
368
+ }
369
+ const collect = (target) => (data) => {
370
+ const chunk = Buffer.isBuffer(data) ? data : Buffer.from(data);
371
+ const remaining = Math.max(0, options.maxOutputBytes - outputBytes);
372
+ if (remaining > 0) target.push(chunk.subarray(0, remaining));
373
+ outputBytes += chunk.byteLength;
374
+ if (outputBytes > options.maxOutputBytes) terminate();
375
+ };
376
+ child.stdout?.on("data", collect(stdout));
377
+ child.stderr?.on("data", collect(stderr));
378
+ child.once("error", () => {
379
+ if (!killed) finish(1);
380
+ });
381
+ child.once("close", (code) => {
382
+ if (!killed) finish(code ?? 1);
383
+ });
384
+ options.signal?.addEventListener("abort", terminate, { once: true });
385
+ if (options.signal?.aborted) terminate();
386
+ timeoutTimer = setTimeout(terminate, options.timeout);
387
+ });
388
+ function explicitEnvironment(source) {
389
+ const result = /* @__PURE__ */ Object.create(null);
390
+ for (const [name, value] of Object.entries(source)) {
391
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name) || value === void 0 || value.includes("\0")) {
392
+ continue;
393
+ }
394
+ Object.defineProperty(result, name, {
395
+ value,
396
+ writable: true,
397
+ enumerable: true,
398
+ configurable: true
399
+ });
400
+ }
401
+ return result;
402
+ }
403
+
404
+ // src/runtime/github-pr.ts
405
+ var GH_TIMEOUT_MS = 1e4;
406
+ var MAX_GH_OUTPUT_BYTES = 128 * 1024;
407
+ var MAX_URL_LENGTH = 4096;
408
+ var MAX_CHECKS = 1e3;
409
+ var MAX_FIELD_LENGTH = 128;
410
+ var RFC3339_TIMESTAMP = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:Z|[+-](\d{2}):(\d{2}))$/u;
411
+ var TERMINAL_PR_LIFETIME_MS = 24 * 60 * 60 * 1e3;
412
+ var GH_PR_FIELDS = [
413
+ "number",
414
+ "isDraft",
415
+ "url",
416
+ "state",
417
+ "closedAt",
418
+ "mergedAt",
419
+ "reviewDecision",
420
+ "statusCheckRollup"
421
+ ];
422
+ function ghPrViewInvocation(platform = process.platform) {
423
+ return {
424
+ command: platform === "win32" ? "gh.exe" : "gh",
425
+ args: ["pr", "view", "--json", GH_PR_FIELDS.join(",")]
426
+ };
427
+ }
428
+ function githubPrEnvironment(source = process.env) {
429
+ const environment = /* @__PURE__ */ Object.create(null);
430
+ for (const [name, value] of Object.entries(source)) {
431
+ const normalized = name.toUpperCase();
432
+ if (normalized === "GH_HOST" || normalized === "GH_REPO") continue;
433
+ Object.defineProperty(environment, name, {
434
+ value,
435
+ writable: true,
436
+ enumerable: true,
437
+ configurable: true
438
+ });
439
+ }
440
+ return environment;
441
+ }
442
+ async function queryGithubPr(exec, cwd, signal, now = Date.now(), options = {}) {
443
+ const invocation = ghPrViewInvocation(options.platform);
444
+ try {
445
+ const result = await exec(invocation.command, invocation.args, {
446
+ cwd,
447
+ signal,
448
+ timeout: GH_TIMEOUT_MS,
449
+ maxOutputBytes: MAX_GH_OUTPUT_BYTES,
450
+ environment: githubPrEnvironment(options.environment)
451
+ });
452
+ if (result.killed || result.code !== 0) return void 0;
453
+ if (Buffer.byteLength(result.stdout) > MAX_GH_OUTPUT_BYTES) return void 0;
454
+ return buildGithubPrSnapshot(JSON.parse(result.stdout), now);
455
+ } catch {
456
+ return void 0;
457
+ }
458
+ }
459
+ function buildGithubPrSnapshot(value, now = Date.now()) {
460
+ try {
461
+ const pr = record(value);
462
+ const number = positiveInteger(pr.number);
463
+ const isDraft = requiredBoolean(pr.isDraft);
464
+ const url = requiredBoundedString(pr.url, MAX_URL_LENGTH, true);
465
+ const state = pullRequestState(pr.state);
466
+ const closedAt = optionalTimestamp(pr.closedAt);
467
+ const mergedAt = optionalTimestamp(pr.mergedAt);
468
+ const reviewDecision = reviewDecisionValue(pr.reviewDecision);
469
+ const checks = summarizeChecks(pr.statusCheckRollup);
470
+ const expiresAt = terminalExpiry(state, closedAt, mergedAt);
471
+ if (state !== "OPEN" && (expiresAt === void 0 || now >= expiresAt)) return void 0;
472
+ const presentationState = state === "MERGED" ? "merged" : state === "CLOSED" ? "closed" : isDraft ? "draft" : "open";
473
+ const checksText = formatChecks(checks);
474
+ const review = formatReview(reviewDecision);
475
+ const status = compactStatus(presentationState, checks, checksText, review);
476
+ const snapshot = {
477
+ number: String(number),
478
+ link: osc8Link(url, `#${number}`),
479
+ state: presentationState,
480
+ checks: checksText,
481
+ review,
482
+ status,
483
+ ...expiresAt === void 0 ? {} : { expiresAt }
484
+ };
485
+ return Object.freeze(snapshot);
486
+ } catch {
487
+ return void 0;
488
+ }
489
+ }
490
+ function githubPrSnapshotEqual(left, right) {
491
+ return JSON.stringify(left) === JSON.stringify(right);
492
+ }
493
+ function terminalExpiry(state, closedAt, mergedAt) {
494
+ if (state === "OPEN") return void 0;
495
+ const terminalAt = state === "MERGED" ? mergedAt : closedAt;
496
+ return terminalAt === void 0 ? void 0 : terminalAt + TERMINAL_PR_LIFETIME_MS;
497
+ }
498
+ function summarizeChecks(value) {
499
+ if (!Array.isArray(value) || value.length > MAX_CHECKS) throw new Error("Invalid PR checks");
500
+ const summary = { failed: 0, pending: 0, total: value.length };
501
+ for (const item of value) {
502
+ const check = record(item);
503
+ const state = optionalUppercase(check.state);
504
+ const status = optionalUppercase(check.status);
505
+ const conclusion = optionalUppercase(check.conclusion);
506
+ if (state === "SUCCESS") continue;
507
+ if (state === "FAILURE" || state === "ERROR") {
508
+ summary.failed += 1;
509
+ continue;
510
+ }
511
+ if (state === "PENDING" || state === "EXPECTED") {
512
+ summary.pending += 1;
513
+ continue;
514
+ }
515
+ if (status && status !== "COMPLETED") {
516
+ summary.pending += 1;
517
+ continue;
518
+ }
519
+ if (conclusion === "SUCCESS" || conclusion === "SKIPPED" || conclusion === "NEUTRAL") {
520
+ continue;
521
+ }
522
+ if (conclusion === "FAILURE" || conclusion === "CANCELLED" || conclusion === "TIMED_OUT" || conclusion === "ACTION_REQUIRED" || conclusion === "STARTUP_FAILURE") {
523
+ summary.failed += 1;
524
+ continue;
525
+ }
526
+ summary.pending += 1;
527
+ }
528
+ return summary;
529
+ }
530
+ function formatChecks(checks) {
531
+ if (checks.total === 0) return "no checks";
532
+ if (checks.failed > 0) return `${checks.failed} failing`;
533
+ if (checks.pending > 0) return `${checks.pending} pending`;
534
+ return "checks passing";
535
+ }
536
+ function formatReview(review) {
537
+ if (review === "APPROVED") return "approved";
538
+ if (review === "CHANGES_REQUESTED") return "changes requested";
539
+ if (review === "REVIEW_REQUIRED") return "review required";
540
+ return "";
541
+ }
542
+ function compactStatus(state, checks, checksText, review) {
543
+ if (state === "merged" || state === "closed" || state === "draft") return state;
544
+ if (checks.failed > 0) return checksText;
545
+ if (review === "changes requested") return review;
546
+ if (checks.pending > 0) return checksText;
547
+ if (review === "approved" || review === "review required") return review;
548
+ return checksText;
549
+ }
550
+ function osc8Link(value, label) {
551
+ if (hasTerminalControls(value)) return label;
552
+ try {
553
+ const url = new URL(value);
554
+ if (url.protocol !== "http:" && url.protocol !== "https:" || url.username || url.password) {
555
+ return label;
556
+ }
557
+ const normalized = url.toString();
558
+ if (normalized.length > MAX_URL_LENGTH || hasTerminalControls(normalized)) return label;
559
+ return `\x1B]8;;${normalized}\x07${label}\x1B]8;;\x07`;
560
+ } catch {
561
+ return label;
562
+ }
563
+ }
564
+ function hasTerminalControls(value) {
565
+ return Array.from(value).some((character) => {
566
+ const codePoint = character.codePointAt(0) ?? 0;
567
+ return codePoint <= 31 || codePoint >= 127 && codePoint <= 159 || codePoint >= 55296 && codePoint <= 57343;
568
+ });
569
+ }
570
+ function record(value) {
571
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
572
+ throw new Error("Expected PR object");
573
+ }
574
+ return value;
575
+ }
576
+ function positiveInteger(value) {
577
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
578
+ throw new Error("Invalid PR number");
579
+ }
580
+ return value;
581
+ }
582
+ function requiredBoolean(value) {
583
+ if (typeof value !== "boolean") throw new Error("Invalid PR boolean");
584
+ return value;
585
+ }
586
+ function requiredBoundedString(value, maxLength, allowEmpty = false) {
587
+ if (typeof value !== "string" || value.length > maxLength || !allowEmpty && value.length === 0) {
588
+ throw new Error("Invalid PR string");
589
+ }
590
+ return value;
591
+ }
592
+ function optionalUppercase(value) {
593
+ if (value === null || value === void 0 || value === "") return void 0;
594
+ return requiredBoundedString(value, MAX_FIELD_LENGTH).toUpperCase();
595
+ }
596
+ function optionalTimestamp(value) {
597
+ if (value === null || value === void 0 || value === "") return void 0;
598
+ const text = requiredBoundedString(value, MAX_FIELD_LENGTH);
599
+ const match = RFC3339_TIMESTAMP.exec(text);
600
+ if (!match) throw new Error("Invalid PR timestamp");
601
+ const [
602
+ ,
603
+ yearText,
604
+ monthText,
605
+ dayText,
606
+ hourText,
607
+ minuteText,
608
+ secondText,
609
+ offsetHourText,
610
+ offsetMinuteText
611
+ ] = match;
612
+ const year = Number(yearText);
613
+ const month = Number(monthText);
614
+ const day = Number(dayText);
615
+ const hour = Number(hourText);
616
+ const minute = Number(minuteText);
617
+ const second = Number(secondText);
618
+ const offsetHour = Number(offsetHourText ?? 0);
619
+ const offsetMinute = Number(offsetMinuteText ?? 0);
620
+ if (month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month) || hour > 23 || minute > 59 || second > 59 || offsetHour > 23 || offsetMinute > 59) {
621
+ throw new Error("Invalid PR timestamp");
622
+ }
623
+ const timestamp = Date.parse(text);
624
+ if (!Number.isFinite(timestamp)) throw new Error("Invalid PR timestamp");
625
+ return timestamp;
626
+ }
627
+ function daysInMonth(year, month) {
628
+ if (month === 2) {
629
+ const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
630
+ return leapYear ? 29 : 28;
631
+ }
632
+ return month === 4 || month === 6 || month === 9 || month === 11 ? 30 : 31;
633
+ }
634
+ function pullRequestState(value) {
635
+ if (value === "OPEN" || value === "CLOSED" || value === "MERGED") return value;
636
+ throw new Error("Invalid PR state");
637
+ }
638
+ function reviewDecisionValue(value) {
639
+ if (value === null || value === void 0 || value === "" || value === "UNKNOWN") return "";
640
+ if (value === "APPROVED" || value === "CHANGES_REQUESTED" || value === "REVIEW_REQUIRED") {
641
+ return value;
642
+ }
643
+ throw new Error("Invalid PR review decision");
644
+ }
645
+
646
+ // src/runtime/refresh-controller.ts
647
+ var AsyncRefreshController = class {
648
+ constructor(options) {
649
+ this.options = options;
650
+ }
651
+ options;
652
+ generation;
653
+ requestId = 0;
654
+ active;
655
+ pending;
656
+ current;
657
+ start(generation) {
658
+ this.cancelActive("Refresh generation replaced");
659
+ this.generation = generation;
660
+ this.requestId += 1;
661
+ this.pending = void 0;
662
+ this.current = void 0;
663
+ }
664
+ clear() {
665
+ this.current = void 0;
666
+ }
667
+ request(input) {
668
+ if (this.generation === void 0) return;
669
+ const request = {
670
+ generation: this.generation,
671
+ requestId: ++this.requestId,
672
+ input
673
+ };
674
+ if (this.active) {
675
+ this.pending = request;
676
+ return;
677
+ }
678
+ this.run(request);
679
+ }
680
+ stop() {
681
+ this.generation = void 0;
682
+ this.requestId += 1;
683
+ this.pending = void 0;
684
+ this.current = void 0;
685
+ this.cancelActive("Refresh controller stopped");
686
+ }
687
+ run(request) {
688
+ if (!this.isCurrentTarget(request)) return;
689
+ const active = {
690
+ request,
691
+ controller: new AbortController()
692
+ };
693
+ this.active = active;
694
+ void this.options.read(request.input, active.controller.signal).then((snapshot) => {
695
+ if (this.active !== active || !this.isCurrentRequest(request)) return;
696
+ if (this.options.equal(this.current, snapshot)) return;
697
+ this.current = snapshot;
698
+ this.options.publish(snapshot);
699
+ }).catch((error) => {
700
+ if (this.active === active && this.isCurrentRequest(request) && !active.controller.signal.aborted) {
701
+ this.options.onError?.(error);
702
+ }
703
+ }).finally(() => {
704
+ if (this.active !== active) return;
705
+ this.active = void 0;
706
+ const pending = this.pending;
707
+ this.pending = void 0;
708
+ if (pending) this.run(pending);
709
+ });
710
+ }
711
+ cancelActive(reason) {
712
+ this.active?.controller.abort(new DOMException(reason, "AbortError"));
713
+ }
714
+ isCurrentTarget(request) {
715
+ return this.generation !== void 0 && request.generation === this.generation;
716
+ }
717
+ isCurrentRequest(request) {
718
+ return this.isCurrentTarget(request) && request.requestId === this.requestId;
719
+ }
720
+ };
721
+
722
+ // src/runtime/workspace.ts
723
+ async function collectWorkspaceSnapshot(input) {
724
+ const requirements = reachableModuleRequirements(input.config);
725
+ if (input.signal?.aborted || !hasWorkspaceRequirement(requirements)) return freezeSnapshot({});
726
+ const fs = createFileSystem(input);
727
+ let listing;
728
+ const context = {
729
+ input,
730
+ fs,
731
+ requirements,
732
+ entries() {
733
+ listing ??= fs.readDirectory(input.cwd);
734
+ return listing;
735
+ },
736
+ options(name) {
737
+ return input.config.modules[name].options;
738
+ },
739
+ needs(name, variable) {
740
+ const variables = requirements.get(name);
741
+ return Boolean(variables && (variable === void 0 || variables.has(variable)));
742
+ }
743
+ };
744
+ const modules = {};
745
+ if (requirements.has("package")) {
746
+ const { collectPackage } = await import("./chunks/package-MXN2YFLX.js");
747
+ if (input.signal?.aborted) return freezeSnapshot({});
748
+ const packageValues = await collectPackage(context);
749
+ if (input.signal?.aborted) return freezeSnapshot({});
750
+ if (packageValues) modules.package = packageValues;
751
+ }
752
+ for (const descriptor of COLLECTOR_GROUPS) {
753
+ if (!descriptor.modules.some((name) => requirements.has(name))) continue;
754
+ if (input.signal?.aborted) return freezeSnapshot({});
755
+ const collector = await descriptor.load();
756
+ if (input.signal?.aborted) return freezeSnapshot({});
757
+ mergeModules(modules, await collector(context));
758
+ }
759
+ return input.signal?.aborted ? freezeSnapshot({}) : freezeSnapshot(modules);
760
+ }
761
+ function workspaceSnapshotEqual(left, right) {
762
+ return JSON.stringify(left) === JSON.stringify(right);
763
+ }
764
+ function hasWorkspaceRequirement(requirements) {
765
+ return [...requirements.keys()].some((name) => !BUILT_IN_ONLY_MODULES.has(name));
766
+ }
767
+ var COLLECTOR_GROUPS = [
768
+ {
769
+ modules: ["nodejs", "python", "rust", "golang", "bun", "deno"],
770
+ load: async () => (await import("./chunks/languages-DPWDCH6Q.js")).collectLanguages
771
+ },
772
+ {
773
+ modules: ["mise", "direnv", "pixi", "conda", "nix_shell", "guix_shell"],
774
+ load: async () => (await import("./chunks/development-TNWZ5SRC.js")).collectDevelopment
775
+ },
776
+ {
777
+ modules: ["docker_context", "kubernetes", "terraform"],
778
+ load: async () => (await import("./chunks/deployment-ZNYM4B6W.js")).collectDeployment
779
+ },
780
+ {
781
+ modules: ["aws", "gcloud", "azure", "openstack"],
782
+ load: async () => (await import("./chunks/cloud-JBSZWTB6.js")).collectCloud
783
+ },
784
+ {
785
+ modules: ["container", "hostname", "os", "username"],
786
+ load: async () => (await import("./chunks/execution-QHAP4U33.js")).collectExecution
787
+ }
788
+ ];
789
+ var BUILT_IN_ONLY_MODULES = /* @__PURE__ */ new Set([
790
+ "brand",
791
+ "provider",
792
+ "model",
793
+ "thinking",
794
+ "directory",
795
+ "git_worktree",
796
+ "git_branch",
797
+ "github_pr",
798
+ "git_commit",
799
+ "git_state",
800
+ "git_metrics",
801
+ "git_status",
802
+ "activity",
803
+ "context",
804
+ "tokens",
805
+ "cost",
806
+ "time",
807
+ "turn",
808
+ "fill",
809
+ "extension_status"
810
+ ]);
811
+ function mergeModules(target, source) {
812
+ for (const [name, values] of Object.entries(source)) {
813
+ Object.defineProperty(target, name, {
814
+ value: values,
815
+ writable: true,
816
+ enumerable: true,
817
+ configurable: true
818
+ });
819
+ }
820
+ }
821
+ function freezeSnapshot(modules) {
822
+ const styleSelectors = {};
823
+ for (const [name, values] of Object.entries(modules)) {
824
+ const selector = Object.hasOwn(values, PRIVATE_STYLE_SELECTOR) ? values[PRIVATE_STYLE_SELECTOR] : void 0;
825
+ delete values[PRIVATE_STYLE_SELECTOR];
826
+ if (selector !== void 0) styleSelectors[name] = selector;
827
+ Object.freeze(values);
828
+ }
829
+ return Object.freeze({
830
+ modules: Object.freeze(modules),
831
+ ...Object.keys(styleSelectors).length > 0 ? { styleSelectors: Object.freeze(styleSelectors) } : {}
832
+ });
833
+ }
834
+
835
+ // src/usage.ts
836
+ function summarizeFooterUsage(entries) {
837
+ const totals = {
838
+ input: 0,
839
+ output: 0,
840
+ cacheRead: 0,
841
+ cacheWrite: 0,
842
+ cost: 0
843
+ };
844
+ for (const entry of entries) {
845
+ let usage;
846
+ if (entry.type === "message" && entry.message.role === "assistant") {
847
+ usage = entry.message.usage;
848
+ const input = usage.input ?? 0;
849
+ const cacheRead = usage.cacheRead ?? 0;
850
+ const cacheWrite = usage.cacheWrite ?? 0;
851
+ const promptTokens = input + cacheRead + cacheWrite;
852
+ totals.latestCacheHitRate = promptTokens > 0 ? cacheRead / promptTokens * 100 : void 0;
853
+ } else if (entry.type === "message" && entry.message.role === "toolResult") {
854
+ usage = entry.message.usage;
855
+ } else if (entry.type === "compaction" || entry.type === "branch_summary") {
856
+ usage = entry.usage;
857
+ }
858
+ if (!usage) continue;
859
+ totals.input += usage.input ?? 0;
860
+ totals.output += usage.output ?? 0;
861
+ totals.cacheRead += usage.cacheRead ?? 0;
862
+ totals.cacheWrite += usage.cacheWrite ?? 0;
863
+ totals.cost += usage.cost?.total ?? 0;
864
+ }
865
+ return totals;
866
+ }
867
+
868
+ // src/pi-starship.ts
869
+ var REFRESH_INTERVAL_MS = 3e4;
870
+ var GITHUB_PR_REFRESH_INTERVAL_MS = 6e4;
871
+ var EVENT_DEBOUNCE_MS = 250;
872
+ var MAX_TIMER_DELAY_MS = 2147483647;
873
+ var starshipCommandsPromise;
874
+ function loadStarshipCommands() {
875
+ if (!starshipCommandsPromise) {
876
+ starshipCommandsPromise = import("./chunks/commands-BSQZ2R4M.js").catch((error) => {
877
+ starshipCommandsPromise = void 0;
878
+ throw error;
879
+ });
880
+ }
881
+ return starshipCommandsPromise;
882
+ }
883
+ function piStarship(pi, options = {}) {
884
+ let loaded;
885
+ const runtime = {
886
+ activeTools: /* @__PURE__ */ new Map(),
887
+ isStreaming: false,
888
+ thinkingLevel: "off"
889
+ };
890
+ let sessionGeneration = 0;
891
+ let menuController = new AbortController();
892
+ let sessionOwner;
893
+ let activeTarget;
894
+ let eventDebounceTimer;
895
+ let githubPrRefreshTimer;
896
+ let githubPrExpiryTimer;
897
+ let githubPrGeneration = 0;
898
+ const refresh = () => runtime.requestRender?.();
899
+ const githubPrExec = options.githubPrExec ?? execWorkspaceCommand;
900
+ const gitController = new AsyncRefreshController({
901
+ async read(input, signal) {
902
+ const requirements = reachableModuleRequirements(input.config);
903
+ const gitReachable = [...requirements.keys()].some((name) => name.startsWith("git_")) || requirements.has("directory") && input.config.modules.directory.options.truncate_to_repo === true;
904
+ if (!gitReachable) return void 0;
905
+ try {
906
+ return await readGitSnapshot(pi, input.cwd, {
907
+ includeMetrics: requirements.has("git_metrics"),
908
+ includeTag: requirements.get("git_commit")?.has("tag") ?? false,
909
+ signal
910
+ });
911
+ } catch {
912
+ return void 0;
913
+ }
914
+ },
915
+ equal: gitSnapshotEqual,
916
+ publish(snapshot) {
917
+ runtime.git = snapshot;
918
+ refresh();
919
+ }
920
+ });
921
+ const githubPrController = new AsyncRefreshController({
922
+ read: (input, signal) => queryGithubPr(githubPrExec, input.cwd, signal),
923
+ equal: githubPrSnapshotEqual,
924
+ publish(snapshot) {
925
+ runtime.githubPr = snapshot;
926
+ scheduleGithubPrExpiry(snapshot);
927
+ refresh();
928
+ }
929
+ });
930
+ const workspaceController = new AsyncRefreshController({
931
+ async read(input, signal) {
932
+ try {
933
+ return await collectWorkspaceSnapshot({ ...input, signal });
934
+ } catch {
935
+ return { modules: {} };
936
+ }
937
+ },
938
+ equal: workspaceSnapshotEqual,
939
+ publish(snapshot) {
940
+ runtime.workspace = snapshot;
941
+ refresh();
942
+ }
943
+ });
944
+ const clearDebounce = () => {
945
+ if (!eventDebounceTimer) return;
946
+ clearTimeout(eventDebounceTimer);
947
+ eventDebounceTimer = void 0;
948
+ };
949
+ const isActiveTarget = (target) => activeTarget?.cwd === target.cwd && activeTarget.generation === target.generation && activeTarget.sessionManager === target.sessionManager && target.generation === sessionGeneration;
950
+ const requestRefresh = (target, reason = "event") => {
951
+ if (!loaded || !isActiveTarget(target)) return;
952
+ gitController.request({ cwd: target.cwd, config: loaded.config });
953
+ workspaceController.request(
954
+ workspaceInput(target.cwd, loaded.config, reason, runtime.workspace)
955
+ );
956
+ };
957
+ const scheduleRefresh = (ctx) => {
958
+ const target = activeTarget;
959
+ if (!target || target.cwd !== ctx.cwd || target.sessionManager !== ctx.sessionManager) {
960
+ return;
961
+ }
962
+ clearDebounce();
963
+ eventDebounceTimer = setTimeout(() => {
964
+ eventDebounceTimer = void 0;
965
+ requestRefresh(target);
966
+ }, EVENT_DEBOUNCE_MS);
967
+ };
968
+ function restartLocalControllers(target) {
969
+ if (!isActiveTarget(target)) return;
970
+ gitController.start(target.generation);
971
+ workspaceController.start(target.generation);
972
+ }
973
+ function clearGithubPrTimers() {
974
+ if (githubPrRefreshTimer) clearInterval(githubPrRefreshTimer);
975
+ if (githubPrExpiryTimer) clearTimeout(githubPrExpiryTimer);
976
+ githubPrRefreshTimer = void 0;
977
+ githubPrExpiryTimer = void 0;
978
+ }
979
+ function stopGithubPr() {
980
+ clearGithubPrTimers();
981
+ githubPrController.stop();
982
+ runtime.githubPr = void 0;
983
+ }
984
+ function githubPrReachable() {
985
+ return Boolean(loaded && reachableModuleRequirements(loaded.config).has("github_pr"));
986
+ }
987
+ function startGithubPr(target) {
988
+ if (!isActiveTarget(target)) return false;
989
+ stopGithubPr();
990
+ if (!githubPrReachable()) return false;
991
+ githubPrController.start(++githubPrGeneration);
992
+ githubPrRefreshTimer = setInterval(() => {
993
+ requestGithubPr(target);
994
+ }, GITHUB_PR_REFRESH_INTERVAL_MS);
995
+ githubPrRefreshTimer.unref?.();
996
+ return true;
997
+ }
998
+ function requestGithubPr(target) {
999
+ if (!isActiveTarget(target) || !githubPrReachable()) return;
1000
+ githubPrController.request({ cwd: target.cwd });
1001
+ }
1002
+ function scheduleGithubPrExpiry(snapshot) {
1003
+ if (githubPrExpiryTimer) clearTimeout(githubPrExpiryTimer);
1004
+ githubPrExpiryTimer = void 0;
1005
+ if (snapshot?.expiresAt === void 0) return;
1006
+ const target = activeTarget;
1007
+ if (!target) return;
1008
+ const delay = snapshot.expiresAt - Date.now();
1009
+ if (delay <= 0) {
1010
+ runtime.githubPr = void 0;
1011
+ githubPrController.clear();
1012
+ refresh();
1013
+ return;
1014
+ }
1015
+ githubPrExpiryTimer = setTimeout(
1016
+ () => {
1017
+ githubPrExpiryTimer = void 0;
1018
+ if (!isActiveTarget(target) || runtime.githubPr !== snapshot) return;
1019
+ scheduleGithubPrExpiry(snapshot);
1020
+ },
1021
+ Math.min(delay, MAX_TIMER_DELAY_MS)
1022
+ );
1023
+ githubPrExpiryTimer.unref?.();
1024
+ }
1025
+ const installFooter = (ctx) => {
1026
+ const generation = ++sessionGeneration;
1027
+ sessionOwner = ctx.sessionManager;
1028
+ menuController.abort(new DOMException("Starship session context replaced", "AbortError"));
1029
+ menuController = new AbortController();
1030
+ const target = { cwd: ctx.cwd, generation, sessionManager: ctx.sessionManager };
1031
+ clearDebounce();
1032
+ gitController.stop();
1033
+ workspaceController.stop();
1034
+ stopGithubPr();
1035
+ runtime.git = void 0;
1036
+ runtime.workspace = void 0;
1037
+ runtime.requestRender = void 0;
1038
+ runtime.renderPreview = void 0;
1039
+ runtime.inspect = void 0;
1040
+ runtime.footerWidth = void 0;
1041
+ activeTarget = ctx.mode === "tui" ? target : void 0;
1042
+ ctx.ui.setStatus("starship", void 0);
1043
+ if (!activeTarget || !loaded) return;
1044
+ gitController.start(generation);
1045
+ workspaceController.start(generation);
1046
+ startGithubPr(target);
1047
+ ctx.ui.setFooter((tui, _theme, footerData) => {
1048
+ runtime.requestRender = () => tui.requestRender();
1049
+ runtime.renderPreview = (preview, width) => {
1050
+ const snapshot = runtimeSnapshot(ctx, footerData, runtime);
1051
+ return wrapFormattedStatusline(
1052
+ renderStatusline(preview.config, snapshot, width).ansi,
1053
+ width
1054
+ );
1055
+ };
1056
+ runtime.inspect = (current) => inspectStatuslineModules(
1057
+ current.config,
1058
+ runtimeSnapshot(ctx, footerData, runtime),
1059
+ runtime.footerWidth ?? 80
1060
+ );
1061
+ const unsubscribe = footerData.onBranchChange(() => {
1062
+ if (!isActiveTarget(target)) return;
1063
+ runtime.git = void 0;
1064
+ restartLocalControllers(target);
1065
+ clearDebounce();
1066
+ startGithubPr(target);
1067
+ requestRefresh(target);
1068
+ requestGithubPr(target);
1069
+ tui.requestRender();
1070
+ });
1071
+ const timer = setInterval(() => {
1072
+ if (!isActiveTarget(target)) return;
1073
+ clearDebounce();
1074
+ requestRefresh(target, "periodic");
1075
+ tui.requestRender();
1076
+ }, REFRESH_INTERVAL_MS);
1077
+ let disposed = false;
1078
+ return {
1079
+ dispose() {
1080
+ if (disposed) return;
1081
+ disposed = true;
1082
+ unsubscribe();
1083
+ clearInterval(timer);
1084
+ if (isActiveTarget(target)) {
1085
+ activeTarget = void 0;
1086
+ clearDebounce();
1087
+ gitController.stop();
1088
+ workspaceController.stop();
1089
+ stopGithubPr();
1090
+ runtime.git = void 0;
1091
+ runtime.workspace = void 0;
1092
+ runtime.requestRender = void 0;
1093
+ runtime.renderPreview = void 0;
1094
+ runtime.inspect = void 0;
1095
+ runtime.footerWidth = void 0;
1096
+ }
1097
+ },
1098
+ invalidate() {
1099
+ },
1100
+ render(width) {
1101
+ runtime.footerWidth = width;
1102
+ if (!loaded) return [];
1103
+ const snapshot = runtimeSnapshot(ctx, footerData, runtime);
1104
+ return wrapFormattedStatusline(
1105
+ renderStatusline(loaded.config, snapshot, width).ansi,
1106
+ width
1107
+ );
1108
+ }
1109
+ };
1110
+ });
1111
+ requestRefresh(target, "initial");
1112
+ requestGithubPr(target);
1113
+ };
1114
+ const configPath = settingsFilePath(getAgentDir());
1115
+ const commandOptions = {
1116
+ settingsPath: configPath,
1117
+ getLoaded: () => loaded ?? loadStarshipConfig(configPath),
1118
+ getInspection: () => {
1119
+ const current = loaded ?? loadStarshipConfig(configPath);
1120
+ return runtime.inspect?.(current);
1121
+ },
1122
+ getMenuOwner: () => {
1123
+ const generation = sessionGeneration;
1124
+ return {
1125
+ signal: menuController.signal,
1126
+ isCurrent: () => generation === sessionGeneration && !menuController.signal.aborted
1127
+ };
1128
+ },
1129
+ apply(next, ctx) {
1130
+ if (sessionOwner !== ctx.sessionManager) {
1131
+ throw new Error("Starship session context was replaced");
1132
+ }
1133
+ loaded = next;
1134
+ const target = activeTarget;
1135
+ if (target) {
1136
+ restartLocalControllers(target);
1137
+ startGithubPr(target);
1138
+ requestRefresh(target);
1139
+ requestGithubPr(target);
1140
+ }
1141
+ refresh();
1142
+ },
1143
+ renderPreview(preview, width) {
1144
+ return runtime.renderPreview?.(preview, width) ?? [
1145
+ "Live preview is unavailable until the footer is ready."
1146
+ ];
1147
+ }
1148
+ };
1149
+ pi.registerCommand("starship", {
1150
+ description: "Customize or inspect the native Starship-style footer",
1151
+ getArgumentCompletions: completeStarshipArguments,
1152
+ handler: async (args, ctx) => {
1153
+ const commands = await loadStarshipCommands();
1154
+ if (sessionOwner !== ctx.sessionManager) return;
1155
+ await commands.handleStarshipCommand(args, ctx, commandOptions);
1156
+ }
1157
+ });
1158
+ pi.on("session_start", (_event, ctx) => {
1159
+ loaded = loadStarshipConfig(configPath);
1160
+ if (loaded.diagnostics.length > 0 && (ctx.mode === "tui" || ctx.hasUI)) {
1161
+ ctx.ui.notify(formatDiagnostics(loaded), "warning");
1162
+ }
1163
+ runtime.thinkingLevel = pi.getThinkingLevel();
1164
+ installFooter(ctx);
1165
+ });
1166
+ pi.on("session_tree", (_event, ctx) => {
1167
+ installFooter(ctx);
1168
+ refresh();
1169
+ });
1170
+ pi.on("session_shutdown", (_event, ctx) => {
1171
+ if (sessionOwner !== ctx.sessionManager) return;
1172
+ sessionOwner = void 0;
1173
+ sessionGeneration += 1;
1174
+ menuController.abort(new DOMException("Starship session shut down", "AbortError"));
1175
+ activeTarget = void 0;
1176
+ clearDebounce();
1177
+ gitController.stop();
1178
+ workspaceController.stop();
1179
+ stopGithubPr();
1180
+ runtime.git = void 0;
1181
+ runtime.workspace = void 0;
1182
+ runtime.requestRender = void 0;
1183
+ runtime.renderPreview = void 0;
1184
+ runtime.inspect = void 0;
1185
+ runtime.footerWidth = void 0;
1186
+ ctx.ui.setFooter(void 0);
1187
+ ctx.ui.setStatus("starship", void 0);
1188
+ });
1189
+ pi.on("model_select", () => refresh());
1190
+ pi.on("thinking_level_select", (event) => {
1191
+ runtime.thinkingLevel = event.level;
1192
+ refresh();
1193
+ });
1194
+ pi.on("agent_start", () => {
1195
+ runtime.isStreaming = true;
1196
+ refresh();
1197
+ });
1198
+ pi.on("agent_end", (_event, ctx) => {
1199
+ runtime.isStreaming = false;
1200
+ scheduleRefresh(ctx);
1201
+ const target = activeTarget;
1202
+ if (target?.sessionManager === ctx.sessionManager) requestGithubPr(target);
1203
+ refresh();
1204
+ });
1205
+ pi.on("turn_start", () => {
1206
+ runtime.isStreaming = true;
1207
+ refresh();
1208
+ });
1209
+ pi.on("turn_end", (_event, ctx) => {
1210
+ scheduleRefresh(ctx);
1211
+ refresh();
1212
+ });
1213
+ pi.on("tool_execution_start", (event) => {
1214
+ runtime.activeTools.set(event.toolName, (runtime.activeTools.get(event.toolName) ?? 0) + 1);
1215
+ refresh();
1216
+ });
1217
+ pi.on("tool_execution_end", (event, ctx) => {
1218
+ const count = runtime.activeTools.get(event.toolName) ?? 0;
1219
+ if (count <= 1) runtime.activeTools.delete(event.toolName);
1220
+ else runtime.activeTools.set(event.toolName, count - 1);
1221
+ runtime.lastCompletedTool = event.toolName;
1222
+ scheduleRefresh(ctx);
1223
+ refresh();
1224
+ });
1225
+ }
1226
+ function workspaceInput(cwd, config, reason, previous) {
1227
+ return {
1228
+ cwd,
1229
+ config,
1230
+ environment: allowlistedEnvironment(config),
1231
+ homeDir: homedir(),
1232
+ platform: process.platform,
1233
+ hostname: hostname(),
1234
+ username: safeUsername(),
1235
+ exec: execWorkspaceCommand,
1236
+ reason,
1237
+ previous
1238
+ };
1239
+ }
1240
+ var ENVIRONMENT_ALLOWLIST = [
1241
+ "AWS_CONFIG_FILE",
1242
+ "AWS_DEFAULT_PROFILE",
1243
+ "AWS_DEFAULT_REGION",
1244
+ "AWS_PROFILE",
1245
+ "AWS_REGION",
1246
+ "AZURE_CONFIG_DIR",
1247
+ "CLOUDSDK_ACTIVE_CONFIG_NAME",
1248
+ "CLOUDSDK_CONFIG",
1249
+ "CODESPACES",
1250
+ "CONDA_DEFAULT_ENV",
1251
+ "DOCKER_CONFIG",
1252
+ "DOCKER_CONTEXT",
1253
+ "GUIX_ENVIRONMENT",
1254
+ "IN_NIX_SHELL",
1255
+ "KUBECONFIG",
1256
+ "LOGNAME",
1257
+ "NIX_SHELL_LEVEL",
1258
+ "NIX_SHELL_NAME",
1259
+ "OS_CLIENT_CONFIG_FILE",
1260
+ "OS_CLOUD",
1261
+ "OS_PROJECT_NAME",
1262
+ "PATH",
1263
+ "PIXI_ENVIRONMENT_NAME",
1264
+ "PIXI_PROJECT_NAME",
1265
+ "PYENV_VERSION",
1266
+ "REMOTE_CONTAINERS",
1267
+ "RUSTC",
1268
+ "RUSTUP_TOOLCHAIN",
1269
+ "SSH_CONNECTION",
1270
+ "SSH_TTY",
1271
+ "TF_DATA_DIR",
1272
+ "TF_WORKSPACE",
1273
+ "USER",
1274
+ "USERNAME",
1275
+ "VIRTUAL_ENV",
1276
+ "WSL_DISTRO_NAME"
1277
+ ];
1278
+ function allowlistedEnvironment(config) {
1279
+ const result = {};
1280
+ const configured = config.modules.username.options.detect_env_vars;
1281
+ const names = /* @__PURE__ */ new Set([
1282
+ ...ENVIRONMENT_ALLOWLIST,
1283
+ ...Array.isArray(configured) ? configured.filter((name) => typeof name === "string") : []
1284
+ ]);
1285
+ for (const name of names) result[name] = process.env[name];
1286
+ return result;
1287
+ }
1288
+ function safeUsername() {
1289
+ try {
1290
+ return userInfo().username;
1291
+ } catch {
1292
+ return process.env.USER ?? process.env.USERNAME ?? "";
1293
+ }
1294
+ }
1295
+ function runtimeSnapshot(ctx, footerData, runtime) {
1296
+ return {
1297
+ cwd: ctx.cwd,
1298
+ homeDir: homedir(),
1299
+ gitRoot: runtime.git?.root,
1300
+ model: ctx.model ? { provider: ctx.model.provider, id: ctx.model.id } : void 0,
1301
+ thinkingLevel: runtime.thinkingLevel,
1302
+ turnCount: userTurnCount(ctx),
1303
+ activeTools: runtime.activeTools,
1304
+ isStreaming: runtime.isStreaming,
1305
+ lastCompletedTool: runtime.lastCompletedTool,
1306
+ contextUsage: ctx.getContextUsage() ?? void 0,
1307
+ tokenTotals: summarizeFooterUsage(ctx.sessionManager.getEntries()),
1308
+ usingSubscription: isSubscriptionBacked(ctx),
1309
+ gitBranch: runtime.git?.branch?.name ?? footerData.getGitBranch(),
1310
+ gitBranchDetails: runtime.git?.branch,
1311
+ gitCommit: runtime.git?.commit,
1312
+ gitState: runtime.git?.state,
1313
+ gitMetrics: runtime.git?.metrics,
1314
+ gitStatus: runtime.git?.status,
1315
+ gitWorktree: runtime.git?.worktree,
1316
+ githubPr: runtime.githubPr,
1317
+ workspace: runtime.workspace,
1318
+ extensionStatuses: footerData.getExtensionStatuses(),
1319
+ now: /* @__PURE__ */ new Date()
1320
+ };
1321
+ }
1322
+ function userTurnCount(ctx) {
1323
+ return ctx.sessionManager.getBranch().filter((entry) => entry.type === "message" && entry.message.role === "user").length;
1324
+ }
1325
+ function isSubscriptionBacked(ctx) {
1326
+ const model = ctx.model;
1327
+ return model !== void 0 && (model.provider === "kimi-coding" || ctx.modelRegistry.isUsingOAuth(model));
1328
+ }
1329
+ function formatDiagnostics(loaded) {
1330
+ const details = loaded.diagnostics.slice(0, 5).map((item) => item.message);
1331
+ const remaining = loaded.diagnostics.length - details.length;
1332
+ return [
1333
+ `pi-starship settings: ${details.join("; ")}`,
1334
+ ...remaining > 0 ? [`+${remaining} more`] : []
1335
+ ].join(" ");
1336
+ }
1337
+ function wrapFormattedStatusline(format, width) {
1338
+ if (width <= 0) return [];
1339
+ return wrapTextWithAnsi(format, width);
1340
+ }
1341
+ export {
1342
+ piStarship as default,
1343
+ parseGitDiffShortstat,
1344
+ parseGitState,
1345
+ parseGitStatusPorcelain,
1346
+ parseGitStatusPorcelainV2,
1347
+ parseGitWorktree,
1348
+ wrapFormattedStatusline
1349
+ };
1350
+ //# sourceMappingURL=pi-starship.ts.map