@wraith-ai/core 0.1.0 → 0.1.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 (153) hide show
  1. package/README.md +1 -1
  2. package/dist/{attempt-BeB7EltG.d.mts → attempt-HgararU3.d.mts} +2 -1
  3. package/dist/attempt-HgararU3.d.mts.map +1 -0
  4. package/dist/{capabilities-BPb5HSH6.d.mts → capabilities-CNsPrkB7.d.mts} +2 -1
  5. package/dist/capabilities-CNsPrkB7.d.mts.map +1 -0
  6. package/dist/index.d.mts +6 -5
  7. package/dist/index.d.mts.map +1 -0
  8. package/dist/index.mjs +11 -9
  9. package/dist/index.mjs.map +1 -0
  10. package/dist/{methods-CZp6XGn8.mjs → methods-7Ryz6zbd.mjs} +4 -2
  11. package/dist/methods-7Ryz6zbd.mjs.map +1 -0
  12. package/dist/{model-B6tJ9kX_.mjs → model-C16NUwXW.mjs} +2 -0
  13. package/dist/model-C16NUwXW.mjs.map +1 -0
  14. package/dist/{model-D6LQSveS.d.mts → model-_wqePNTL.d.mts} +4 -3
  15. package/dist/model-_wqePNTL.d.mts.map +1 -0
  16. package/dist/{models-dev-Y0ZikMBQ.d.mts → models-dev-DNgymZy3.d.mts} +3 -2
  17. package/dist/models-dev-DNgymZy3.d.mts.map +1 -0
  18. package/dist/{openai-codex-BhtZvNpm.mjs → openai-codex-Bz1EFPEi.mjs} +3 -1
  19. package/dist/openai-codex-Bz1EFPEi.mjs.map +1 -0
  20. package/dist/{openai-codex-Bk-iG7MZ.mjs → openai-codex-uvjhVoVy.mjs} +6 -4
  21. package/dist/openai-codex-uvjhVoVy.mjs.map +1 -0
  22. package/dist/{openai-compatible-hkXv-P74.mjs → openai-compatible-DBppnQ_N.mjs} +4 -2
  23. package/dist/openai-compatible-DBppnQ_N.mjs.map +1 -0
  24. package/dist/{openrouter-BflQBug2.mjs → openrouter-D8nTOAQo.mjs} +5 -3
  25. package/dist/openrouter-D8nTOAQo.mjs.map +1 -0
  26. package/dist/providers/openai-codex.d.mts +4 -3
  27. package/dist/providers/openai-codex.d.mts.map +1 -0
  28. package/dist/providers/openai-codex.mjs +1 -1
  29. package/dist/providers/openai-compatible.d.mts +3 -2
  30. package/dist/providers/openai-compatible.d.mts.map +1 -0
  31. package/dist/providers/openai-compatible.mjs +1 -1
  32. package/dist/providers/openrouter.d.mts +3 -2
  33. package/dist/providers/openrouter.d.mts.map +1 -0
  34. package/dist/providers/openrouter.mjs +1 -1
  35. package/dist/{shared-8d7RsyPH.mjs → shared-BIJaPhMm.mjs} +3 -1
  36. package/dist/shared-BIJaPhMm.mjs.map +1 -0
  37. package/dist/snapshot.d.mts +3 -2
  38. package/dist/snapshot.d.mts.map +1 -0
  39. package/dist/snapshot.mjs +4999 -4977
  40. package/dist/snapshot.mjs.map +1 -0
  41. package/dist/{turn-effort-DquDDwdE.mjs → turn-effort-C61L4JIt.mjs} +2 -0
  42. package/dist/turn-effort-C61L4JIt.mjs.map +1 -0
  43. package/package.json +3 -2
  44. package/src/agent/agent.ts +90 -0
  45. package/src/agent/attachments.ts +195 -0
  46. package/src/agent/classifier.ts +525 -0
  47. package/src/agent/compact.ts +384 -0
  48. package/src/agent/conversation.ts +300 -0
  49. package/src/agent/cost.ts +164 -0
  50. package/src/agent/inbox.ts +80 -0
  51. package/src/agent/instructions.ts +62 -0
  52. package/src/agent/loop.ts +675 -0
  53. package/src/agent/messages.ts +252 -0
  54. package/src/agent/on-demand.ts +58 -0
  55. package/src/agent/prompts.ts +35 -0
  56. package/src/agent/request-images.ts +94 -0
  57. package/src/agent/stop.ts +37 -0
  58. package/src/agent/title.ts +122 -0
  59. package/src/agent/tool-groups.ts +186 -0
  60. package/src/agent/tools.ts +106 -0
  61. package/src/app.ts +67 -0
  62. package/src/config/credential-file-store.ts +66 -0
  63. package/src/config/environment.ts +105 -0
  64. package/src/config/instructions.ts +157 -0
  65. package/src/config/load.ts +667 -0
  66. package/src/config/locked-file.ts +85 -0
  67. package/src/config/paths.ts +368 -0
  68. package/src/config/schema.ts +363 -0
  69. package/src/config/subagents.ts +156 -0
  70. package/src/config/trust.ts +53 -0
  71. package/src/config/write.ts +241 -0
  72. package/src/errors.ts +85 -0
  73. package/src/events/types.ts +258 -0
  74. package/src/glob.ts +161 -0
  75. package/src/index.ts +681 -0
  76. package/src/logger.ts +47 -0
  77. package/src/paths.ts +143 -0
  78. package/src/permissions/chain.ts +42 -0
  79. package/src/permissions/command.ts +233 -0
  80. package/src/permissions/layered.ts +77 -0
  81. package/src/permissions/match.ts +80 -0
  82. package/src/permissions/modes.ts +48 -0
  83. package/src/permissions/policy.ts +160 -0
  84. package/src/permissions/types.ts +159 -0
  85. package/src/providers/cache.ts +107 -0
  86. package/src/providers/capabilities.ts +77 -0
  87. package/src/providers/catalog-view.ts +91 -0
  88. package/src/providers/catalog.ts +65 -0
  89. package/src/providers/errors.ts +108 -0
  90. package/src/providers/factories/index.ts +15 -0
  91. package/src/providers/factories/openai-codex.ts +382 -0
  92. package/src/providers/factories/openai-compatible.ts +81 -0
  93. package/src/providers/factories/openrouter.ts +165 -0
  94. package/src/providers/factories/shared.ts +22 -0
  95. package/src/providers/model.ts +197 -0
  96. package/src/providers/models-dev.ts +355 -0
  97. package/src/providers/oauth/methods.ts +10 -0
  98. package/src/providers/oauth/openai-codex.ts +228 -0
  99. package/src/providers/oauth.ts +177 -0
  100. package/src/providers/openai-codex.ts +7 -0
  101. package/src/providers/openai-compatible.ts +2 -0
  102. package/src/providers/openrouter.ts +2 -0
  103. package/src/providers/registry.ts +464 -0
  104. package/src/providers/turn-effort.ts +156 -0
  105. package/src/providers/types.ts +83 -0
  106. package/src/session/backend.ts +44 -0
  107. package/src/session/file-store.ts +278 -0
  108. package/src/session/format.ts +1037 -0
  109. package/src/session/memory-store.ts +73 -0
  110. package/src/session/session.ts +153 -0
  111. package/src/session/store.ts +219 -0
  112. package/src/sign-in/attempt.ts +166 -0
  113. package/src/sign-in/loopback.ts +74 -0
  114. package/src/snapshot/data.json +8936 -0
  115. package/src/snapshot/index.ts +37 -0
  116. package/src/tools/bin.ts +364 -0
  117. package/src/tools/builtin.ts +48 -0
  118. package/src/tools/change.ts +88 -0
  119. package/src/tools/define.ts +267 -0
  120. package/src/tools/describe.ts +96 -0
  121. package/src/tools/fs/edit-file.ts +129 -0
  122. package/src/tools/fs/glob.ts +75 -0
  123. package/src/tools/fs/grep.ts +212 -0
  124. package/src/tools/fs/line-endings.ts +17 -0
  125. package/src/tools/fs/list-dir.ts +85 -0
  126. package/src/tools/fs/read-file.ts +230 -0
  127. package/src/tools/fs/ripgrep.ts +211 -0
  128. package/src/tools/fs/write-file.ts +97 -0
  129. package/src/tools/job.ts +252 -0
  130. package/src/tools/mcp/auth-store.ts +127 -0
  131. package/src/tools/mcp/command.ts +151 -0
  132. package/src/tools/mcp/config.ts +168 -0
  133. package/src/tools/mcp/servers.ts +463 -0
  134. package/src/tools/mcp/sign-in.ts +226 -0
  135. package/src/tools/mcp/stdio.ts +204 -0
  136. package/src/tools/mcp/tools.ts +173 -0
  137. package/src/tools/on-demand.ts +184 -0
  138. package/src/tools/registry.ts +935 -0
  139. package/src/tools/shell/bash.ts +217 -0
  140. package/src/tools/shell/find-bash.ts +162 -0
  141. package/src/tools/source.ts +35 -0
  142. package/src/tools/spill.ts +127 -0
  143. package/src/tools/subagents.ts +597 -0
  144. package/src/tools/tasks.ts +603 -0
  145. package/src/tools/to-model.ts +33 -0
  146. package/src/tools/web/address.ts +95 -0
  147. package/src/tools/web/exa.ts +163 -0
  148. package/src/tools/web/fetch.ts +373 -0
  149. package/src/tools/web/html.ts +173 -0
  150. package/src/tools/web/search.ts +111 -0
  151. package/src/tools/web/source.ts +51 -0
  152. package/src/units.ts +18 -0
  153. package/src/version.ts +23 -0
@@ -0,0 +1,85 @@
1
+ import { chmod, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
2
+
3
+ /**
4
+ * A small JSON file that several processes take turns writing: sign-ins whose
5
+ * refresh tokens work once. One writer at a time behind a lock file, and a
6
+ * reader never finds half a file.
7
+ */
8
+
9
+ const FILE_MODE = 0o600;
10
+
11
+ /** Twice a refresh's own timeout: a holder still refreshing is never evicted. */
12
+ const STALE_LOCK_MS = 30_000;
13
+ const LOCK_DEADLINE_MS = 45_000;
14
+
15
+ const RENAME_ATTEMPTS = 10;
16
+ /** What an antivirus or indexer briefly holding the file looks like on Windows. */
17
+ const TRANSIENT_RENAME = new Set(["EPERM", "EBUSY", "EACCES"]);
18
+
19
+ const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
20
+ const errorCode = (error: unknown) => (error as NodeJS.ErrnoException | undefined)?.code;
21
+
22
+ /** The file's text, or undefined when there is none or it cannot be read. */
23
+ export async function readTextFile(file: string): Promise<string | undefined> {
24
+ try {
25
+ return (await readFile(file, "utf8")).replace(/^/, "");
26
+ } catch {
27
+ return undefined;
28
+ }
29
+ }
30
+
31
+ export async function writeFileAtomically(file: string, text: string): Promise<void> {
32
+ const temp = `${file}.${String(process.pid)}.${String(Date.now())}.tmp`;
33
+ await writeFile(temp, text, { encoding: "utf8", mode: FILE_MODE });
34
+ await chmod(temp, FILE_MODE).catch(() => undefined);
35
+
36
+ for (let attempt = 1; ; attempt += 1) {
37
+ try {
38
+ await rename(temp, file);
39
+ return;
40
+ } catch (error) {
41
+ if (!TRANSIENT_RENAME.has(errorCode(error) ?? "") || attempt >= RENAME_ATTEMPTS) {
42
+ await rm(temp, { force: true });
43
+ throw error;
44
+ }
45
+ await sleep(20 * attempt);
46
+ }
47
+ }
48
+ }
49
+
50
+ async function isStale(lock: string): Promise<boolean> {
51
+ try {
52
+ return Date.now() - (await stat(lock)).mtimeMs > STALE_LOCK_MS;
53
+ } catch {
54
+ // Gone already: the next attempt will simply take it.
55
+ return false;
56
+ }
57
+ }
58
+
59
+ /** Runs `work` holding `lock`; `timedOut` is what to throw when it never comes free. */
60
+ export async function withFileLock<T>(lock: string, work: () => Promise<T>, timedOut: () => Error): Promise<T> {
61
+ const deadline = Date.now() + LOCK_DEADLINE_MS;
62
+ for (;;) {
63
+ try {
64
+ const handle = await open(lock, "wx");
65
+ await handle.writeFile(String(process.pid));
66
+ await handle.close();
67
+ break;
68
+ } catch (error) {
69
+ if (errorCode(error) !== "EEXIST") throw error;
70
+ // A process killed mid-refresh must not lock everybody out for good.
71
+ if (await isStale(lock)) {
72
+ await rm(lock, { force: true });
73
+ continue;
74
+ }
75
+ if (Date.now() > deadline) throw timedOut();
76
+ await sleep(25 + Math.random() * 75);
77
+ }
78
+ }
79
+
80
+ try {
81
+ return await work();
82
+ } finally {
83
+ await rm(lock, { force: true });
84
+ }
85
+ }
@@ -0,0 +1,368 @@
1
+ import { posix, win32 } from "node:path";
2
+ import {
3
+ CONFIG_FILE_NAME,
4
+ CREDENTIALS_FILE_NAME,
5
+ LOCAL_CONFIG_FILE_NAME,
6
+ PROMPT_FILE_NAME,
7
+ WRAITH,
8
+ type AppIdentity,
9
+ envVar,
10
+ } from "../app";
11
+
12
+ /**
13
+ * Where the CLI and TUI look for their files.
14
+ *
15
+ * The environment is an argument instead of being read, so a test can resolve
16
+ * Windows paths on Linux and vice versa.
17
+ *
18
+ * A library host never calls this: it builds a Config object itself.
19
+ */
20
+
21
+ export interface PathEnvironment {
22
+ cwd: string;
23
+ home: string;
24
+ platform: string;
25
+ env: Record<string, string | undefined>;
26
+ /**
27
+ * Which product these paths belong to. Defaults to `WRAITH`, which uses
28
+ * `.wraith` and `WRAITH_HOME`.
29
+ */
30
+ app?: AppIdentity;
31
+ /**
32
+ * Whether this directory holds a project directory.
33
+ *
34
+ * Absent means "look in cwd only".
35
+ */
36
+ hasProjectDir?: (directory: string) => boolean;
37
+ /**
38
+ * What sits at a path, and what a small file says; together they find the
39
+ * git checkout around cwd and its repository. Absent, git is never asked.
40
+ */
41
+ entryKind?: (path: string) => EntryKind | undefined;
42
+ readFile?: (path: string) => string | null;
43
+ }
44
+
45
+ export type EntryKind = "file" | "directory";
46
+
47
+ export interface AppPaths {
48
+ /**
49
+ * `<project root>/.wraith` — per project, shared with the team. Absent, with
50
+ * the three files in it, when that directory is the user's own.
51
+ */
52
+ projectDir: string | undefined;
53
+ projectConfig: string | undefined;
54
+ /**
55
+ * Personal overrides, git-ignored. A linked worktree has no copy of its own:
56
+ * this is the main checkout's file there.
57
+ */
58
+ projectLocalConfig: string | undefined;
59
+ projectPrompt: string | undefined;
60
+ /**
61
+ * Where a project keeps kinds of agent of its own, one file each. Absent as
62
+ * the rest are, and also from a project that was loaded untrusted.
63
+ */
64
+ projectAgentsDir: string | undefined;
65
+ /**
66
+ * Directory holding `.wraith`: the nearest at or above cwd, never above the
67
+ * git checkout. Without one, the checkout's root; outside git, cwd.
68
+ */
69
+ projectRoot: string;
70
+ /**
71
+ * The git checkout around cwd: a repository's working tree, or one linked
72
+ * worktree of it. `projectRoot` outside git.
73
+ */
74
+ checkoutRoot: string;
75
+ /**
76
+ * The repository's main checkout. Sessions and trust are keyed by it, so
77
+ * every subdirectory and every worktree shares them.
78
+ */
79
+ repoRoot: string;
80
+ /** This checkout's own git directory, where its `HEAD` lives. Absent outside git. */
81
+ gitDir: string | undefined;
82
+ /**
83
+ * The project's `.env`, if it has one. We never parse it — we look for
84
+ * variable *names*, to report a key sitting where the agent can read it.
85
+ */
86
+ projectEnvFile: string;
87
+
88
+ /** `~/.wraith` — everything this user owns, in one findable place. */
89
+ userDir: string;
90
+ userConfig: string;
91
+ userPrompt: string;
92
+ /** The user's own kinds of agent, one file each. */
93
+ userAgentsDir: string;
94
+ /** Provider API keys. Never inside the project — the agent reads that. */
95
+ userCredentials: string;
96
+ /** One file per signed-in provider; apart from keys because tokens rotate. */
97
+ userOAuthDir: string;
98
+
99
+ /** `~/.wraith/projects` — one directory per project worked on. */
100
+ projectsDir: string;
101
+ /** This project's directory; sessions live inside it. */
102
+ projectDataDir: string;
103
+ projectSessionsDir: string;
104
+ cacheDir: string;
105
+ }
106
+
107
+ const MAX_SLUG_LENGTH = 120;
108
+
109
+ /** Not ours and not branded: the runtime's convention, the same for every app. */
110
+ const ENV_FILE_NAME = ".env";
111
+
112
+ /** Kinds of agent written as files, in the project's directory and in the user's. */
113
+ const AGENTS_DIR_NAME = "agents";
114
+
115
+ /** What such a file is called: `<name>.md`. */
116
+ export const AGENT_FILE_EXTENSION = ".md";
117
+
118
+ /** FNV-1a. Eight hex characters is plenty to separate two truncated paths. */
119
+ function shortHash(value: string): string {
120
+ let hash = 0x811c9dc5;
121
+ for (let index = 0; index < value.length; index += 1) {
122
+ hash ^= value.charCodeAt(index);
123
+ hash = Math.imul(hash, 0x01000193) >>> 0;
124
+ }
125
+ return hash.toString(16).padStart(8, "0");
126
+ }
127
+
128
+ /**
129
+ * A directory name that says which project it belongs to.
130
+ *
131
+ * Every character a path separator could be becomes a dash. Long paths are
132
+ * truncated and closed with a hash of the original: nested projects on Windows
133
+ * would otherwise walk into the path length limit.
134
+ */
135
+ export function projectSlug(cwd: string): string {
136
+ // One dash per replaced character, not per run: collapsing them would make
137
+ // `H:\proj` and `H:proj` share a directory.
138
+ const flattened = cwd.replace(/[^A-Za-z0-9._-]/g, "-");
139
+ if (flattened.length <= MAX_SLUG_LENGTH) return flattened;
140
+ return `${flattened.slice(0, MAX_SLUG_LENGTH - 9)}-${shortHash(cwd)}`;
141
+ }
142
+
143
+ type PathModule = typeof win32 | typeof posix;
144
+
145
+ /**
146
+ * The nearest directory at or above `cwd` that holds a project directory.
147
+ *
148
+ * The walk stops at `ceiling`, the git checkout's root, and returns it when
149
+ * nothing is found; without a ceiling it returns `cwd`. Without the walk, an
150
+ * agent started from a subdirectory misses the team's configuration and files
151
+ * its sessions under the subdirectory's slug.
152
+ */
153
+ export function findProjectRoot(
154
+ cwd: string,
155
+ path: PathModule,
156
+ hasProjectDir?: (directory: string) => boolean,
157
+ ceiling?: string,
158
+ ): string {
159
+ if (hasProjectDir === undefined) return ceiling ?? cwd;
160
+
161
+ let directory = path.resolve(cwd);
162
+ for (;;) {
163
+ if (hasProjectDir(directory)) return directory;
164
+ if (directory === ceiling) return ceiling;
165
+ const parent = path.dirname(directory);
166
+ if (parent === directory) return cwd;
167
+ directory = parent;
168
+ }
169
+ }
170
+
171
+ /** Windows paths differ only by case; everywhere else they do not. */
172
+ function samePath(left: string, right: string, platform: string): boolean {
173
+ const path = platform === "win32" ? win32 : posix;
174
+ const a = path.resolve(left);
175
+ const b = path.resolve(right);
176
+ return platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
177
+ }
178
+
179
+ /** Where a session is started: a checkout, and the repository it belongs to. */
180
+ export type SessionPlace = Pick<AppPaths, "checkoutRoot" | "repoRoot">;
181
+
182
+ /** What a new session's header says about where it was started. */
183
+ export function checkoutMeta(place: SessionPlace): { checkout: string } {
184
+ return { checkout: place.checkoutRoot };
185
+ }
186
+
187
+ /**
188
+ * Whether a listed session was started in this checkout.
189
+ *
190
+ * Worktrees share one session directory, so "continue the last one" has to
191
+ * ask. A session with no recorded checkout belongs to the main checkout.
192
+ */
193
+ export function inCheckout(
194
+ session: { checkout?: string },
195
+ place: SessionPlace,
196
+ platform: string = process.platform,
197
+ ): boolean {
198
+ return samePath(session.checkout ?? place.repoRoot, place.checkoutRoot, platform);
199
+ }
200
+
201
+ const GIT_ENTRY = ".git";
202
+ const GITDIR_PREFIX = "gitdir:";
203
+
204
+ interface Checkout {
205
+ /** The directory holding `.git`. */
206
+ root: string;
207
+ /** Absent when `.git` is a file nobody could make sense of. */
208
+ gitDir: string | undefined;
209
+ /** `root` itself, unless this is a linked worktree that proves where it came from. */
210
+ repoRoot: string;
211
+ }
212
+
213
+ /** Where a `gitdir: <path>` file points, resolved against the directory holding it. */
214
+ function gitdirTarget(
215
+ file: string,
216
+ path: PathModule,
217
+ readFile: (path: string) => string | null,
218
+ ): string | undefined {
219
+ const text = readFile(file)?.trim();
220
+ if (text === undefined || !text.startsWith(GITDIR_PREFIX)) return undefined;
221
+ const target = text.slice(GITDIR_PREFIX.length).trim();
222
+ return target === "" ? undefined : path.resolve(path.dirname(file), target);
223
+ }
224
+
225
+ /**
226
+ * The main checkout a linked worktree belongs to — on proof only. An unpacked
227
+ * archive can ship a `.git` file aimed at a repository the user trusts; what it
228
+ * cannot forge is the pointer back, inside that repository's own `.git`.
229
+ */
230
+ function mainCheckout(
231
+ root: string,
232
+ gitDir: string,
233
+ path: PathModule,
234
+ environment: PathEnvironment & Required<Pick<PathEnvironment, "entryKind" | "readFile">>,
235
+ ): string | undefined {
236
+ const { platform, entryKind, readFile } = environment;
237
+ const worktrees = path.dirname(gitDir);
238
+ const commonDir = path.dirname(worktrees);
239
+ if (path.basename(worktrees) !== "worktrees" || path.basename(commonDir) !== GIT_ENTRY) {
240
+ return undefined;
241
+ }
242
+
243
+ const declared = readFile(path.join(gitDir, "commondir"))?.trim();
244
+ if (!declared || !samePath(path.resolve(gitDir, declared), commonDir, platform)) return undefined;
245
+
246
+ const back = readFile(path.join(gitDir, "gitdir"))?.trim();
247
+ if (!back || !samePath(path.resolve(gitDir, back), path.join(root, GIT_ENTRY), platform)) {
248
+ return undefined;
249
+ }
250
+
251
+ // The main checkout has to really hold that directory, not merely be named by it.
252
+ if (entryKind(path.join(commonDir, "HEAD")) !== "file") return undefined;
253
+ return path.dirname(commonDir);
254
+ }
255
+
256
+ /**
257
+ * The git checkout around `cwd`, read from the files git leaves — no process.
258
+ *
259
+ * A `.git` directory is an ordinary checkout; a `.git` file is a linked
260
+ * worktree (or a submodule, which stays its own repository).
261
+ */
262
+ function findCheckout(environment: PathEnvironment, path: PathModule): Checkout | undefined {
263
+ const { entryKind, readFile } = environment;
264
+ if (entryKind === undefined) return undefined;
265
+
266
+ let directory = path.resolve(environment.cwd);
267
+ for (;;) {
268
+ const dotGit = path.join(directory, GIT_ENTRY);
269
+ const kind = entryKind(dotGit);
270
+ // A `.git` directory with no HEAD is debris, not a repository: keep walking.
271
+ if (kind === "directory" && entryKind(path.join(dotGit, "HEAD")) === "file") {
272
+ return { root: directory, gitDir: dotGit, repoRoot: directory };
273
+ }
274
+ if (kind === "file") {
275
+ const gitDir = readFile === undefined ? undefined : gitdirTarget(dotGit, path, readFile);
276
+ const main =
277
+ gitDir === undefined || readFile === undefined
278
+ ? undefined
279
+ : mainCheckout(directory, gitDir, path, { ...environment, entryKind, readFile });
280
+ return { root: directory, gitDir, repoRoot: main ?? directory };
281
+ }
282
+ const parent = path.dirname(directory);
283
+ if (parent === directory) return undefined;
284
+ directory = parent;
285
+ }
286
+ }
287
+
288
+ export function resolveAppPaths(environment: PathEnvironment): AppPaths {
289
+ const path = environment.platform === "win32" ? win32 : posix;
290
+ const app = environment.app ?? WRAITH;
291
+ const projectDirName = app.projectDirName;
292
+
293
+ // One root for everything this user owns.
294
+ const userDir =
295
+ environment.env[envVar("HOME", app)] ?? path.join(environment.home, projectDirName);
296
+
297
+ /**
298
+ * The personal directory is not a project: without this guard the walk
299
+ * upwards finds `~/.wraith`, and every repository under home silently
300
+ * shares its config and session directory. The name has to come from the
301
+ * identity, not a constant: a constant guards nothing for another product.
302
+ */
303
+ const personal = [userDir, path.join(environment.home, projectDirName)];
304
+ const probe = environment.hasProjectDir;
305
+ const isProjectRoot =
306
+ probe === undefined
307
+ ? undefined
308
+ : (directory: string): boolean => {
309
+ const candidate = path.join(directory, projectDirName);
310
+ if (personal.some((dir) => samePath(dir, candidate, environment.platform))) return false;
311
+ return probe(directory);
312
+ };
313
+
314
+ // A repository rooted at the home directory would gather every folder under
315
+ // it into one project.
316
+ const isHome = (directory: string): boolean =>
317
+ samePath(directory, environment.home, environment.platform);
318
+ const found = findCheckout(environment, path);
319
+ const checkout = found === undefined || isHome(found.root) ? undefined : found;
320
+
321
+ const projectRoot = findProjectRoot(environment.cwd, path, isProjectRoot, checkout?.root);
322
+ const checkoutRoot = checkout?.root ?? projectRoot;
323
+ const repoRoot =
324
+ checkout === undefined || isHome(checkout.repoRoot) ? checkoutRoot : checkout.repoRoot;
325
+
326
+ // The walk skips the personal directory, but its fallback to cwd lands on it
327
+ // when started from the home directory; that is no project, not a second copy.
328
+ const candidate = path.join(projectRoot, projectDirName);
329
+ const projectDir = personal.some((dir) => samePath(dir, candidate, environment.platform))
330
+ ? undefined
331
+ : candidate;
332
+ const inProject = (name: string): string | undefined =>
333
+ projectDir === undefined ? undefined : path.join(projectDir, name);
334
+ // One file per repository, read and written: a copy per worktree would drift
335
+ // at the first `config set`.
336
+ const localDir =
337
+ projectDir === undefined || samePath(repoRoot, checkoutRoot, environment.platform)
338
+ ? projectDir
339
+ : path.join(repoRoot, path.relative(checkoutRoot, projectRoot), projectDirName);
340
+ const projectsDir = path.join(userDir, "projects");
341
+ const projectDataDir = path.join(projectsDir, projectSlug(repoRoot));
342
+
343
+ return {
344
+ projectRoot,
345
+ checkoutRoot,
346
+ repoRoot,
347
+ gitDir: checkout?.gitDir,
348
+ projectDir,
349
+ projectConfig: inProject(CONFIG_FILE_NAME),
350
+ projectLocalConfig:
351
+ localDir === undefined ? undefined : path.join(localDir, LOCAL_CONFIG_FILE_NAME),
352
+ projectPrompt: inProject(PROMPT_FILE_NAME),
353
+ projectAgentsDir: inProject(AGENTS_DIR_NAME),
354
+ projectEnvFile: path.join(projectRoot, ENV_FILE_NAME),
355
+
356
+ userDir,
357
+ userConfig: path.join(userDir, CONFIG_FILE_NAME),
358
+ userPrompt: path.join(userDir, PROMPT_FILE_NAME),
359
+ userAgentsDir: path.join(userDir, AGENTS_DIR_NAME),
360
+ userCredentials: path.join(userDir, CREDENTIALS_FILE_NAME),
361
+ userOAuthDir: path.join(userDir, "oauth"),
362
+
363
+ projectsDir,
364
+ projectDataDir,
365
+ projectSessionsDir: path.join(projectDataDir, "sessions"),
366
+ cacheDir: path.join(userDir, "cache"),
367
+ };
368
+ }