@narumitw/pi-starship 0.60.1 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.md +67 -9
  2. package/dist/chunks/chunk-63R6R5DH.ts +679 -0
  3. package/dist/chunks/chunk-63R6R5DH.ts.map +7 -0
  4. package/dist/chunks/{chunk-KZZKGGFW.ts → chunk-A65IOGL6.ts} +858 -1007
  5. package/dist/chunks/chunk-A65IOGL6.ts.map +7 -0
  6. package/dist/chunks/chunk-IYDZ3R2T.ts +69 -0
  7. package/dist/chunks/chunk-IYDZ3R2T.ts.map +7 -0
  8. package/dist/chunks/chunk-KP33I6BR.ts +579 -0
  9. package/dist/chunks/chunk-KP33I6BR.ts.map +7 -0
  10. package/dist/chunks/{chunk-PD457PX5.ts → chunk-S2KBLHE2.ts} +75 -10
  11. package/dist/chunks/chunk-S2KBLHE2.ts.map +7 -0
  12. package/dist/chunks/chunk-XQUIQO2G.ts +20 -0
  13. package/dist/chunks/chunk-XQUIQO2G.ts.map +7 -0
  14. package/dist/chunks/{chunk-ADX4CY27.ts → chunk-XTLQ4WUL.ts} +1 -1
  15. package/dist/chunks/chunk-XTLQ4WUL.ts.map +7 -0
  16. package/dist/chunks/chunk-Y24TJYG6.ts +1586 -0
  17. package/dist/chunks/chunk-Y24TJYG6.ts.map +7 -0
  18. package/dist/chunks/{cloud-EPAEV4ZB.ts → cloud-J2ZOE3HE.ts} +6 -2
  19. package/dist/chunks/cloud-J2ZOE3HE.ts.map +7 -0
  20. package/dist/chunks/command-configuration-menu-YOLN2SPR.ts +147 -0
  21. package/dist/chunks/command-configuration-menu-YOLN2SPR.ts.map +7 -0
  22. package/dist/chunks/command-settings-chat-5AHP3JGV.ts +1124 -0
  23. package/dist/chunks/command-settings-chat-5AHP3JGV.ts.map +7 -0
  24. package/dist/chunks/commands-IOG2PL67.ts +1026 -0
  25. package/dist/chunks/commands-IOG2PL67.ts.map +7 -0
  26. package/dist/chunks/{deployment-7J54EHNR.ts → deployment-NOJ2KCLI.ts} +85 -5
  27. package/dist/chunks/deployment-NOJ2KCLI.ts.map +7 -0
  28. package/dist/chunks/{development-IWJAAAEV.ts → development-T3XXVVDP.ts} +67 -15
  29. package/dist/chunks/development-T3XXVVDP.ts.map +7 -0
  30. package/dist/chunks/directory-OX6BWJZA.ts +31 -0
  31. package/dist/chunks/directory-OX6BWJZA.ts.map +7 -0
  32. package/dist/chunks/{execution-P4WZALW2.ts → execution-R2OHIP2L.ts} +8 -4
  33. package/dist/chunks/execution-R2OHIP2L.ts.map +7 -0
  34. package/dist/chunks/jujutsu-XLDYKSX2.ts +174 -0
  35. package/dist/chunks/jujutsu-XLDYKSX2.ts.map +7 -0
  36. package/dist/chunks/languages-CBQNNYXM.ts +262 -0
  37. package/dist/chunks/languages-CBQNNYXM.ts.map +7 -0
  38. package/dist/chunks/{package-H24VJEX3.ts → package-7KVAK3TC.ts} +6 -2
  39. package/dist/chunks/package-7KVAK3TC.ts.map +7 -0
  40. package/dist/chunks/system-574MHB4R.ts +165 -0
  41. package/dist/chunks/system-574MHB4R.ts.map +7 -0
  42. package/dist/index.ts +670 -206
  43. package/dist/index.ts.map +4 -4
  44. package/package.json +5 -1
  45. package/skills/configure-pi-starship/SKILL.md +17 -1
  46. package/skills/configure-pi-starship/references/configuration.md +119 -32
  47. package/skills/configure-pi-starship/references/module-catalog.md +278 -25
  48. package/skills/configure-pi-starship/references/modules.md +213 -36
  49. package/skills/configure-pi-starship/references/runtime-and-security.md +88 -28
  50. package/src/command-commit.ts +41 -7
  51. package/src/command-configuration-menu.ts +155 -0
  52. package/src/command-configuration.ts +15 -94
  53. package/src/command-preview.ts +3 -3
  54. package/src/command-settings-chat.ts +168 -0
  55. package/src/commands.ts +76 -124
  56. package/src/config/module-options.ts +112 -0
  57. package/src/config.ts +23 -59
  58. package/src/effective-config.ts +5 -4
  59. package/src/format/bounded-regex.ts +66 -0
  60. package/src/format/version.ts +24 -0
  61. package/src/modules/catalog.ts +10 -0
  62. package/src/modules/cloud.ts +1 -0
  63. package/src/modules/deployment.ts +8 -0
  64. package/src/modules/development.ts +20 -2
  65. package/src/modules/directory.ts +171 -51
  66. package/src/modules/execution.ts +2 -0
  67. package/src/modules/git/branch.ts +19 -4
  68. package/src/modules/git/commit.ts +9 -2
  69. package/src/modules/git/metrics.ts +9 -4
  70. package/src/modules/git/runtime.ts +122 -33
  71. package/src/modules/git/state.ts +23 -2
  72. package/src/modules/git/status-templates.ts +58 -0
  73. package/src/modules/git/status.ts +96 -30
  74. package/src/modules/jujutsu.ts +225 -0
  75. package/src/modules/languages.ts +26 -2
  76. package/src/modules/package.ts +1 -0
  77. package/src/modules/render.ts +42 -16
  78. package/src/modules/system.ts +54 -0
  79. package/src/modules/time-format.ts +188 -0
  80. package/src/modules/time.ts +11 -5
  81. package/src/modules/types.ts +42 -4
  82. package/src/pi-starship.ts +198 -88
  83. package/src/profile-store.ts +5 -0
  84. package/src/runtime/cloud.ts +3 -0
  85. package/src/runtime/command.ts +1 -1
  86. package/src/runtime/deployment.ts +120 -4
  87. package/src/runtime/development.ts +86 -13
  88. package/src/runtime/directory.ts +33 -0
  89. package/src/runtime/execution.ts +12 -2
  90. package/src/runtime/helpers.ts +57 -8
  91. package/src/runtime/jujutsu.ts +225 -0
  92. package/src/runtime/languages.ts +106 -19
  93. package/src/runtime/package.ts +3 -0
  94. package/src/runtime/system.ts +202 -0
  95. package/src/runtime/types.ts +3 -0
  96. package/src/runtime/version-requirements.ts +30 -0
  97. package/src/runtime/workspace.ts +12 -1
  98. package/src/settings-agent.ts +80 -0
  99. package/src/settings-chat-transcript.ts +192 -0
  100. package/src/settings-chat-ui.ts +526 -0
  101. package/src/settings-draft.ts +260 -0
  102. package/src/settings-snapshots.ts +41 -0
  103. package/dist/chunks/chunk-ADX4CY27.ts.map +0 -7
  104. package/dist/chunks/chunk-KZZKGGFW.ts.map +0 -7
  105. package/dist/chunks/chunk-PD457PX5.ts.map +0 -7
  106. package/dist/chunks/cloud-EPAEV4ZB.ts.map +0 -7
  107. package/dist/chunks/commands-C2VJ6ZBN.ts +0 -3374
  108. package/dist/chunks/commands-C2VJ6ZBN.ts.map +0 -7
  109. package/dist/chunks/deployment-7J54EHNR.ts.map +0 -7
  110. package/dist/chunks/development-IWJAAAEV.ts.map +0 -7
  111. package/dist/chunks/execution-P4WZALW2.ts.map +0 -7
  112. package/dist/chunks/languages-JO6R2PHL.ts +0 -168
  113. package/dist/chunks/languages-JO6R2PHL.ts.map +0 -7
  114. package/dist/chunks/package-H24VJEX3.ts.map +0 -7
  115. package/src/command-inspector.ts +0 -41
@@ -0,0 +1,225 @@
1
+ import { dirname, resolve } from "node:path";
2
+ import { parse } from "smol-toml";
3
+ import type { JujutsuBookmark } from "../modules/types.js";
4
+ import { isRecord, MAX_COMMAND_OUTPUT_BYTES, runBounded } from "./helpers.js";
5
+ import type { CollectorContext, MutableModuleSnapshot } from "./types.js";
6
+
7
+ const MAX_ANCESTORS = 64;
8
+ const MODULES = ["jj_bookmark", "jj_change", "jj_metrics", "jj_status"] as const;
9
+
10
+ // Match Starship's selection: the current change, the latest mutable conflicted
11
+ // ancestor head, and the latest bookmark ancestor. These can be the same change.
12
+ const REVSET = "@ | latest(heads(mutable() & ::@ & conflicts()), 1) | latest(bookmarks() & ::@, 1)";
13
+ const TEMPLATE = String.raw`if(
14
+ current_working_copy,
15
+ join(
16
+ "\n",
17
+ concat("current.has_description = ", description.len() > 0),
18
+ concat("current.hidden = ", hidden),
19
+ concat("current.immutable = ", immutable),
20
+ concat("current.divergent = ", divergent),
21
+ concat("current.change_offset = ", change_offset),
22
+ concat("current.change_id = \"", change_id, "\""),
23
+ concat("current.change_id_prefix_len = ", change_id.shortest().prefix().len()),
24
+ concat("current.commit_id = \"", commit_id, "\""),
25
+ concat("current.commit_id_prefix_len = ", commit_id.shortest().prefix().len()),
26
+ concat("current.lines_added = ", diff.stat().total_added()),
27
+ concat("current.lines_removed = ", diff.stat().total_removed()),
28
+ concat("current.conflicted = ", conflict),
29
+ concat("current.bookmarks = [", bookmarks.map(|bm| concat("{ name = ", bm.name().escape_json(), ", remote = ", if(bm.remote(), bm.remote().escape_json(), "\"\""), ", diverged = ", !bm.conflict() && !bm.synced() && (!bm.remote() || bm.tracked()), " }")).join(","), "]"),
30
+ concat("current.statuses = \"", self.diff().files().map(|file| file.status_char()).join(""), "\""),
31
+ "",
32
+ ),
33
+ concat(
34
+ "parents.", commit_id, ".conflicted = ", conflict, "\n",
35
+ "parents.", commit_id, ".bookmark_source = ", contained_in("latest(bookmarks() & ::@, 1)"), "\n",
36
+ "parents.", commit_id, ".bookmarks = [", bookmarks.map(|bm| concat("{ name = ", bm.name().escape_json(), ", remote = ", if(bm.remote(), bm.remote().escape_json(), "\"\""), ", diverged = ", !bm.conflict() && !bm.synced() && (!bm.remote() || bm.tracked()), " }")).join(","), "]\n",
37
+ ),
38
+ )`;
39
+
40
+ export async function collectJujutsu(context: CollectorContext): Promise<MutableModuleSnapshot> {
41
+ if (context.input.signal?.aborted || !MODULES.some((name) => context.needs(name))) return {};
42
+ const root = await discoverRoot(context);
43
+ if (!root || context.input.signal?.aborted) return {};
44
+ // Unlike a shell prompt, a footer must not snapshot the working copy or write
45
+ // the repository. Values describe the last recorded working-copy change.
46
+ const output = await runBounded(context, "jj", [
47
+ "--color",
48
+ "never",
49
+ "--ignore-working-copy",
50
+ "--no-integrate-operation",
51
+ "--no-pager",
52
+ "--quiet",
53
+ "--repository",
54
+ root,
55
+ "show",
56
+ REVSET,
57
+ "--no-patch",
58
+ "--template",
59
+ TEMPLATE,
60
+ ]);
61
+ if (output === undefined || context.input.signal?.aborted) return {};
62
+ const change = parseJujutsuOutput(output);
63
+ if (!change) return {};
64
+ const modules: MutableModuleSnapshot = {};
65
+ if (context.needs("jj_bookmark")) modules.jj_bookmark = { bookmarks: JSON.stringify(change.bookmarks) };
66
+ if (context.needs("jj_change")) {
67
+ modules.jj_change = {
68
+ change_id: change.changeId,
69
+ change_prefix_len: String(change.changePrefixLength),
70
+ commit_id: change.commitId,
71
+ commit_prefix_len: String(change.commitPrefixLength),
72
+ ...(change.changeOffset === undefined ? {} : { change_offset: String(change.changeOffset) }),
73
+ };
74
+ }
75
+ if (context.needs("jj_metrics"))
76
+ modules.jj_metrics = { added: String(change.added), deleted: String(change.deleted) };
77
+ if (context.needs("jj_status")) {
78
+ modules.jj_status = {
79
+ conflicted: String(change.conflicted),
80
+ has_description: String(change.hasDescription),
81
+ hidden: String(change.hidden),
82
+ immutable: String(change.immutable),
83
+ added: String(countStatus(change.statuses, "A")),
84
+ copied: String(countStatus(change.statuses, "C")),
85
+ deleted: String(countStatus(change.statuses, "D")),
86
+ modified: String(countStatus(change.statuses, "M")),
87
+ renamed: String(countStatus(change.statuses, "R")),
88
+ };
89
+ }
90
+ return modules;
91
+ }
92
+
93
+ async function discoverRoot(context: CollectorContext): Promise<string | undefined> {
94
+ let current = resolve(context.input.cwd);
95
+ for (let depth = 0; depth < MAX_ANCESTORS; depth += 1) {
96
+ if (context.input.signal?.aborted) return undefined;
97
+ let entries: Awaited<ReturnType<CollectorContext["entries"]>>;
98
+ try {
99
+ entries = depth === 0 ? await context.entries() : await context.fs.readDirectory(current);
100
+ } catch {
101
+ return undefined;
102
+ }
103
+ if (context.input.signal?.aborted) return undefined;
104
+ if (entries.some((entry) => entry.name === ".jj" && entry.isDirectory)) return current;
105
+ const parent = dirname(current);
106
+ if (parent === current) return undefined;
107
+ current = parent;
108
+ }
109
+ return undefined;
110
+ }
111
+
112
+ interface JujutsuChange {
113
+ changeId: string;
114
+ changePrefixLength: number;
115
+ commitId: string;
116
+ commitPrefixLength: number;
117
+ changeOffset?: number;
118
+ bookmarks: JujutsuBookmark[];
119
+ added: number;
120
+ deleted: number;
121
+ conflicted: boolean;
122
+ hasDescription: boolean;
123
+ hidden: boolean;
124
+ immutable: boolean;
125
+ statuses: string;
126
+ }
127
+
128
+ export function parseJujutsuOutput(output: string): JujutsuChange | undefined {
129
+ if (Buffer.byteLength(output) > MAX_COMMAND_OUTPUT_BYTES) return undefined;
130
+ try {
131
+ const document = parse(output);
132
+ const current = document.current;
133
+ const parents = document.parents ?? {};
134
+ if (!isRecord(current) || !isRecord(parents)) return undefined;
135
+ // Unique ancestor tables prevent duplicate TOML keys when both selected
136
+ // ancestors have bookmarks or conflicts.
137
+ const entries = Object.entries(parents);
138
+ if (entries.length > 2 || entries.some(([key, value]) => !/^[a-fA-F0-9]{1,128}$/u.test(key) || !isRecord(value)))
139
+ return undefined;
140
+ const selectedAncestors = entries.map(([, value]) => value as Record<string, unknown>);
141
+ if (
142
+ selectedAncestors.some((ancestor) => typeof ancestor.bookmark_source !== "boolean") ||
143
+ selectedAncestors.filter((ancestor) => ancestor.bookmark_source === true).length > 1
144
+ )
145
+ return undefined;
146
+ const ancestors = selectedAncestors;
147
+ if (
148
+ ancestors.some(
149
+ (ancestor) =>
150
+ !bookmarks(ancestor.bookmarks) ||
151
+ (ancestor.conflicted !== undefined && typeof ancestor.conflicted !== "boolean"),
152
+ )
153
+ )
154
+ return undefined;
155
+ if (
156
+ !asciiId(current.change_id, 32, 32) ||
157
+ !asciiId(current.commit_id, 1, 128) ||
158
+ !unsigned(current.change_id_prefix_len, 255) ||
159
+ !unsigned(current.commit_id_prefix_len, 255) ||
160
+ !unsigned(current.change_offset, 65_535) ||
161
+ !unsigned(current.lines_added, 4_294_967_295) ||
162
+ !unsigned(current.lines_removed, 4_294_967_295) ||
163
+ ![current.has_description, current.hidden, current.immutable, current.divergent].every(
164
+ (value) => typeof value === "boolean",
165
+ ) ||
166
+ typeof current.statuses !== "string" ||
167
+ (current.conflicted !== undefined && typeof current.conflicted !== "boolean") ||
168
+ !bookmarks(current.bookmarks)
169
+ )
170
+ return undefined;
171
+ return {
172
+ changeId: current.change_id,
173
+ changePrefixLength: current.change_id_prefix_len,
174
+ commitId: current.commit_id,
175
+ commitPrefixLength: current.commit_id_prefix_len,
176
+ ...(current.divergent ? { changeOffset: current.change_offset } : {}),
177
+ bookmarks: [
178
+ ...(current.bookmarks ?? []),
179
+ ...selectedAncestors
180
+ .filter((ancestor) => ancestor.bookmark_source === true)
181
+ .flatMap((ancestor) => (ancestor.bookmarks ?? []) as JujutsuBookmark[]),
182
+ ],
183
+ added: current.lines_added,
184
+ deleted: current.lines_removed,
185
+ conflicted: current.conflicted === true || ancestors.some((ancestor) => ancestor.conflicted === true),
186
+ hasDescription: current.has_description === true,
187
+ hidden: current.hidden === true,
188
+ immutable: current.immutable === true,
189
+ statuses: current.statuses,
190
+ };
191
+ } catch {
192
+ return undefined;
193
+ }
194
+ }
195
+
196
+ function unsigned(value: unknown, maximum: number): value is number {
197
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= maximum;
198
+ }
199
+
200
+ function asciiId(value: unknown, minimum: number, maximum: number): value is string {
201
+ return (
202
+ typeof value === "string" && value.length >= minimum && value.length <= maximum && /^[A-Za-z0-9]+$/u.test(value)
203
+ );
204
+ }
205
+
206
+ function bookmarks(value: unknown): value is JujutsuBookmark[] | undefined {
207
+ return (
208
+ value === undefined ||
209
+ (Array.isArray(value) &&
210
+ value.every(
211
+ (item) =>
212
+ isRecord(item) &&
213
+ typeof item.name === "string" &&
214
+ typeof item.remote === "string" &&
215
+ typeof item.diverged === "boolean" &&
216
+ Object.keys(item).every((key) => key === "name" || key === "remote" || key === "diverged"),
217
+ ))
218
+ );
219
+ }
220
+
221
+ function countStatus(statuses: string, status: string): number {
222
+ let count = 0;
223
+ for (const character of statuses) if (character === status) count += 1;
224
+ return count;
225
+ }
@@ -1,15 +1,19 @@
1
- import { delimiter, join } from "node:path";
1
+ import { delimiter, dirname, join } from "node:path";
2
+ import { styleVariables } from "../format/formatter.js";
2
3
  import {
4
+ detectEnvironment,
3
5
  directMatch,
4
6
  formatVersion,
5
7
  MAX_METADATA_FILE_BYTES,
8
+ optionBoolean,
6
9
  optionString,
7
10
  optionStrings,
8
11
  pathName,
9
12
  runBounded,
10
13
  safeMetadata,
11
14
  } from "./helpers.js";
12
- import type { CollectorContext, MutableModuleSnapshot } from "./types.js";
15
+ import { type CollectorContext, type MutableModuleSnapshot, PRIVATE_STYLE_SELECTOR } from "./types.js";
16
+ import { goRequirementSatisfied, nodeRequirementSatisfied } from "./version-requirements.js";
13
17
 
14
18
  const LANGUAGE_NAMES = ["nodejs", "python", "rust", "golang", "bun", "deno"] as const;
15
19
  type LanguageName = (typeof LANGUAGE_NAMES)[number];
@@ -36,12 +40,16 @@ export async function collectLanguages(context: CollectorContext): Promise<Mutab
36
40
  if (!LANGUAGE_NAMES.some((name) => context.needs(name))) return result;
37
41
  const entries = await context.entries();
38
42
  for (const name of LANGUAGE_NAMES) {
43
+ if (context.input.signal?.aborted) return {};
39
44
  if (!context.needs(name)) continue;
40
45
  const defaults = DEFAULT_DETECTION[name];
41
46
  const files = optionStrings(context, name, "detect_files");
42
47
  const extensions = optionStrings(context, name, "detect_extensions");
43
48
  const folders = optionStrings(context, name, "detect_folders");
49
+ const envNames = name === "python" ? optionStrings(context, name, "detect_env_vars") : [];
50
+ const environmentDetected = envNames.length > 0 && detectEnvironment(context.input.environment, envNames);
44
51
  if (
52
+ !environmentDetected &&
45
53
  !directMatch(
46
54
  entries,
47
55
  files.length > 0 ? files : defaults.files,
@@ -53,23 +61,38 @@ export async function collectLanguages(context: CollectorContext): Promise<Mutab
53
61
  }
54
62
  const values: Record<string, string> = {};
55
63
  addEnvironmentValues(context, name, values);
56
- if (context.needs(name, "engines_version")) {
57
- const engine = await readNodeEngine(context);
58
- if (engine) values.engines_version = engine;
64
+ const checkRequirement = requirementStyleNeeded(context, name);
65
+ let requirement: string | undefined;
66
+ if (name === "nodejs" && (context.needs(name, "engines_version") || checkRequirement)) {
67
+ requirement = await readNodeEngine(context);
68
+ const display = safeMetadata(requirement, 80);
69
+ if (display && context.needs(name, "engines_version")) values.engines_version = display;
59
70
  }
71
+ if (name === "golang" && (context.needs(name, "mod_version") || checkRequirement)) {
72
+ requirement = await readGoRequirement(context);
73
+ // Pi keeps requirement variables visible, even when the runtime satisfies them.
74
+ if (requirement && context.needs(name, "mod_version")) values.mod_version = requirement;
75
+ }
76
+ if (context.input.signal?.aborted) return {};
60
77
  const needsVersion = context.needs(name, "version");
61
78
  const needsNumver = name === "rust" && context.needs(name, "numver");
62
- if (needsVersion || needsNumver) {
63
- const command = await versionCommand(context, name);
64
- if (command) {
65
- const output = await runBounded(context, command[0], command[1]);
66
- const version = output ? parseRuntimeVersion(name, output) : undefined;
67
- if (version) {
68
- if (needsVersion) {
69
- values.version = formatVersion(version, optionString(context, name, "version_format"));
70
- }
71
- if (needsNumver) values.numver = version.replace(/^v/u, "");
79
+ if (needsVersion || needsNumver || (checkRequirement && requirement)) {
80
+ const pyenvLabel = name === "python" && optionBoolean(context, name, "pyenv_version_name");
81
+ const version = pyenvLabel ? await pyenvVersion(context) : await runtimeVersion(context, name);
82
+ if (context.input.signal?.aborted) return {};
83
+ if (version) {
84
+ if (needsVersion) {
85
+ values.version = pyenvLabel ? version : formatVersion(version, optionString(context, name, "version_format"));
72
86
  }
87
+ if (needsNumver) values.numver = version.replace(/^v/u, "");
88
+ }
89
+ if (
90
+ checkRequirement &&
91
+ !(name === "nodejs"
92
+ ? nodeRequirementSatisfied(version, requirement)
93
+ : goRequirementSatisfied(version, requirement))
94
+ ) {
95
+ values[PRIVATE_STYLE_SELECTOR] = "not_capable";
73
96
  }
74
97
  }
75
98
  result[name] = values;
@@ -81,9 +104,22 @@ function addEnvironmentValues(context: CollectorContext, name: LanguageName, val
81
104
  const env = context.input.environment;
82
105
  if (name === "python") {
83
106
  const virtualenv = safeMetadata(env.VIRTUAL_ENV) ?? safeMetadata(env.CONDA_DEFAULT_ENV);
84
- if (virtualenv && context.needs(name, "virtualenv")) values.virtualenv = pathName(virtualenv);
85
- const pyenv = safeMetadata(env.PYENV_VERSION);
86
- if (pyenv && context.needs(name, "pyenv_prefix")) values.pyenv_prefix = pyenv;
107
+ if (virtualenv && context.needs(name, "virtualenv")) {
108
+ const label = pathName(virtualenv);
109
+ const parent = dirname(virtualenv.replace(/[\\/]+$/u, ""));
110
+ const parentName = pathName(parent);
111
+ values.virtualenv =
112
+ optionStrings(context, name, "generic_venv_names").includes(label) &&
113
+ parentName !== "." &&
114
+ parent !== dirname(parent)
115
+ ? parentName
116
+ : label;
117
+ }
118
+ const pyenv = optionBoolean(context, name, "pyenv_version_name")
119
+ ? optionString(context, name, "pyenv_prefix")
120
+ : safeMetadata(env.PYENV_VERSION);
121
+ // The false branch retains Pi's existing PYENV_VERSION prefix value.
122
+ if (pyenv !== undefined && context.needs(name, "pyenv_prefix")) values.pyenv_prefix = pyenv;
87
123
  }
88
124
  if (name === "rust") {
89
125
  const toolchain = safeMetadata(env.RUSTUP_TOOLCHAIN);
@@ -96,12 +132,62 @@ async function readNodeEngine(context: CollectorContext): Promise<string | undef
96
132
  if (!source) return undefined;
97
133
  try {
98
134
  const document = JSON.parse(source) as { engines?: { node?: unknown } };
99
- return safeMetadata(document.engines?.node, 80);
135
+ return typeof document?.engines?.node === "string" ? document.engines.node : undefined;
100
136
  } catch {
101
137
  return undefined;
102
138
  }
103
139
  }
104
140
 
141
+ function requirementStyleNeeded(context: CollectorContext, name: LanguageName): boolean {
142
+ if (name !== "nodejs" && name !== "golang") return false;
143
+ const module = context.input.config.modules[name];
144
+ const style = module.styles.not_capable_style;
145
+ const hasRuntimeValue =
146
+ context.needs(name, "version") || context.needs(name, name === "nodejs" ? "engines_version" : "mod_version");
147
+ return Boolean(
148
+ hasRuntimeValue && style !== undefined && style !== "none" && styleVariables(module.formatAst).has("style"),
149
+ );
150
+ }
151
+
152
+ async function readGoRequirement(context: CollectorContext): Promise<string | undefined> {
153
+ const source = await context.fs.readFile(join(context.input.cwd, "go.mod"), MAX_METADATA_FILE_BYTES);
154
+ if (!source) return undefined;
155
+ return /^[ \t]*go[ \t]+(\d{1,9}\.\d{1,9}(?:\.\d{1,9})?)[ \t]*(?:\/\/[^\r\n]*)?\r?$/mu.exec(source)?.[1];
156
+ }
157
+
158
+ async function pyenvVersion(context: CollectorContext): Promise<string | undefined> {
159
+ const env = context.input.environment.PYENV_VERSION;
160
+ if (env !== undefined) return safeMetadata(env);
161
+ const output = await runBounded(context, "pyenv", ["version-name"]);
162
+ return safeMetadata(output);
163
+ }
164
+
165
+ async function runtimeVersion(context: CollectorContext, name: LanguageName): Promise<string | undefined> {
166
+ if (name === "python") {
167
+ const alternatives = context.options(name).python_binary;
168
+ if (Array.isArray(alternatives) && alternatives.length > 0) {
169
+ for (const alternative of alternatives) {
170
+ if (context.input.signal?.aborted) return undefined;
171
+ const argv = typeof alternative === "string" ? [alternative] : alternative;
172
+ if (!Array.isArray(argv) || typeof argv[0] !== "string") return undefined;
173
+ const output = await runBounded(context, argv[0], [...argv.slice(1), "--version"]);
174
+ // Like upstream, the first successful command owns parsing, even when its output is malformed.
175
+ if (output !== undefined) return parseRuntimeVersion(name, output);
176
+ }
177
+ return undefined;
178
+ }
179
+ }
180
+ const command = await versionCommand(context, name);
181
+ if (!command || context.input.signal?.aborted) return undefined;
182
+ // Go otherwise may download a toolchain selected by go.mod before printing its version.
183
+ const commandContext =
184
+ name === "golang"
185
+ ? { ...context, input: { ...context.input, environment: { ...context.input.environment, GOTOOLCHAIN: "local" } } }
186
+ : context;
187
+ const output = await runBounded(commandContext, command[0], command[1]);
188
+ return output ? parseRuntimeVersion(name, output) : undefined;
189
+ }
190
+
105
191
  async function versionCommand(context: CollectorContext, name: LanguageName): Promise<[string, string[]] | undefined> {
106
192
  switch (name) {
107
193
  case "nodejs":
@@ -136,6 +222,7 @@ async function safeRustCompiler(context: CollectorContext): Promise<string | und
136
222
  .map((directory) => join(directory, context.input.platform === "win32" ? "rustc.exe" : "rustc")),
137
223
  ];
138
224
  for (const rawCandidate of candidates) {
225
+ if (context.input.signal?.aborted) return undefined;
139
226
  const candidate = safeMetadata(rawCandidate, 1_024);
140
227
  if (!candidate || /(?:^|[\\/])\.(?:cargo|rustup)(?:[\\/]|$)/iu.test(candidate)) continue;
141
228
  if (await context.fs.fileExists(candidate)) return candidate;
@@ -4,6 +4,7 @@ import {
4
4
  formatVersion,
5
5
  isRecord,
6
6
  MAX_METADATA_FILE_BYTES,
7
+ optionBoolean,
7
8
  optionString,
8
9
  parentDirectories,
9
10
  safeMetadata,
@@ -34,6 +35,8 @@ async function readPackageJson(context: CollectorContext): Promise<PackageVersio
34
35
  if (!source) return undefined;
35
36
  try {
36
37
  const document = JSON.parse(source) as unknown;
38
+ if (isRecord(document) && document.private === true && !optionBoolean(context, "package", "display_private"))
39
+ return undefined;
37
40
  const version = isRecord(document) ? safeVersion(document.version) : undefined;
38
41
  return version ? { version, source: "package.json" } : undefined;
39
42
  } catch {
@@ -0,0 +1,202 @@
1
+ import { freemem, totalmem } from "node:os";
2
+ import { join } from "node:path";
3
+ import { MAX_METADATA_FILE_BYTES, optionNumber } from "./helpers.js";
4
+ import type { CollectorContext, MutableModuleSnapshot } from "./types.js";
5
+
6
+ const POWER_SUPPLY_ROOT = "/sys/class/power_supply";
7
+ const MAX_POWER_SUPPLIES = 32;
8
+ const MAX_UEVENT_BYTES = 8_192;
9
+
10
+ type BatteryState = "charging" | "discharging" | "full" | "empty" | "unknown";
11
+ interface MemoryStats {
12
+ total: number;
13
+ free: number;
14
+ swap?: { total: number; free: number };
15
+ }
16
+ interface BatteryStats {
17
+ energy: number;
18
+ full: number;
19
+ state: BatteryState;
20
+ }
21
+
22
+ export async function collectSystem(context: CollectorContext): Promise<MutableModuleSnapshot> {
23
+ const modules: MutableModuleSnapshot = {};
24
+ if (context.input.signal?.aborted) return modules;
25
+ if (context.needs("memory_usage")) {
26
+ const values = await collectMemory(context);
27
+ if (context.input.signal?.aborted) return {};
28
+ if (values) modules.memory_usage = values;
29
+ }
30
+ if (context.needs("battery")) {
31
+ const values = await collectBattery(context);
32
+ if (context.input.signal?.aborted) return {};
33
+ if (values) modules.battery = values;
34
+ }
35
+ return modules;
36
+ }
37
+
38
+ async function collectMemory(context: CollectorContext): Promise<Record<string, string> | undefined> {
39
+ let stats: MemoryStats | undefined;
40
+ const injected = context.input.systemMemory;
41
+ try {
42
+ // The injection is a test seam, not an extension setting. No sample is taken
43
+ // before reachability and cancellation checks in collectSystem().
44
+ stats = injected ? injected() : { total: totalmem(), free: freemem() };
45
+ } catch {
46
+ return undefined;
47
+ }
48
+ if (!stats || !validTotal(stats.total) || !validBytes(stats.free)) return undefined;
49
+ const used = Math.max(0, stats.total - stats.free);
50
+ const percentage = Math.round(100 * (used / stats.total));
51
+ if (percentage < (optionNumber(context, "memory_usage", "threshold") ?? 75)) return undefined;
52
+ const values: Record<string, string> = { ram: formatUsage(stats.total, stats.free), ram_pct: `${percentage}%` };
53
+ if (context.needs("memory_usage", "swap") || context.needs("memory_usage", "swap_pct")) {
54
+ // Node's native os API has no swap data. Linux can supply it through this
55
+ // bounded read; other platforms (or missing/malformed sources) omit swap.
56
+ const swap =
57
+ stats.swap ??
58
+ (injected === undefined && context.input.platform === "linux"
59
+ ? parseSwap(await readBounded(context, "/proc/meminfo", MAX_METADATA_FILE_BYTES))
60
+ : undefined);
61
+ if (context.input.signal?.aborted) return undefined;
62
+ if (swap && validTotal(swap.total) && validBytes(swap.free)) {
63
+ values.swap = formatUsage(swap.total, swap.free);
64
+ values.swap_pct = `${Math.round(100 * (Math.max(0, swap.total - swap.free) / swap.total))}%`;
65
+ }
66
+ }
67
+ return values;
68
+ }
69
+
70
+ function validBytes(value: number): boolean {
71
+ return Number.isFinite(value) && value >= 0 && value <= Number.MAX_SAFE_INTEGER;
72
+ }
73
+
74
+ function validTotal(value: number): boolean {
75
+ return validBytes(value) && value > 0;
76
+ }
77
+
78
+ function formatUsage(total: number, free: number): string {
79
+ return `${formatBytes(Math.max(0, total - free))}/${formatBytes(total)}`;
80
+ }
81
+
82
+ function formatBytes(value: number): string {
83
+ const units = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"];
84
+ let unit = 0;
85
+ while (value >= 1_024 && unit < units.length - 1) {
86
+ value /= 1_024;
87
+ unit += 1;
88
+ }
89
+ return `${Math.floor(value)}${units[unit]}`;
90
+ }
91
+
92
+ function parseSwap(source: string | undefined): MemoryStats["swap"] {
93
+ if (source === undefined) return undefined;
94
+ const total = /^SwapTotal:\s+([0-9]+) kB\s*$/mu.exec(source)?.[1];
95
+ const free = /^SwapFree:\s+([0-9]+) kB\s*$/mu.exec(source)?.[1];
96
+ if (total === undefined || free === undefined) return undefined;
97
+ const stats = { total: Number(total) * 1_024, free: Number(free) * 1_024 };
98
+ return validTotal(stats.total) && validBytes(stats.free) ? stats : undefined;
99
+ }
100
+
101
+ async function collectBattery(context: CollectorContext): Promise<Record<string, string> | undefined> {
102
+ // Linux sysfs only. Do not probe another platform with external commands.
103
+ if (context.input.platform !== "linux" || context.input.signal?.aborted) return undefined;
104
+ let entries: Awaited<ReturnType<CollectorContext["fs"]["readDirectory"]>>;
105
+ try {
106
+ entries = await context.fs.readDirectory(POWER_SUPPLY_ROOT);
107
+ } catch {
108
+ return undefined;
109
+ }
110
+ if (context.input.signal?.aborted || entries.length > MAX_POWER_SUPPLIES) return undefined;
111
+ let energy = 0;
112
+ let full = 0;
113
+ const states = new Set<BatteryState>();
114
+ for (const entry of [...entries].sort((left, right) =>
115
+ left.name < right.name ? -1 : left.name > right.name ? 1 : 0,
116
+ )) {
117
+ // Reject names rather than normalize them into another filesystem path.
118
+ if (!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/u.test(entry.name)) continue;
119
+ const source = await readBounded(context, join(POWER_SUPPLY_ROOT, entry.name, "uevent"), MAX_UEVENT_BYTES);
120
+ if (context.input.signal?.aborted) return undefined;
121
+ const battery = parseBattery(source);
122
+ if (!battery) continue;
123
+ energy += battery.energy;
124
+ full += battery.full;
125
+ states.add(battery.state);
126
+ }
127
+ if (!validTotal(full) || !validBytes(energy)) return undefined;
128
+ const percentage = Math.min(100, Math.max(0, 100 * (energy / full)));
129
+ return {
130
+ percentage: `${Math.round(percentage)}%`,
131
+ percentage_raw: String(percentage),
132
+ state: mergeBatteryStates(states),
133
+ };
134
+ }
135
+
136
+ function parseBattery(source: string | undefined): BatteryStats | undefined {
137
+ if (source === undefined) return undefined;
138
+ const fields = new Map<string, string>();
139
+ for (const line of source.split(/\r?\n/u)) {
140
+ if (!line) continue;
141
+ const separator = line.indexOf("=");
142
+ if (separator < 1) return undefined;
143
+ const key = line.slice(0, separator);
144
+ if (!/^POWER_SUPPLY_[A-Z0-9_]+$/u.test(key) || fields.has(key)) return undefined;
145
+ fields.set(key, line.slice(separator + 1));
146
+ }
147
+ const present = fields.get("POWER_SUPPLY_PRESENT");
148
+ if (fields.get("POWER_SUPPLY_TYPE") !== "Battery" || (present !== undefined && present !== "1")) return undefined;
149
+ const number = (key: string) => {
150
+ const raw = fields.get(`POWER_SUPPLY_${key}`);
151
+ if (raw === undefined || !/^[0-9]+$/u.test(raw)) return undefined;
152
+ const value = Number(raw);
153
+ return validBytes(value) ? value : undefined;
154
+ };
155
+ let energy = number("ENERGY_NOW");
156
+ let full = number("ENERGY_FULL");
157
+ if (energy === undefined || full === undefined) {
158
+ const charge = number("CHARGE_NOW");
159
+ const chargeFull = number("CHARGE_FULL");
160
+ const voltage = number("VOLTAGE_MIN_DESIGN") ?? number("VOLTAGE_NOW");
161
+ if (charge === undefined || chargeFull === undefined || voltage === undefined || voltage <= 0) return undefined;
162
+ // Both branches use micro-watt-hours so different battery types can be weighted together.
163
+ energy = charge * (voltage / 1_000_000);
164
+ full = chargeFull * (voltage / 1_000_000);
165
+ }
166
+ if (!validTotal(full) || !validBytes(energy)) return undefined;
167
+ const rawState = fields.get("POWER_SUPPLY_STATUS");
168
+ const state =
169
+ rawState === "Charging"
170
+ ? "charging"
171
+ : rawState === "Discharging"
172
+ ? "discharging"
173
+ : rawState === "Full"
174
+ ? "full"
175
+ : rawState === "Empty"
176
+ ? "empty"
177
+ : "unknown";
178
+ return { energy: Math.min(full, energy), full, state };
179
+ }
180
+
181
+ function mergeBatteryStates(states: ReadonlySet<BatteryState>): BatteryState {
182
+ if (states.has("charging")) return "charging";
183
+ if (states.has("discharging")) return "discharging";
184
+ // An ambiguous full/empty combination must remain unknown even when a later
185
+ // battery is full; aggregation must not depend on power-supply naming order.
186
+ if (states.has("full") && states.has("empty")) return "unknown";
187
+ if (states.has("full")) return "full";
188
+ if (states.has("empty")) return "empty";
189
+ return "unknown";
190
+ }
191
+
192
+ async function readBounded(context: CollectorContext, path: string, maxBytes: number): Promise<string | undefined> {
193
+ if (context.input.signal?.aborted) return undefined;
194
+ try {
195
+ const source = await context.fs.readFile(path, maxBytes);
196
+ return !context.input.signal?.aborted && source !== undefined && Buffer.byteLength(source) <= maxBytes
197
+ ? source
198
+ : undefined;
199
+ } catch {
200
+ return undefined;
201
+ }
202
+ }
@@ -31,6 +31,8 @@ export interface WorkspaceFileSystem {
31
31
  readFile(path: string, maxBytes: number): Promise<string | undefined>;
32
32
  readDirectory(path: string): Promise<readonly WorkspaceEntry[]>;
33
33
  fileExists(path: string): Promise<boolean>;
34
+ realPath?(path: string): Promise<string | undefined>;
35
+ isWritable?(path: string): Promise<boolean | undefined>;
34
36
  }
35
37
 
36
38
  export interface WorkspaceRefreshInput {
@@ -46,6 +48,7 @@ export interface WorkspaceRefreshInput {
46
48
  fileExists?(path: string): Promise<boolean>;
47
49
  reason?: "initial" | "event" | "periodic";
48
50
  previous?: WorkspaceSnapshot;
51
+ systemMemory?: () => { total: number; free: number; swap?: { total: number; free: number } } | undefined;
49
52
  signal?: AbortSignal;
50
53
  }
51
54