Open History to see the last commit
1import { ProviderDriverKind, type CodexSettings } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Path from "effect/Path";
5import * as Schema from "effect/Schema";
6import * as PlatformError from "effect/PlatformError";
7
8import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10
11export interface CodexHomeLayout {
12 readonly mode: "direct" | "authOverlay";
13 readonly sharedHomePath: string;
14 readonly effectiveHomePath: string | undefined;
15 readonly continuationKey: string;
16}
17
18const KNOWN_SHARED_DIRECTORIES = [
19 "sessions",
20 "archived_sessions",
21 "sqlite",
22 "shell_snapshots",
23 "worktrees",
24 "skills",
25 "plugins",
26 "cache",
27 "logs",
28 "mcp-oauth-locks",
29 "thread-writer-locks",
30] as const;
31
32// auth.lock guards the shadow home's private auth.json.
33const PRIVATE_ENTRY_NAMES = new Set(["auth.json", "auth.lock", "models_cache.json"]);
34// Finder maintains metadata separately for each directory, including shadow homes.
35const SHADOW_LOCAL_ENTRY_NAMES = new Set(["log", "memories", "tmp", ".DS_Store"]);
36// Shadow homes may create local runtime locks first; replace them with shared links because they guard shared state.
37const REPLACEABLE_SHARED_RUNTIME_ENTRIES = new Set([
38 "mcp-oauth-locks",
39 "thread-writer-locks",
40 ".sqlite-maintenance.lock",
41]);
42
43function resolveHomePath(path: Path.Path, home: string, value: string | undefined): string {
44 const expanded =
45 value && value.trim().length > 0 ? expandHomePath(value, home) : path.join(home, ".codex");
46 return path.resolve(expanded);
47}
48
49export const resolveCodexHomeLayout = Effect.fn("resolveCodexHomeLayout")(function* (
50 config: CodexSettings,
51): Effect.fn.Return<CodexHomeLayout, never, Path.Path> {
52 const path = yield* Path.Path;
53 const home = yield* HostProcess.HomeDirectory;
54 const sharedHomePath = resolveHomePath(path, home, config.homePath);
55 const shadowHomePath = config.shadowHomePath.trim();
56 if (shadowHomePath.length === 0) {
57 return {
58 mode: "direct",
59 sharedHomePath,
60 effectiveHomePath: config.homePath.trim().length > 0 ? sharedHomePath : undefined,
61 continuationKey: `codex:home:${sharedHomePath}`,
62 };
63 }
64
65 const effectiveHomePath = path.resolve(expandHomePath(shadowHomePath, home));
66 return {
67 mode: "authOverlay",
68 sharedHomePath,
69 effectiveHomePath,
70 continuationKey: `codex:home:${sharedHomePath}`,
71 };
72});
73
74const CodexShadowHomeContext = {
75 sharedHomePath: Schema.String,
76 effectiveHomePath: Schema.String,
77};
78
79export class CodexShadowHomeFileSystemError extends Schema.TaggedError<CodexShadowHomeFileSystemError>()(
80 "CodexShadowHomeFileSystemError",
81 {
82 ...CodexShadowHomeContext,
83 operation: Schema.Literals(["readLink", "makeDirectory", "readDirectory", "remove", "symlink"]),
84 path: Schema.String,
85 targetPath: Schema.optional(Schema.String),
86 entryName: Schema.optional(Schema.String),
87 cause: Schema.Defect(),
88 },
89) {
90 override get message(): string {
91 const target = this.targetPath === undefined ? "" : ` to '${this.targetPath}'`;
92 return `Codex shadow home filesystem operation '${this.operation}' failed for '${this.path}'${target}.`;
93 }
94}
95
96export class CodexShadowHomePathConflictError extends Schema.TaggedError<CodexShadowHomePathConflictError>()(
97 "CodexShadowHomePathConflictError",
98 CodexShadowHomeContext,
99) {
100 override get message(): string {
101 return `Codex shadow home path '${this.effectiveHomePath}' must be different from the shared home path '${this.sharedHomePath}'.`;
102 }
103}
104
105export class CodexShadowHomeEntryConflictError extends Schema.TaggedError<CodexShadowHomeEntryConflictError>()(
106 "CodexShadowHomeEntryConflictError",
107 {
108 ...CodexShadowHomeContext,
109 entryName: Schema.String,
110 linkPath: Schema.String,
111 targetPath: Schema.String,
112 },
113) {
114 override get message(): string {
115 return `Cannot create Codex shadow home entry '${this.entryName}' because '${this.linkPath}' already exists and is not a symlink.`;
116 }
117}
118
119export class CodexShadowHomePrivateEntrySymlinkError extends Schema.TaggedError<CodexShadowHomePrivateEntrySymlinkError>()(
120 "CodexShadowHomePrivateEntrySymlinkError",
121 {
122 ...CodexShadowHomeContext,
123 entryName: Schema.String,
124 path: Schema.String,
125 },
126) {
127 override get message(): string {
128 return `Codex shadow home private entry '${this.entryName}' at '${this.path}' must be a real file, not a symlink.`;
129 }
130}
131
132export const CodexShadowHomeError = Schema.Union([
133 CodexShadowHomeFileSystemError,
134 CodexShadowHomePathConflictError,
135 CodexShadowHomeEntryConflictError,
136 CodexShadowHomePrivateEntrySymlinkError,
137]);
138export type CodexShadowHomeError = typeof CodexShadowHomeError.Type;
139
140type LinkState =
141 | {
142 readonly _tag: "Missing";
143 }
144 | {
145 readonly _tag: "NotSymlink";
146 }
147 | {
148 readonly _tag: "Symlink";
149 readonly target: string;
150 };
151
152function isNotSymlinkError(error: PlatformError.PlatformError): boolean {
153 const cause = error.reason.cause;
154 return (
155 error.reason._tag === "Unknown" &&
156 typeof cause === "object" &&
157 cause !== null &&
158 "code" in cause &&
159 cause.code === "EINVAL"
160 );
161}
162
163const readLinkState = Effect.fn("CodexHomeLayout.readLinkState")(function* (input: {
164 readonly fileSystem: FileSystem.FileSystem;
165 readonly sharedHomePath: string;
166 readonly effectiveHomePath: string;
167 readonly entryName: string;
168 readonly linkPath: string;
169}): Effect.fn.Return<LinkState, CodexShadowHomeError> {
170 return yield* input.fileSystem.readLink(input.linkPath).pipe(
171 Effect.map((target): LinkState => ({ _tag: "Symlink", target })),
172 Effect.catchTags({
173 PlatformError: (cause) => {
174 if (cause.reason._tag === "NotFound") {
175 return Effect.succeed<LinkState>({ _tag: "Missing" });
176 }
177 if (isNotSymlinkError(cause)) {
178 return Effect.succeed<LinkState>({ _tag: "NotSymlink" });
179 }
180 return new CodexShadowHomeFileSystemError({
181 sharedHomePath: input.sharedHomePath,
182 effectiveHomePath: input.effectiveHomePath,
183 operation: "readLink",
184 path: input.linkPath,
185 entryName: input.entryName,
186 cause,
187 });
188 },
189 }),
190 );
191});
192
193const removePrivateSymlink = Effect.fn("CodexHomeLayout.removePrivateSymlink")(function* (input: {
194 readonly fileSystem: FileSystem.FileSystem;
195 readonly sharedHomePath: string;
196 readonly effectiveHomePath: string;
197 readonly entryName: string;
198}): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {
199 const path = yield* Path.Path;
200 const privatePath = path.join(input.effectiveHomePath, input.entryName);
201 const state = yield* readLinkState({
202 ...input,
203 linkPath: privatePath,
204 });
205 if (state._tag === "Symlink") {
206 yield* input.fileSystem.remove(privatePath).pipe(
207 Effect.catchTags({
208 PlatformError: (cause) =>
209 new CodexShadowHomeFileSystemError({
210 sharedHomePath: input.sharedHomePath,
211 effectiveHomePath: input.effectiveHomePath,
212 operation: "remove",
213 path: privatePath,
214 entryName: input.entryName,
215 cause,
216 }),
217 }),
218 );
219 }
220});
221
222const ensureSymlink = Effect.fn("CodexHomeLayout.ensureSymlink")(function* (input: {
223 readonly fileSystem: FileSystem.FileSystem;
224 readonly sharedHomePath: string;
225 readonly effectiveHomePath: string;
226 readonly entryName: string;
227}): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {
228 const path = yield* Path.Path;
229 const target = path.join(input.sharedHomePath, input.entryName);
230 const link = path.join(input.effectiveHomePath, input.entryName);
231 const state = yield* readLinkState({
232 ...input,
233 linkPath: link,
234 });
235
236 const createLink = input.fileSystem.symlink(target, link).pipe(
237 Effect.catchTags({
238 PlatformError: (cause) =>
239 new CodexShadowHomeFileSystemError({
240 sharedHomePath: input.sharedHomePath,
241 effectiveHomePath: input.effectiveHomePath,
242 operation: "symlink",
243 path: link,
244 targetPath: target,
245 entryName: input.entryName,
246 cause,
247 }),
248 }),
249 );
250
251 if (state._tag === "NotSymlink") {
252 if (!REPLACEABLE_SHARED_RUNTIME_ENTRIES.has(input.entryName)) {
253 return yield* new CodexShadowHomeEntryConflictError({
254 sharedHomePath: input.sharedHomePath,
255 effectiveHomePath: input.effectiveHomePath,
256 entryName: input.entryName,
257 linkPath: link,
258 targetPath: target,
259 });
260 }
261
262 if (input.entryName === "thread-writer-locks") {
263 const lockNames = yield* input.fileSystem.readDirectory(link).pipe(
264 Effect.catchTags({
265 PlatformError: (cause) =>
266 new CodexShadowHomeFileSystemError({
267 sharedHomePath: input.sharedHomePath,
268 effectiveHomePath: input.effectiveHomePath,
269 operation: "readDirectory",
270 path: link,
271 entryName: input.entryName,
272 cause,
273 }),
274 }),
275 );
276 // Codex deletes a thread lock on release, so one that is left may still guard a live
277 // writer. Keep the local directory until a later setup finds none.
278 if (lockNames.some((name) => name.endsWith(".lock") && name !== ".coordination.lock")) {
279 return yield* Effect.logWarning(
280 "Codex shadow home still has thread writer locks; it will share them on a later setup.",
281 { path: link },
282 );
283 }
284 }
285
286 yield* input.fileSystem.remove(link, { recursive: true }).pipe(
287 Effect.catchTags({
288 PlatformError: (cause) =>
289 new CodexShadowHomeFileSystemError({
290 sharedHomePath: input.sharedHomePath,
291 effectiveHomePath: input.effectiveHomePath,
292 operation: "remove",
293 path: link,
294 entryName: input.entryName,
295 cause,
296 }),
297 }),
298 );
299 return yield* createLink;
300 }
301
302 if (state._tag === "Missing") {
303 return yield* createLink;
304 }
305
306 const resolvedExisting = path.resolve(path.dirname(link), state.target);
307 if (resolvedExisting !== target) {
308 yield* input.fileSystem.remove(link).pipe(
309 Effect.catchTags({
310 PlatformError: (cause) =>
311 new CodexShadowHomeFileSystemError({
312 sharedHomePath: input.sharedHomePath,
313 effectiveHomePath: input.effectiveHomePath,
314 operation: "remove",
315 path: link,
316 entryName: input.entryName,
317 cause,
318 }),
319 }),
320 );
321 yield* createLink;
322 }
323});
324
325const ensureShadowAuthIsPrivate = Effect.fn("CodexHomeLayout.ensureShadowAuthIsPrivate")(
326 function* (input: {
327 readonly fileSystem: FileSystem.FileSystem;
328 readonly sharedHomePath: string;
329 readonly effectiveHomePath: string;
330 }): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {
331 const path = yield* Path.Path;
332 const entryName = "auth.json";
333 const authPath = path.join(input.effectiveHomePath, entryName);
334 const state = yield* readLinkState({
335 ...input,
336 entryName,
337 linkPath: authPath,
338 });
339 if (state._tag === "Symlink") {
340 return yield* new CodexShadowHomePrivateEntrySymlinkError({
341 sharedHomePath: input.sharedHomePath,
342 effectiveHomePath: input.effectiveHomePath,
343 entryName,
344 path: authPath,
345 });
346 }
347 },
348);
349
350export const materializeCodexShadowHome = Effect.fn("materializeCodexShadowHome")(function* (
351 layout: CodexHomeLayout,
352) {
353 if (layout.mode !== "authOverlay") return;
354 const effectiveHomePath = layout.effectiveHomePath;
355 if (!effectiveHomePath) return;
356 if (layout.sharedHomePath === effectiveHomePath) {
357 return yield* new CodexShadowHomePathConflictError({
358 sharedHomePath: layout.sharedHomePath,
359 effectiveHomePath,
360 });
361 }
362
363 const fileSystem = yield* FileSystem.FileSystem;
364 const path = yield* Path.Path;
365
366 const makeDirectory = (directoryPath: string) =>
367 fileSystem.makeDirectory(directoryPath, { recursive: true }).pipe(
368 Effect.catchTags({
369 PlatformError: (cause) =>
370 new CodexShadowHomeFileSystemError({
371 sharedHomePath: layout.sharedHomePath,
372 effectiveHomePath,
373 operation: "makeDirectory",
374 path: directoryPath,
375 cause,
376 }),
377 }),
378 );
379
380 yield* Effect.all(
381 [
382 makeDirectory(layout.sharedHomePath),
383 makeDirectory(effectiveHomePath),
384 ...KNOWN_SHARED_DIRECTORIES.map((directory) =>
385 makeDirectory(path.join(layout.sharedHomePath, directory)),
386 ),
387 ],
388 { concurrency: "unbounded" },
389 );
390
391 const sharedEntryNames = yield* fileSystem.readDirectory(layout.sharedHomePath).pipe(
392 Effect.catchTags({
393 PlatformError: (cause) =>
394 new CodexShadowHomeFileSystemError({
395 sharedHomePath: layout.sharedHomePath,
396 effectiveHomePath,
397 operation: "readDirectory",
398 path: layout.sharedHomePath,
399 cause,
400 }),
401 }),
402 );
403 const entries = new Set<string>(KNOWN_SHARED_DIRECTORIES);
404 for (const entryName of sharedEntryNames) {
405 if (!PRIVATE_ENTRY_NAMES.has(entryName) && !SHADOW_LOCAL_ENTRY_NAMES.has(entryName)) {
406 entries.add(entryName);
407 }
408 }
409
410 yield* Effect.forEach(
411 PRIVATE_ENTRY_NAMES,
412 (entryName) =>
413 entryName === "auth.json"
414 ? Effect.void
415 : removePrivateSymlink({
416 fileSystem,
417 sharedHomePath: layout.sharedHomePath,
418 effectiveHomePath,
419 entryName,
420 }),
421 { discard: true },
422 );
423
424 yield* Effect.forEach(
425 entries,
426 (entryName) => {
427 if (PRIVATE_ENTRY_NAMES.has(entryName)) {
428 return Effect.void;
429 }
430 return ensureSymlink({
431 fileSystem,
432 sharedHomePath: layout.sharedHomePath,
433 effectiveHomePath,
434 entryName,
435 });
436 },
437 { discard: true },
438 );
439
440 yield* ensureShadowAuthIsPrivate({
441 fileSystem,
442 sharedHomePath: layout.sharedHomePath,
443 effectiveHomePath,
444 });
445});
446
447export function codexContinuationIdentity(layout: CodexHomeLayout) {
448 return {
449 driverKind: ProviderDriverKind.make("codex"),
450 continuationKey: layout.continuationKey,
451 };
452}