@oh-my-pi-zen/pi-utils 16.3.6-zen.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/CHANGELOG.md +245 -0
  2. package/README.md +36 -0
  3. package/dist/types/abortable.d.ts +32 -0
  4. package/dist/types/async.d.ts +6 -0
  5. package/dist/types/binary.d.ts +17 -0
  6. package/dist/types/cli.d.ts +117 -0
  7. package/dist/types/color.d.ts +102 -0
  8. package/dist/types/dirs.d.ts +260 -0
  9. package/dist/types/env.d.ts +74 -0
  10. package/dist/types/fetch-retry.d.ts +94 -0
  11. package/dist/types/format.d.ts +37 -0
  12. package/dist/types/frontmatter.d.ts +25 -0
  13. package/dist/types/fs-error.d.ts +31 -0
  14. package/dist/types/glob.d.ts +28 -0
  15. package/dist/types/index.d.ts +35 -0
  16. package/dist/types/json-parse.d.ts +48 -0
  17. package/dist/types/json.d.ts +4 -0
  18. package/dist/types/logger.d.ts +83 -0
  19. package/dist/types/loop-phase.d.ts +10 -0
  20. package/dist/types/mermaid-ascii.d.ts +11 -0
  21. package/dist/types/mime.d.ts +29 -0
  22. package/dist/types/module-timer.d.ts +1 -0
  23. package/dist/types/path-tree.d.ts +76 -0
  24. package/dist/types/path.d.ts +2 -0
  25. package/dist/types/peek-file.d.ts +29 -0
  26. package/dist/types/postmortem.d.ts +37 -0
  27. package/dist/types/procmgr.d.ts +29 -0
  28. package/dist/types/prompt.d.ts +18 -0
  29. package/dist/types/ptree.d.ts +108 -0
  30. package/dist/types/ring.d.ts +93 -0
  31. package/dist/types/runtime-install.d.ts +68 -0
  32. package/dist/types/sanitize-text.d.ts +29 -0
  33. package/dist/types/snowflake.d.ts +25 -0
  34. package/dist/types/stream.d.ts +68 -0
  35. package/dist/types/tab-spacing.d.ts +24 -0
  36. package/dist/types/temp.d.ts +17 -0
  37. package/dist/types/timing-buffer.d.ts +22 -0
  38. package/dist/types/tls-fetch.d.ts +37 -0
  39. package/dist/types/type-guards.d.ts +3 -0
  40. package/dist/types/vendor/mermaid-ascii/ascii/ansi.d.ts +41 -0
  41. package/dist/types/vendor/mermaid-ascii/ascii/canvas.d.ts +89 -0
  42. package/dist/types/vendor/mermaid-ascii/ascii/class-diagram.d.ts +7 -0
  43. package/dist/types/vendor/mermaid-ascii/ascii/converter.d.ts +12 -0
  44. package/dist/types/vendor/mermaid-ascii/ascii/draw.d.ts +66 -0
  45. package/dist/types/vendor/mermaid-ascii/ascii/edge-bundling.d.ts +48 -0
  46. package/dist/types/vendor/mermaid-ascii/ascii/edge-routing.d.ts +43 -0
  47. package/dist/types/vendor/mermaid-ascii/ascii/er-diagram.d.ts +7 -0
  48. package/dist/types/vendor/mermaid-ascii/ascii/grid.d.ts +56 -0
  49. package/dist/types/vendor/mermaid-ascii/ascii/index.d.ts +65 -0
  50. package/dist/types/vendor/mermaid-ascii/ascii/multiline-utils.d.ts +27 -0
  51. package/dist/types/vendor/mermaid-ascii/ascii/pathfinder.d.ts +17 -0
  52. package/dist/types/vendor/mermaid-ascii/ascii/sequence.d.ts +7 -0
  53. package/dist/types/vendor/mermaid-ascii/ascii/shapes/circle.d.ts +11 -0
  54. package/dist/types/vendor/mermaid-ascii/ascii/shapes/corners.d.ts +34 -0
  55. package/dist/types/vendor/mermaid-ascii/ascii/shapes/diamond.d.ts +11 -0
  56. package/dist/types/vendor/mermaid-ascii/ascii/shapes/hexagon.d.ts +11 -0
  57. package/dist/types/vendor/mermaid-ascii/ascii/shapes/index.d.ts +26 -0
  58. package/dist/types/vendor/mermaid-ascii/ascii/shapes/rectangle.d.ts +31 -0
  59. package/dist/types/vendor/mermaid-ascii/ascii/shapes/rounded.d.ts +11 -0
  60. package/dist/types/vendor/mermaid-ascii/ascii/shapes/special.d.ts +59 -0
  61. package/dist/types/vendor/mermaid-ascii/ascii/shapes/stadium.d.ts +17 -0
  62. package/dist/types/vendor/mermaid-ascii/ascii/shapes/state.d.ts +30 -0
  63. package/dist/types/vendor/mermaid-ascii/ascii/shapes/types.d.ts +55 -0
  64. package/dist/types/vendor/mermaid-ascii/ascii/types.d.ts +206 -0
  65. package/dist/types/vendor/mermaid-ascii/ascii/validate.d.ts +51 -0
  66. package/dist/types/vendor/mermaid-ascii/ascii/xychart.d.ts +2 -0
  67. package/dist/types/vendor/mermaid-ascii/class/parser.d.ts +6 -0
  68. package/dist/types/vendor/mermaid-ascii/class/types.d.ts +102 -0
  69. package/dist/types/vendor/mermaid-ascii/er/parser.d.ts +6 -0
  70. package/dist/types/vendor/mermaid-ascii/er/types.d.ts +76 -0
  71. package/dist/types/vendor/mermaid-ascii/index.d.ts +1 -0
  72. package/dist/types/vendor/mermaid-ascii/multiline-utils.d.ts +9 -0
  73. package/dist/types/vendor/mermaid-ascii/parser.d.ts +7 -0
  74. package/dist/types/vendor/mermaid-ascii/sequence/parser.d.ts +6 -0
  75. package/dist/types/vendor/mermaid-ascii/sequence/types.d.ts +130 -0
  76. package/dist/types/vendor/mermaid-ascii/text-metrics.d.ts +21 -0
  77. package/dist/types/vendor/mermaid-ascii/types.d.ts +114 -0
  78. package/dist/types/vendor/mermaid-ascii/xychart/colors.d.ts +25 -0
  79. package/dist/types/vendor/mermaid-ascii/xychart/parser.d.ts +6 -0
  80. package/dist/types/vendor/mermaid-ascii/xychart/types.d.ts +145 -0
  81. package/dist/types/which.d.ts +37 -0
  82. package/dist/types/worker-host.d.ts +47 -0
  83. package/package.json +62 -0
  84. package/src/abortable.ts +109 -0
  85. package/src/async.ts +50 -0
  86. package/src/binary.ts +50 -0
  87. package/src/cli.ts +457 -0
  88. package/src/color.ts +302 -0
  89. package/src/dirs.ts +925 -0
  90. package/src/env.ts +226 -0
  91. package/src/fetch-retry.ts +355 -0
  92. package/src/format.ts +113 -0
  93. package/src/frontmatter.ts +162 -0
  94. package/src/fs-error.ts +56 -0
  95. package/src/glob.ts +189 -0
  96. package/src/index.ts +55 -0
  97. package/src/json-parse.ts +612 -0
  98. package/src/json.ts +10 -0
  99. package/src/logger.ts +672 -0
  100. package/src/loop-phase.ts +49 -0
  101. package/src/mermaid-ascii.ts +31 -0
  102. package/src/mime.ts +159 -0
  103. package/src/module-timer.ts +148 -0
  104. package/src/path-tree.ts +147 -0
  105. package/src/path.ts +28 -0
  106. package/src/peek-file.ts +188 -0
  107. package/src/postmortem.ts +222 -0
  108. package/src/procmgr.ts +195 -0
  109. package/src/prompt.ts +562 -0
  110. package/src/ptree.ts +395 -0
  111. package/src/ring.ts +169 -0
  112. package/src/runtime-install.ts +372 -0
  113. package/src/sanitize-text.ts +96 -0
  114. package/src/snowflake.ts +121 -0
  115. package/src/stream.ts +432 -0
  116. package/src/tab-spacing.ts +336 -0
  117. package/src/temp.ts +134 -0
  118. package/src/timing-buffer.ts +47 -0
  119. package/src/tls-fetch.ts +178 -0
  120. package/src/type-guards.ts +11 -0
  121. package/src/vendor/mermaid-ascii/NOTICE +33 -0
  122. package/src/vendor/mermaid-ascii/ascii/ansi.ts +409 -0
  123. package/src/vendor/mermaid-ascii/ascii/canvas.ts +476 -0
  124. package/src/vendor/mermaid-ascii/ascii/class-diagram.ts +699 -0
  125. package/src/vendor/mermaid-ascii/ascii/converter.ts +271 -0
  126. package/src/vendor/mermaid-ascii/ascii/draw.ts +1382 -0
  127. package/src/vendor/mermaid-ascii/ascii/edge-bundling.ts +328 -0
  128. package/src/vendor/mermaid-ascii/ascii/edge-routing.ts +297 -0
  129. package/src/vendor/mermaid-ascii/ascii/er-diagram.ts +441 -0
  130. package/src/vendor/mermaid-ascii/ascii/grid.ts +578 -0
  131. package/src/vendor/mermaid-ascii/ascii/index.ts +187 -0
  132. package/src/vendor/mermaid-ascii/ascii/multiline-utils.ts +78 -0
  133. package/src/vendor/mermaid-ascii/ascii/pathfinder.ts +215 -0
  134. package/src/vendor/mermaid-ascii/ascii/sequence.ts +460 -0
  135. package/src/vendor/mermaid-ascii/ascii/shapes/circle.ts +27 -0
  136. package/src/vendor/mermaid-ascii/ascii/shapes/corners.ts +127 -0
  137. package/src/vendor/mermaid-ascii/ascii/shapes/diamond.ts +27 -0
  138. package/src/vendor/mermaid-ascii/ascii/shapes/hexagon.ts +27 -0
  139. package/src/vendor/mermaid-ascii/ascii/shapes/index.ts +101 -0
  140. package/src/vendor/mermaid-ascii/ascii/shapes/rectangle.ts +175 -0
  141. package/src/vendor/mermaid-ascii/ascii/shapes/rounded.ts +27 -0
  142. package/src/vendor/mermaid-ascii/ascii/shapes/special.ts +296 -0
  143. package/src/vendor/mermaid-ascii/ascii/shapes/stadium.ts +114 -0
  144. package/src/vendor/mermaid-ascii/ascii/shapes/state.ts +192 -0
  145. package/src/vendor/mermaid-ascii/ascii/shapes/types.ts +73 -0
  146. package/src/vendor/mermaid-ascii/ascii/types.ts +273 -0
  147. package/src/vendor/mermaid-ascii/ascii/validate.ts +120 -0
  148. package/src/vendor/mermaid-ascii/ascii/xychart.ts +875 -0
  149. package/src/vendor/mermaid-ascii/class/parser.ts +290 -0
  150. package/src/vendor/mermaid-ascii/class/types.ts +121 -0
  151. package/src/vendor/mermaid-ascii/er/parser.ts +181 -0
  152. package/src/vendor/mermaid-ascii/er/types.ts +91 -0
  153. package/src/vendor/mermaid-ascii/index.ts +14 -0
  154. package/src/vendor/mermaid-ascii/multiline-utils.ts +30 -0
  155. package/src/vendor/mermaid-ascii/parser.ts +645 -0
  156. package/src/vendor/mermaid-ascii/sequence/parser.ts +207 -0
  157. package/src/vendor/mermaid-ascii/sequence/types.ts +146 -0
  158. package/src/vendor/mermaid-ascii/text-metrics.ts +71 -0
  159. package/src/vendor/mermaid-ascii/types.ts +164 -0
  160. package/src/vendor/mermaid-ascii/xychart/colors.ts +140 -0
  161. package/src/vendor/mermaid-ascii/xychart/parser.ts +115 -0
  162. package/src/vendor/mermaid-ascii/xychart/types.ts +150 -0
  163. package/src/which.ts +232 -0
  164. package/src/worker-host.ts +92 -0
package/src/dirs.ts ADDED
@@ -0,0 +1,925 @@
1
+ /**
2
+ * Centralized path helpers for omp config directories.
3
+ *
4
+ * Uses PI_CONFIG_DIR (default ".omp") for the config root and
5
+ * PI_CODING_AGENT_DIR to override the agent directory.
6
+ *
7
+ * On Linux, if XDG_DATA_HOME / XDG_STATE_HOME / XDG_CACHE_HOME environment
8
+ * variables are set, paths are redirected to XDG-compliant locations under
9
+ * $XDG_*_HOME/omp/. This requires running `omp config migrate` first to
10
+ * move data to the new locations. No filesystem existence checks are performed
11
+ * — if the env var is set, omp trusts that the migration has been done.
12
+ */
13
+
14
+ import * as fs from "node:fs";
15
+ import * as os from "node:os";
16
+ import * as path from "node:path";
17
+ import { engines, version } from "../package.json" with { type: "json" };
18
+
19
+ /** App name (e.g. "omp") */
20
+ export const APP_NAME: string = "omp";
21
+
22
+ /** Config directory name (e.g. ".omp") */
23
+ export const CONFIG_DIR_NAME: string = ".omp";
24
+
25
+ /** Version (e.g. "1.0.0") */
26
+ export const VERSION: string = version;
27
+
28
+ /** Minimum Bun version */
29
+ export const MIN_BUN_VERSION: string = engines.bun.replace(/[^0-9.]/g, "");
30
+
31
+ const PROFILE_NAME_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
32
+ const PROFILE_ENV_KEYS = ["OMP_PROFILE", "PI_PROFILE"] as const;
33
+
34
+ /**
35
+ * Names Windows treats as reserved device aliases. Matches the basename
36
+ * itself as well as any `BASENAME.<anything>` form, because Windows reserves
37
+ * `CON.foo`/`PRN.txt`/etc. too — using them as a profile name would let
38
+ * `setProfile` accept the input only for directory creation to fail later
39
+ * with a confusing `ENOENT`/`EINVAL`. Case-insensitive: NTFS treats `CON`
40
+ * and `con` identically.
41
+ */
42
+ const WINDOWS_RESERVED_BASENAME_RE = /^(?:CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])(?:\..*)?$/i;
43
+
44
+ /**
45
+ * Normalize and validate a profile name. Returns `undefined` for the implicit
46
+ * default (empty string, whitespace, or the explicit "default" sentinel) and
47
+ * throws for syntactically invalid or platform-reserved names.
48
+ *
49
+ * Exported so consumers of `@oh-my-pi-zen/pi-utils/dirs` (CLI bootstrap, tests,
50
+ * downstream tools) can validate user input without re-deriving the rules.
51
+ */
52
+ export function normalizeProfileName(profile: string | undefined): string | undefined {
53
+ const normalized = profile?.trim();
54
+ if (!normalized || normalized === "default") return undefined;
55
+ if (
56
+ normalized === "." ||
57
+ normalized === ".." ||
58
+ normalized.endsWith(".") ||
59
+ !PROFILE_NAME_RE.test(normalized) ||
60
+ WINDOWS_RESERVED_BASENAME_RE.test(normalized)
61
+ ) {
62
+ throw new Error(
63
+ `Invalid OMP profile "${profile}". Profile names must match ${PROFILE_NAME_RE.source}, ` +
64
+ `cannot be "." or "..", cannot end with ".", and cannot be a Windows reserved device name ` +
65
+ `(CON, PRN, AUX, NUL, COM0-9, LPT0-9, or any of those with an extension).`,
66
+ );
67
+ }
68
+ return normalized;
69
+ }
70
+
71
+ /**
72
+ * Resolve the active profile from the two profile env vars. `OMP_PROFILE` is the
73
+ * canonical variable and takes precedence; `PI_PROFILE` is the legacy
74
+ * compatibility fallback, consulted only when `OMP_PROFILE` is undefined. An
75
+ * explicitly-empty `OMP_PROFILE` therefore selects the default profile rather
76
+ * than silently inheriting `PI_PROFILE`. Delegates validation/normalization to
77
+ * {@link normalizeProfileName} (which throws on a syntactically invalid value).
78
+ */
79
+ export function resolveProfileEnv(omp: string | undefined, pi: string | undefined): string | undefined {
80
+ return normalizeProfileName(omp !== undefined ? omp : pi);
81
+ }
82
+
83
+ function getProfileFromEnv(): string | undefined {
84
+ return resolveProfileEnv(process.env.OMP_PROFILE, process.env.PI_PROFILE);
85
+ }
86
+
87
+ /**
88
+ * Module-load profile resolution. Unlike {@link getProfileFromEnv}, an invalid
89
+ * OMP_PROFILE/PI_PROFILE value does NOT throw here — a bad env var must not
90
+ * crash a bare `import` of this module with an uncaught stack trace before the
91
+ * CLI's error handling is in scope. The default profile is used instead; the
92
+ * CLI re-validates the env (see `runCli` in coding-agent/src/cli.ts) so the
93
+ * user still gets a clean "Invalid OMP profile" message.
94
+ */
95
+ function readProfileFromEnvSafe(): string | undefined {
96
+ try {
97
+ return getProfileFromEnv();
98
+ } catch {
99
+ return undefined;
100
+ }
101
+ }
102
+
103
+ function getBaseConfigRoot(): string {
104
+ return path.join(os.homedir(), getConfigDirName());
105
+ }
106
+
107
+ function getProfileConfigRoot(profile: string | undefined): string {
108
+ const root = getBaseConfigRoot();
109
+ return profile ? path.join(root, "profiles", profile) : root;
110
+ }
111
+
112
+ function readPiProfileFromEnvSafe(): string | undefined {
113
+ try {
114
+ return normalizeProfileName(process.env.PI_PROFILE);
115
+ } catch {
116
+ return undefined;
117
+ }
118
+ }
119
+
120
+ function getProfileAgentDir(profile: string): string {
121
+ return path.join(getProfileConfigRoot(profile), "agent");
122
+ }
123
+
124
+ function isProfileDerivedAgentDir(profile: string | undefined, agentDirEnv: string | undefined): boolean {
125
+ return profile !== undefined && agentDirEnv === getProfileAgentDir(profile);
126
+ }
127
+ // =============================================================================
128
+ // Project directory
129
+ // =============================================================================
130
+
131
+ /**
132
+ * On macOS, strip /private prefix only when both paths resolve to the same location.
133
+ * This preserves aliases like /private/tmp -> /tmp without rewriting unrelated paths.
134
+ */
135
+ function standardizeMacOSPath(p: string): string {
136
+ if (process.platform !== "darwin" || !p.startsWith("/private/")) return p;
137
+ const stripped = p.slice("/private".length);
138
+ try {
139
+ if (fs.realpathSync(p) === fs.realpathSync(stripped)) {
140
+ return stripped;
141
+ }
142
+ } catch {}
143
+ return p;
144
+ }
145
+
146
+ export function resolveEquivalentPath(inputPath: string): string {
147
+ const resolvedPath = path.resolve(inputPath);
148
+ try {
149
+ return fs.realpathSync(resolvedPath);
150
+ } catch {
151
+ return resolvedPath;
152
+ }
153
+ }
154
+
155
+ export function normalizePathForComparison(inputPath: string): string {
156
+ const resolvedPath = resolveEquivalentPath(inputPath);
157
+ return process.platform === "win32" ? resolvedPath.toLowerCase() : resolvedPath;
158
+ }
159
+
160
+ export function pathIsWithin(root: string, candidate: string): boolean {
161
+ const normalizedRoot = normalizePathForComparison(root);
162
+ const normalizedCandidate = normalizePathForComparison(candidate);
163
+ const relative = path.relative(normalizedRoot, normalizedCandidate);
164
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
165
+ }
166
+
167
+ export function relativePathWithinRoot(root: string, candidate: string): string | null {
168
+ if (!pathIsWithin(root, candidate)) return null;
169
+ const normalizedRoot = normalizePathForComparison(root);
170
+ const normalizedCandidate = normalizePathForComparison(candidate);
171
+ const relative = path.relative(normalizedRoot, normalizedCandidate);
172
+ return relative || null;
173
+ }
174
+
175
+ let projectDir = standardizeMacOSPath(process.cwd());
176
+
177
+ /** Get the project directory. */
178
+ export function getProjectDir(): string {
179
+ return projectDir;
180
+ }
181
+
182
+ /** Set the project directory. */
183
+ export function setProjectDir(dir: string): void {
184
+ projectDir = standardizeMacOSPath(path.resolve(dir));
185
+ process.chdir(projectDir);
186
+ }
187
+
188
+ /**
189
+ * Whether `dir` resolves to an existing directory. Any stat failure — a deleted
190
+ * path (ENOENT), permission error, or a non-directory — returns `false`, so
191
+ * callers can decide whether a directory is safe to `chdir` into or adopt as a
192
+ * working directory before {@link setProjectDir} throws on it.
193
+ */
194
+ export async function directoryExists(dir: string): Promise<boolean> {
195
+ try {
196
+ return (await fs.promises.stat(dir)).isDirectory();
197
+ } catch {
198
+ return false;
199
+ }
200
+ }
201
+
202
+ /** Get the config directory name relative to home (e.g. ".omp" or PI_CONFIG_DIR override). */
203
+ export function getConfigDirName(): string {
204
+ return process.env.PI_CONFIG_DIR || CONFIG_DIR_NAME;
205
+ }
206
+
207
+ /** Get the config agent directory name relative to home (e.g. ".omp/agent" or PI_CONFIG_DIR + "/agent"). */
208
+ export function getConfigAgentDirName(): string {
209
+ const profile = getActiveProfile();
210
+ return profile ? path.join(getConfigDirName(), "profiles", profile, "agent") : `${getConfigDirName()}/agent`;
211
+ }
212
+
213
+ // =============================================================================
214
+ // DirResolver — cached, XDG-aware path resolution
215
+ // =============================================================================
216
+
217
+ type XdgCategory = "data" | "state" | "cache";
218
+
219
+ /**
220
+ * Resolves and caches all omp directory paths. On Linux, when XDG environment
221
+ * variables are set, paths are redirected under $XDG_*_HOME/omp/. A new
222
+ * instance is created whenever the agent directory changes, which naturally
223
+ * invalidates all cached paths.
224
+ */
225
+ class DirResolver {
226
+ readonly configRoot: string;
227
+ readonly agentDir: string;
228
+
229
+ // Per-category base dirs. Without XDG, all three equal configRoot / agentDir.
230
+ // With XDG on Linux, they point to $XDG_*_HOME/omp/.
231
+ readonly #rootDirs: Record<XdgCategory, string>;
232
+ readonly #agentDirs: Record<XdgCategory, string>;
233
+
234
+ readonly #rootCache = new Map<string, string>();
235
+ readonly #agentCache = new Map<string, string>();
236
+
237
+ constructor(options: { agentDirOverride?: string; profile?: string } = {}) {
238
+ const profile = normalizeProfileName(options.profile);
239
+ this.configRoot = getProfileConfigRoot(profile);
240
+
241
+ const defaultAgent = path.join(this.configRoot, "agent");
242
+ const agentDirOverride = profile ? undefined : options.agentDirOverride;
243
+ this.agentDir = agentDirOverride ? path.resolve(agentDirOverride) : defaultAgent;
244
+ const isDefault = this.agentDir === defaultAgent;
245
+
246
+ // XDG is a Linux convention. On supported platforms, default profile state
247
+ // resolves under $XDG_*_HOME/omp once `omp config init-xdg` has migrated
248
+ // the user's data. Named profiles follow a stricter rule: the XDG choice
249
+ // is keyed on the profile-specific XDG path, never the base app root.
250
+ //
251
+ // Why: if we consulted the base app root for named profiles too, the same
252
+ // profile could resolve to `~/.omp/profiles/<name>` on first activation
253
+ // (when no $XDG_*_HOME/omp exists yet) and then silently move to
254
+ // `$XDG_*_HOME/omp/profiles/<name>` the moment the base appeared, orphaning
255
+ // the earlier state. Pinning on the profile path means a profile's location
256
+ // is decided at first activation and stays put until the user explicitly
257
+ // migrates it (e.g. by mkdir'ing the XDG profile dir).
258
+ let xdgData: string | undefined;
259
+ let xdgState: string | undefined;
260
+ let xdgCache: string | undefined;
261
+ if ((process.platform === "linux" || process.platform === "darwin") && isDefault) {
262
+ const resolveIf = (envVar: string) => {
263
+ const value = process.env[envVar];
264
+ if (!value) return undefined;
265
+ try {
266
+ const appRoot = path.join(value, APP_NAME);
267
+ if (profile) {
268
+ const profilePath = path.join(appRoot, "profiles", profile);
269
+ if (fs.existsSync(profilePath)) {
270
+ return profilePath;
271
+ }
272
+ return undefined;
273
+ }
274
+ if (fs.existsSync(appRoot)) {
275
+ return appRoot;
276
+ }
277
+ } catch {}
278
+ return undefined;
279
+ };
280
+ xdgData = resolveIf("XDG_DATA_HOME");
281
+ xdgState = resolveIf("XDG_STATE_HOME");
282
+ xdgCache = resolveIf("XDG_CACHE_HOME");
283
+ }
284
+
285
+ this.#rootDirs = {
286
+ data: xdgData ?? this.configRoot,
287
+ state: xdgState ?? this.configRoot,
288
+ cache: xdgCache ?? this.configRoot,
289
+ };
290
+ // XDG flattens the agent/ prefix: ~/.omp/agent/sessions → $XDG_DATA_HOME/omp/sessions
291
+ this.#agentDirs = {
292
+ data: xdgData ?? this.agentDir,
293
+ state: xdgState ?? this.agentDir,
294
+ cache: xdgCache ?? this.agentDir,
295
+ };
296
+ }
297
+
298
+ /** Config-root subdirectory, with optional XDG override. */
299
+ rootSubdir(subdir: string, xdg?: XdgCategory): string {
300
+ const cached = this.#rootCache.get(subdir);
301
+ if (cached) return cached;
302
+ const base = xdg ? this.#rootDirs[xdg] : this.configRoot;
303
+ const result = path.join(base, subdir);
304
+ this.#rootCache.set(subdir, result);
305
+ return result;
306
+ }
307
+
308
+ /** Agent subdirectory, with optional XDG override. */
309
+ agentSubdir(userAgentDir: string | undefined, subdir: string, xdg?: XdgCategory): string {
310
+ if (!userAgentDir || userAgentDir === this.agentDir) {
311
+ const cached = this.#agentCache.get(subdir);
312
+ if (cached) return cached;
313
+ const base = xdg ? this.#agentDirs[xdg] : this.agentDir;
314
+ const result = path.join(base, subdir);
315
+ this.#agentCache.set(subdir, result);
316
+ return result;
317
+ }
318
+ return path.join(userAgentDir, subdir);
319
+ }
320
+ }
321
+
322
+ /**
323
+ * Decide which `PI_CODING_AGENT_DIR` value to capture as the pre-profile
324
+ * baseline. A value equal to a profile's derived agent dir is profile-derived
325
+ * (propagated by a parent's `setProfile`), so it must NOT be snapshotted as the
326
+ * default-mode baseline — otherwise default mode would resolve to the profile's
327
+ * agent dir. The profile source can be the active profile or a lower-priority
328
+ * `PI_PROFILE` that was bypassed because `OMP_PROFILE` explicitly selected the
329
+ * default profile. Returns `undefined` in those cases so reset falls back to the
330
+ * standard `~/.omp/agent`.
331
+ */
332
+ function resolvePreProfileAgentDir(
333
+ profile: string | undefined,
334
+ agentDirEnv: string | undefined,
335
+ profileAgentDirSource: string | undefined = profile,
336
+ ): string | undefined {
337
+ return isProfileDerivedAgentDir(profile ?? profileAgentDirSource, agentDirEnv) ? undefined : agentDirEnv;
338
+ }
339
+
340
+ let activeProfile = readProfileFromEnvSafe();
341
+
342
+ /**
343
+ * Resolve the agent-dir override for the current `activeProfile` from the live
344
+ * environment. A named profile derives its own agent dir (no override); default
345
+ * mode honors a non-profile `PI_CODING_AGENT_DIR` (see
346
+ * {@link resolvePreProfileAgentDir}). Shared by the module-load resolver and
347
+ * {@link refreshDirsFromEnv} so both apply identical logic.
348
+ */
349
+ function resolveActiveAgentDirOverride(): string | undefined {
350
+ return activeProfile
351
+ ? undefined
352
+ : resolvePreProfileAgentDir(undefined, process.env.PI_CODING_AGENT_DIR, readPiProfileFromEnvSafe());
353
+ }
354
+
355
+ let dirs = new DirResolver({
356
+ agentDirOverride: resolveActiveAgentDirOverride(),
357
+ profile: activeProfile,
358
+ });
359
+ /**
360
+ * Snapshot of `PI_CODING_AGENT_DIR` from before the first named-profile
361
+ * activation. Reset paths restore this value (or its absence) instead of
362
+ * unconditionally deleting the env var. Without the snapshot, a process started
363
+ * with `PI_CODING_AGENT_DIR=/custom` then `setProfile("work")` then
364
+ * `setProfile(undefined)` would silently lose `/custom` and fall back to
365
+ * `~/.omp/agent`. Captured at module load — ignoring a profile-derived value
366
+ * inherited from a parent's `setProfile` (see {@link resolvePreProfileAgentDir})
367
+ * — and refreshed on `setAgentDir`, since that call is the user explicitly
368
+ * redefining the baseline.
369
+ */
370
+ let preProfileAgentDirEnv: string | undefined = resolvePreProfileAgentDir(
371
+ activeProfile,
372
+ process.env.PI_CODING_AGENT_DIR,
373
+ activeProfile ?? readPiProfileFromEnvSafe(),
374
+ );
375
+ // Anchor home for the resolver. Captured at module load to stay stable across
376
+ // test mocks of `os.homedir()`. `getPluginsDir(home)` compares against this so
377
+ // production callers (`home === RESOLVER_HOME`) hit the XDG-aware resolver while
378
+ // tests passing a temp HOME short-circuit to a deterministic path.
379
+ const RESOLVER_HOME = os.homedir();
380
+
381
+ /**
382
+ * Rebuild the dirs resolver from the current environment, reusing the profile
383
+ * resolved at module load. Directory-affecting keys (XDG_*_HOME and, in default
384
+ * mode, `PI_CODING_AGENT_DIR`) loaded from a profile/agent `.env` only reach
385
+ * `process.env` *after* this module froze the resolver at import time, so
386
+ * `env.ts` calls this once after applying its `.env` files. The agent `.env`
387
+ * location derives from the profile name + home before this runs, so the
388
+ * rebuild re-reads only the directory vars, never the profile selection. The
389
+ * `preProfileAgentDirEnv` snapshot is intentionally left untouched.
390
+ */
391
+ export function refreshDirsFromEnv(): void {
392
+ dirs = new DirResolver({
393
+ agentDirOverride: resolveActiveAgentDirOverride(),
394
+ profile: activeProfile,
395
+ });
396
+ }
397
+
398
+ // =============================================================================
399
+ // Root directories
400
+ // =============================================================================
401
+
402
+ /** Get the config root directory (~/.omp). */
403
+ export function getConfigRootDir(): string {
404
+ return dirs.configRoot;
405
+ }
406
+
407
+ /** Set the coding agent directory. Creates a fresh resolver, invalidating all cached paths. */
408
+ export function setAgentDir(dir: string): void {
409
+ activeProfile = undefined;
410
+ dirs = new DirResolver({ agentDirOverride: dir });
411
+ process.env.PI_CODING_AGENT_DIR = dir;
412
+ preProfileAgentDirEnv = dir;
413
+ for (const key of PROFILE_ENV_KEYS) {
414
+ delete process.env[key];
415
+ }
416
+ }
417
+
418
+ /**
419
+ * Test-only: reset the pre-profile `PI_CODING_AGENT_DIR` snapshot to whatever
420
+ * the current environment looks like. Cross-suite test pollution can otherwise
421
+ * leak a stale snapshot through `setAgentDir` and corrupt `setProfile(undefined)`
422
+ * restore semantics. Production code MUST NOT call this — the snapshot's
423
+ * lifecycle is owned by `setAgentDir` / `setProfile` and a runtime caller has
424
+ * no business clearing it.
425
+ */
426
+ export function __resetProfileSnapshotForTests(): void {
427
+ preProfileAgentDirEnv = resolvePreProfileAgentDir(
428
+ activeProfile,
429
+ process.env.PI_CODING_AGENT_DIR,
430
+ activeProfile ?? readPiProfileFromEnvSafe(),
431
+ );
432
+ }
433
+
434
+ /**
435
+ * Test-only: rebuild profile + directory state from the current process env.
436
+ * Production code keeps the module-load profile stable; tests that mutate
437
+ * `setAgentDir`/`setProfile` need an exact restore point after they put env vars
438
+ * back.
439
+ */
440
+ export function __resetDirsFromEnvForTests(): void {
441
+ activeProfile = readProfileFromEnvSafe();
442
+ __resetProfileSnapshotForTests();
443
+ refreshDirsFromEnv();
444
+ }
445
+
446
+ /** Activate a named profile. Passing undefined or "default" returns to the default profile. */
447
+ export function setProfile(profile: string | undefined): void {
448
+ const next = normalizeProfileName(profile);
449
+ if (next && !activeProfile) {
450
+ // First activation of a named profile in this process: snapshot the
451
+ // current PI_CODING_AGENT_DIR so a later reset can restore the user's
452
+ // explicit override. Subsequent profile switches keep the original
453
+ // snapshot — the "pre-profile" baseline is the state before profiles
454
+ // entered the picture, not the state between two activations.
455
+ preProfileAgentDirEnv = resolvePreProfileAgentDir(
456
+ undefined,
457
+ process.env.PI_CODING_AGENT_DIR,
458
+ readPiProfileFromEnvSafe(),
459
+ );
460
+ }
461
+ activeProfile = next;
462
+ if (activeProfile) {
463
+ dirs = new DirResolver({ profile: activeProfile });
464
+ process.env.OMP_PROFILE = activeProfile;
465
+ process.env.PI_PROFILE = activeProfile;
466
+ process.env.PI_CODING_AGENT_DIR = dirs.agentDir;
467
+ } else {
468
+ for (const key of PROFILE_ENV_KEYS) {
469
+ delete process.env[key];
470
+ }
471
+ if (preProfileAgentDirEnv === undefined) {
472
+ delete process.env.PI_CODING_AGENT_DIR;
473
+ } else {
474
+ process.env.PI_CODING_AGENT_DIR = preProfileAgentDirEnv;
475
+ }
476
+ dirs = new DirResolver({ agentDirOverride: preProfileAgentDirEnv });
477
+ }
478
+ }
479
+
480
+ /** Get the active named profile. Undefined means the default profile. */
481
+ export function getActiveProfile(): string | undefined {
482
+ return activeProfile;
483
+ }
484
+
485
+ /** Resolve the config root that backs a profile without activating it. */
486
+ export function getProfileRootDir(profile: string | undefined): string {
487
+ return getProfileConfigRoot(normalizeProfileName(profile));
488
+ }
489
+ /** Get the agent config directory (~/.omp/agent). */
490
+ export function getAgentDir(): string {
491
+ return dirs.agentDir;
492
+ }
493
+
494
+ /** Get the project-local config directory (.omp). */
495
+ export function getProjectAgentDir(cwd: string = getProjectDir()): string {
496
+ return path.join(cwd, CONFIG_DIR_NAME);
497
+ }
498
+
499
+ // =============================================================================
500
+ // Config-root subdirectories (~/.omp/*)
501
+ // =============================================================================
502
+
503
+ /** Get the reports directory (~/.omp/reports). */
504
+ export function getReportsDir(): string {
505
+ return dirs.rootSubdir("reports", "state");
506
+ }
507
+
508
+ /** Get the logs directory (~/.omp/logs). */
509
+ export function getLogsDir(): string {
510
+ return dirs.rootSubdir("logs", "state");
511
+ }
512
+
513
+ /** Get the path to a dated log file (~/.omp/logs/omp.YYYY-MM-DD.log). */
514
+ export function getLogPath(date = new Date()): string {
515
+ return path.join(getLogsDir(), `${APP_NAME}.${date.toISOString().slice(0, 10)}.log`);
516
+ }
517
+
518
+ /**
519
+ * Get the plugins directory (~/.omp/plugins or its XDG equivalent).
520
+ *
521
+ * No-arg form (production callers) goes through the XDG-aware DirResolver so
522
+ * reads and writes always agree. The optional `home` parameter is for test
523
+ * isolation: when it differs from `os.homedir()` it short-circuits the resolver
524
+ * and returns `<home>/<configDir>/plugins` so tests with a temp HOME get a
525
+ * deterministic path. Passing `os.homedir()` explicitly is identical to the
526
+ * no-arg form — XDG semantics are preserved.
527
+ */
528
+ export function getPluginsDir(home?: string): string {
529
+ if (home !== undefined && home !== RESOLVER_HOME) {
530
+ return path.join(home, getConfigDirName(), "plugins");
531
+ }
532
+ return dirs.rootSubdir("plugins", "data");
533
+ }
534
+
535
+ /** Where npm installs packages (~/.omp/plugins/node_modules). */
536
+ export function getPluginsNodeModules(home?: string): string {
537
+ return path.join(getPluginsDir(home), "node_modules");
538
+ }
539
+
540
+ /** Plugin manifest (~/.omp/plugins/package.json). */
541
+ export function getPluginsPackageJson(home?: string): string {
542
+ return path.join(getPluginsDir(home), "package.json");
543
+ }
544
+
545
+ /** Plugin lock file (~/.omp/plugins/omp-plugins.lock.json). */
546
+ export function getPluginsLockfile(home?: string): string {
547
+ return path.join(getPluginsDir(home), "omp-plugins.lock.json");
548
+ }
549
+
550
+ /** Get the remote mount directory (~/.omp/remote). */
551
+ export function getRemoteDir(): string {
552
+ return dirs.rootSubdir("remote", "data");
553
+ }
554
+
555
+ /**
556
+ * Expand a leading `~` and require an absolute result. Returns `undefined` for
557
+ * empty/whitespace input or a path that is still relative after expansion.
558
+ *
559
+ * A worktree base is process-global and consumed by both creation
560
+ * (PR checkout, task isolation) and cleanup (`omp worktree`). A relative value
561
+ * would resolve against whatever cwd happened to launch `omp`, so checkout and
562
+ * cleanup could disagree — we refuse it rather than silently bind it to cwd.
563
+ */
564
+ function resolveWorktreeBase(value: string | undefined): string | undefined {
565
+ const trimmed = value?.trim();
566
+ if (!trimmed) return undefined;
567
+ let p = trimmed;
568
+ if (p === "~") p = os.homedir();
569
+ else if (p.startsWith("~/") || p.startsWith("~\\")) p = os.homedir() + p.slice(1);
570
+ return path.isAbsolute(p) ? path.normalize(p) : undefined;
571
+ }
572
+
573
+ let worktreesDirOverride: string | undefined;
574
+
575
+ /**
576
+ * Relocate the base directory for agent-managed worktrees (PR checkouts, task
577
+ * isolation, and `omp worktree` cleanup all read the same base). Driven by the
578
+ * `worktree.base` setting in coding-agent; pass `undefined`/empty to clear and
579
+ * fall back to `OMP_WORKTREE_DIR` or the `~/.omp/wt` default.
580
+ *
581
+ * `~` is expanded and a relative path is rejected (see {@link resolveWorktreeBase}).
582
+ * Returns the absolute path that took effect, or `undefined` if the input was
583
+ * cleared or rejected — callers can warn on a non-empty input that returns
584
+ * `undefined`.
585
+ */
586
+ export function setWorktreesDir(dir: string | undefined): string | undefined {
587
+ worktreesDirOverride = resolveWorktreeBase(dir);
588
+ return worktreesDirOverride;
589
+ }
590
+
591
+ /**
592
+ * Get the agent-managed worktrees directory. Resolution order: the
593
+ * `OMP_WORKTREE_DIR` env var, then the {@link setWorktreesDir} override (the
594
+ * `worktree.base` setting), then the `~/.omp/wt` default. The env var and the
595
+ * override are both `~`-expanded and must be absolute; a relative value is
596
+ * ignored and resolution falls through.
597
+ */
598
+ export function getWorktreesDir(): string {
599
+ return resolveWorktreeBase(process.env.OMP_WORKTREE_DIR) ?? worktreesDirOverride ?? dirs.rootSubdir("wt", "data");
600
+ }
601
+
602
+ /** Get the SSH control socket directory (~/.omp/ssh-control). */
603
+ export function getSshControlDir(): string {
604
+ return dirs.rootSubdir("ssh-control", "state");
605
+ }
606
+
607
+ /** Get the remote host info directory (~/.omp/remote-host). */
608
+ export function getRemoteHostDir(): string {
609
+ return dirs.rootSubdir("remote-host", "data");
610
+ }
611
+
612
+ /** Get the managed Python venv directory (~/.omp/python-env). */
613
+ export function getPythonEnvDir(): string {
614
+ return dirs.rootSubdir("python-env", "data");
615
+ }
616
+
617
+ /** Get the shared Python gateway state directory (~/.omp/agent/python-gateway; XDG default: $XDG_STATE_HOME/omp/python-gateway). */
618
+ export function getPythonGatewayDir(): string {
619
+ return dirs.agentSubdir(undefined, "python-gateway", "state");
620
+ }
621
+
622
+ /** Get the puppeteer sandbox directory (~/.omp/puppeteer). */
623
+ export function getPuppeteerDir(): string {
624
+ return dirs.rootSubdir("puppeteer", "cache");
625
+ }
626
+
627
+ /** Get DOCS_RS cache directory () */
628
+ export function getDocsRsCacheDir(): string {
629
+ return dirs.rootSubdir("webcache", "cache");
630
+ }
631
+
632
+ /**Get AutoQa db directory */
633
+ export function getAutoQaDbDir(): string {
634
+ return dirs.rootSubdir("autoqa.db", "data");
635
+ }
636
+ /**
637
+ * Stable 7-character hex digest of an absolute filesystem path.
638
+ *
639
+ * Used to pack the project identity into a single short fs-safe segment
640
+ * (e.g. PR-checkout and task-isolation worktree dirs under `~/.omp/wt/`).
641
+ * Bun.hash is non-cryptographic — collision space is ~2^28, which is fine
642
+ * for naming a handful of repos on a single machine. Same input on the
643
+ * same Bun runtime yields the same output.
644
+ */
645
+ export function hashPath(absPath: string): string {
646
+ return Bun.hash(path.resolve(absPath)).toString(16).padStart(16, "0").slice(-7);
647
+ }
648
+
649
+ /** Get the path to a single worktree directory (~/.omp/wt/<segment>). */
650
+ export function getWorktreeDir(segment: string): string {
651
+ return path.join(getWorktreesDir(), segment);
652
+ }
653
+
654
+ /** Get the GPU cache path (~/.omp/gpu_cache.json). */
655
+ export function getGpuCachePath(): string {
656
+ return dirs.rootSubdir("gpu_cache.json", "cache");
657
+ }
658
+
659
+ /**
660
+ * Get the GitHub view cache database path (~/.omp/cache/github-cache.db).
661
+ * Honors the `OMP_GITHUB_CACHE_DB` env var when set so tests can isolate the
662
+ * cache file without touching the rest of the config root.
663
+ */
664
+ export function getGithubCacheDbPath(): string {
665
+ const override = process.env.OMP_GITHUB_CACHE_DB;
666
+ if (override) return override;
667
+ return dirs.rootSubdir(path.join("cache", "github-cache.db"), "cache");
668
+ }
669
+
670
+ /**
671
+ * Get the encrypted auth-broker snapshot cache path (~/.omp/cache/auth-broker-snapshot.enc).
672
+ * Honors the `OMP_AUTH_BROKER_SNAPSHOT_CACHE` env var when set so tests and
673
+ * operators can isolate or relocate the cache file.
674
+ */
675
+ export function getAuthBrokerSnapshotCachePath(): string {
676
+ const override = process.env.OMP_AUTH_BROKER_SNAPSHOT_CACHE;
677
+ if (override) return override;
678
+ return dirs.rootSubdir(path.join("cache", "auth-broker-snapshot.enc"), "cache");
679
+ }
680
+
681
+ /** Get the local FastEmbed model cache directory (~/.omp/cache/fastembed). */
682
+ export function getFastembedCacheDir(): string {
683
+ return dirs.rootSubdir(path.join("cache", "fastembed"), "cache");
684
+ }
685
+
686
+ /** Get the on-demand fastembed runtime install root (~/.omp/cache/fastembed-runtime). */
687
+ export function getFastembedRuntimeDir(): string {
688
+ return dirs.rootSubdir(path.join("cache", "fastembed-runtime"), "cache");
689
+ }
690
+
691
+ /** Get the natives directory (~/.omp/natives). */
692
+ export function getNativesDir(): string {
693
+ return dirs.rootSubdir("natives", "cache");
694
+ }
695
+
696
+ /** Get the stats database path (~/.omp/stats.db). */
697
+ export function getStatsDbPath(): string {
698
+ return dirs.rootSubdir("stats.db", "data");
699
+ }
700
+
701
+ /** Get the autoresearch state directory (~/.omp/autoresearch). */
702
+ export function getAutoresearchDir(): string {
703
+ return dirs.rootSubdir("autoresearch", "state");
704
+ }
705
+
706
+ /** Get the per-project autoresearch state directory (~/.omp/autoresearch/<encoded-project>). */
707
+ export function getAutoresearchProjectDir(encodedProject: string): string {
708
+ return path.join(getAutoresearchDir(), encodedProject);
709
+ }
710
+
711
+ /** Get the per-project autoresearch SQLite database path (~/.omp/autoresearch/<encoded-project>.db). */
712
+ export function getAutoresearchDbPath(encodedProject: string): string {
713
+ return path.join(getAutoresearchDir(), `${encodedProject}.db`);
714
+ }
715
+
716
+ /** Get the per-run artifact directory (~/.omp/autoresearch/<encoded-project>/runs/<runId>). */
717
+ export function getAutoresearchRunDir(encodedProject: string, runId: number): string {
718
+ return path.join(getAutoresearchProjectDir(encodedProject), "runs", String(runId).padStart(4, "0"));
719
+ }
720
+
721
+ // =============================================================================
722
+ // Agent subdirectories (~/.omp/agent/*)
723
+ // =============================================================================
724
+
725
+ /** Get the path to agent.db (SQLite database for settings and auth storage). */
726
+ export function getAgentDbPath(agentDir?: string): string {
727
+ return dirs.agentSubdir(agentDir, "agent.db", "data");
728
+ }
729
+
730
+ /** Get the last-seen-changelog-version marker file (~/.omp/agent/last-changelog-version). */
731
+ export function getLastChangelogVersionPath(agentDir?: string): string {
732
+ return dirs.agentSubdir(agentDir, "last-changelog-version", "state");
733
+ }
734
+
735
+ /** Get the path to history.db (SQLite database for session history). */
736
+ export function getHistoryDbPath(agentDir?: string): string {
737
+ return dirs.agentSubdir(agentDir, "history.db", "data");
738
+ }
739
+
740
+ /** Get the path to models.db (model cache database). */
741
+ export function getModelDbPath(agentDir?: string): string {
742
+ return dirs.agentSubdir(agentDir, "models.db", "data");
743
+ }
744
+
745
+ /** Get the tiny title model cache directory (~/.omp/agent/cache/tiny-models). */
746
+ export function getTinyModelsCacheDir(agentDir?: string): string {
747
+ return dirs.agentSubdir(agentDir, path.join("cache", "tiny-models"), "cache");
748
+ }
749
+
750
+ /** Get the document conversion cache directory (~/.omp/agent/cache/document-conversions; XDG default: $XDG_CACHE_HOME/omp/cache/document-conversions). */
751
+ export function getDocumentConversionCacheDir(agentDir?: string): string {
752
+ return dirs.agentSubdir(agentDir, path.join("cache", "document-conversions"), "cache");
753
+ }
754
+
755
+ /** Get the sessions directory (~/.omp/agent/sessions). */
756
+ export function getSessionsDir(agentDir?: string): string {
757
+ return dirs.agentSubdir(agentDir, "sessions", "data");
758
+ }
759
+
760
+ /** Get the content-addressed blob store directory (~/.omp/agent/blobs). */
761
+ export function getBlobsDir(agentDir?: string): string {
762
+ return dirs.agentSubdir(agentDir, "blobs", "data");
763
+ }
764
+
765
+ /** Get the custom themes directory (~/.omp/agent/themes). */
766
+ export function getCustomThemesDir(agentDir?: string): string {
767
+ return dirs.agentSubdir(agentDir, "themes");
768
+ }
769
+
770
+ /** Get the tools directory (~/.omp/agent/tools). */
771
+ export function getToolsDir(agentDir?: string): string {
772
+ return dirs.agentSubdir(agentDir, "tools");
773
+ }
774
+
775
+ /** Get the slash commands directory (~/.omp/agent/commands). */
776
+ export function getCommandsDir(agentDir?: string): string {
777
+ return dirs.agentSubdir(agentDir, "commands");
778
+ }
779
+
780
+ /** Get the prompts directory (~/.omp/agent/prompts). */
781
+ export function getPromptsDir(agentDir?: string): string {
782
+ return dirs.agentSubdir(agentDir, "prompts");
783
+ }
784
+
785
+ /** Get the user-level Python modules directory (~/.omp/agent/modules). */
786
+ export function getAgentModulesDir(agentDir?: string): string {
787
+ return dirs.agentSubdir(agentDir, "modules");
788
+ }
789
+
790
+ /** Get the memories directory (~/.omp/agent/memories). */
791
+ export function getMemoriesDir(agentDir?: string): string {
792
+ return dirs.agentSubdir(agentDir, "memories", "state");
793
+ }
794
+
795
+ /** Get the terminal sessions directory (~/.omp/agent/terminal-sessions). */
796
+ export function getTerminalSessionsDir(agentDir?: string): string {
797
+ return dirs.agentSubdir(agentDir, "terminal-sessions", "state");
798
+ }
799
+
800
+ /** Get the crash log path (~/.omp/agent/omp-crash.log). */
801
+ export function getCrashLogPath(agentDir?: string): string {
802
+ return dirs.agentSubdir(agentDir, "omp-crash.log", "state");
803
+ }
804
+
805
+ /** Get the debug log path (~/.omp/agent/omp-debug.log). */
806
+ export function getDebugLogPath(agentDir?: string): string {
807
+ return dirs.agentSubdir(agentDir, `${APP_NAME}-debug.log`, "state");
808
+ }
809
+
810
+ // =============================================================================
811
+ // Project subdirectories (.omp/*)
812
+ // =============================================================================
813
+
814
+ /** Get the project-level Python modules directory (.omp/modules). */
815
+ export function getProjectModulesDir(cwd: string = getProjectDir()): string {
816
+ return path.join(getProjectAgentDir(cwd), "modules");
817
+ }
818
+
819
+ /** Get the project-level prompts directory (.omp/prompts). */
820
+ export function getProjectPromptsDir(cwd: string = getProjectDir()): string {
821
+ return path.join(getProjectAgentDir(cwd), "prompts");
822
+ }
823
+
824
+ /** Get the project-level plugin overrides path (.omp/plugin-overrides.json). */
825
+ export function getProjectPluginOverridesPath(cwd: string = getProjectDir()): string {
826
+ return path.join(getProjectAgentDir(cwd), "plugin-overrides.json");
827
+ }
828
+
829
+ // =============================================================================
830
+ // MCP config paths
831
+ // =============================================================================
832
+
833
+ /** Get the primary MCP config file path (first candidate). */
834
+ export function getMCPConfigPath(scope: "user" | "project", cwd: string = getProjectDir()): string {
835
+ if (scope === "user") {
836
+ return path.join(getAgentDir(), "mcp.json");
837
+ }
838
+ return path.join(getProjectAgentDir(cwd), "mcp.json");
839
+ }
840
+
841
+ /** Get the SSH config file path. */
842
+ export function getSSHConfigPath(scope: "user" | "project", cwd: string = getProjectDir()): string {
843
+ if (scope === "user") {
844
+ return path.join(getAgentDir(), "ssh.json");
845
+ }
846
+ return path.join(getProjectAgentDir(cwd), "ssh.json");
847
+ }
848
+
849
+ // =============================================================================
850
+ // Install identity
851
+ // =============================================================================
852
+
853
+ let cachedInstallId: string | null = null;
854
+
855
+ const INSTALL_ID_FILE = "install-id";
856
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
857
+
858
+ /**
859
+ * Persistent per-install UUID stored at `~/.omp/install-id`.
860
+ *
861
+ * Generated lazily on first call and persisted with `O_CREAT|O_EXCL` so
862
+ * concurrent first-call races don't clobber each other (loser re-reads the
863
+ * winner's id). Survives independently of agent state: deleting
864
+ * `~/.omp/agent/` does not regenerate it. Server-side dedup for grievance
865
+ * pushes (and similar telemetry) keys on this id.
866
+ *
867
+ * Anchored to the base config root (`~/.omp/install-id`) regardless of the
868
+ * active profile: install identity is per-install, not per-profile, so every
869
+ * profile shares one id and the global cache stays correct no matter the
870
+ * profile / `getInstallId` call order.
871
+ */
872
+ export function getInstallId(): string {
873
+ if (cachedInstallId) return cachedInstallId;
874
+ const filePath = path.join(getBaseConfigRoot(), INSTALL_ID_FILE);
875
+
876
+ let observedInvalid = false;
877
+ try {
878
+ const existing = fs.readFileSync(filePath, "utf8").trim();
879
+ if (UUID_RE.test(existing)) {
880
+ cachedInstallId = existing;
881
+ return existing;
882
+ }
883
+ // File present but unparseable — fall through and overwrite below.
884
+ observedInvalid = existing.length > 0;
885
+ } catch {}
886
+
887
+ const next = crypto.randomUUID();
888
+ try {
889
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
890
+ // If we already saw garbage in the file, unlink first so O_EXCL doesn't
891
+ // trip on it. Ignored if the unlink races against another writer.
892
+ if (observedInvalid) {
893
+ try {
894
+ fs.unlinkSync(filePath);
895
+ } catch {}
896
+ }
897
+ const fd = fs.openSync(filePath, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
898
+ try {
899
+ fs.writeSync(fd, `${next}\n`);
900
+ } finally {
901
+ fs.closeSync(fd);
902
+ }
903
+ } catch (err) {
904
+ // Lost the create race — re-read whatever the winner wrote.
905
+ if ((err as NodeJS.ErrnoException).code === "EEXIST") {
906
+ try {
907
+ const existing = fs.readFileSync(filePath, "utf8").trim();
908
+ if (UUID_RE.test(existing)) {
909
+ cachedInstallId = existing;
910
+ return existing;
911
+ }
912
+ } catch {}
913
+ }
914
+ // Any other failure: keep the generated id in-memory so the rest of
915
+ // this process has a stable value; future processes will retry.
916
+ }
917
+
918
+ cachedInstallId = next;
919
+ return next;
920
+ }
921
+
922
+ /** Test-only: clear cached install id. Never call from production code. */
923
+ export function __resetInstallIdCacheForTests(): void {
924
+ cachedInstallId = null;
925
+ }