Open History to see the last commit
1import * as NodeOS from "node:os";
2
3import { ProviderDriverKind, type CodexSettings } from "@t3tools/contracts";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Path from "effect/Path";
7import * as Schema from "effect/Schema";
8import * as PlatformError from "effect/PlatformError";
9
10import { expandHomePath } from "../../pathExpansion.ts";
11
12export interface CodexHomeLayout {
13 readonly mode: "direct" | "authOverlay";
14 readonly sharedHomePath: string;
15 readonly effectiveHomePath: string | undefined;
16 readonly continuationKey: string;
17}
18
19const KNOWN_SHARED_DIRECTORIES = [
20 "sessions",
21 "archived_sessions",
22 "sqlite",
23 "shell_snapshots",
24 "worktrees",
25 "skills",
26 "plugins",
27 "cache",
28 "logs",
29] as const;
30
31const PRIVATE_ENTRY_NAMES = new Set(["auth.json", "models_cache.json"]);
32const SHADOW_LOCAL_ENTRY_NAMES = new Set(["log", "memories", "tmp"]);
33
34function resolveHomePath(path: Path.Path, value: string | undefined): string {
35 const expanded =
36 value && value.trim().length > 0
37 ? expandHomePath(value)
38 : path.join(NodeOS.homedir(), ".codex");
39 return path.resolve(expanded);
40}
41
42export const resolveCodexHomeLayout = Effect.fn("resolveCodexHomeLayout")(function* (
43 config: CodexSettings,
44): Effect.fn.Return<CodexHomeLayout, never, Path.Path> {
45 const path = yield* Path.Path;
46 const sharedHomePath = resolveHomePath(path, config.homePath);
47 const shadowHomePath = config.shadowHomePath.trim();
48 if (shadowHomePath.length === 0) {
49 return {
50 mode: "direct",
51 sharedHomePath,
52 effectiveHomePath: config.homePath.trim().length > 0 ? sharedHomePath : undefined,
53 continuationKey: `codex:home:${sharedHomePath}`,
54 };
55 }
56
57 const effectiveHomePath = path.resolve(expandHomePath(shadowHomePath));
58 return {
59 mode: "authOverlay",
60 sharedHomePath,
61 effectiveHomePath,
62 continuationKey: `codex:home:${sharedHomePath}`,
63 };
64});
65
66export class CodexShadowHomeError extends Schema.TaggedErrorClass<CodexShadowHomeError>()(
67 "CodexShadowHomeError",
68 {
69 detail: Schema.String,
70 cause: Schema.optional(Schema.Unknown),
71 },
72) {
73 override get message(): string {
74 return this.detail;
75 }
76}
77const isCodexShadowHomeError = Schema.is(CodexShadowHomeError);
78
79type LinkState =
80 | {
81 readonly _tag: "Missing";
82 }
83 | {
84 readonly _tag: "NotSymlink";
85 }
86 | {
87 readonly _tag: "Symlink";
88 readonly target: string;
89 };
90
91function toShadowHomeError(cause: unknown): CodexShadowHomeError {
92 return isCodexShadowHomeError(cause)
93 ? cause
94 : new CodexShadowHomeError({
95 detail: "Failed to materialize Codex shadow home.",
96 cause,
97 });
98}
99
100function normalizeShadowHomeError<A, E, R>(
101 effect: Effect.Effect<A, E, R>,
102): Effect.Effect<A, CodexShadowHomeError, R> {
103 return effect.pipe(Effect.mapError(toShadowHomeError));
104}
105
106function isNotSymlinkError(error: PlatformError.PlatformError): boolean {
107 const cause = error.reason.cause;
108 return (
109 error.reason._tag === "Unknown" &&
110 typeof cause === "object" &&
111 cause !== null &&
112 "code" in cause &&
113 cause.code === "EINVAL"
114 );
115}
116
117const readLinkState = Effect.fn("CodexHomeLayout.readLinkState")(function* (
118 fileSystem: FileSystem.FileSystem,
119 linkPath: string,
120): Effect.fn.Return<LinkState, CodexShadowHomeError> {
121 return yield* fileSystem.readLink(linkPath).pipe(
122 Effect.map((target): LinkState => ({ _tag: "Symlink", target })),
123 Effect.catch((error) => {
124 if (error.reason._tag === "NotFound") {
125 return Effect.succeed<LinkState>({ _tag: "Missing" });
126 }
127 if (isNotSymlinkError(error)) {
128 return Effect.succeed<LinkState>({ _tag: "NotSymlink" });
129 }
130 return Effect.fail(toShadowHomeError(error));
131 }),
132 );
133});
134
135const removePrivateSymlink = Effect.fn("CodexHomeLayout.removePrivateSymlink")(function* (input: {
136 readonly fileSystem: FileSystem.FileSystem;
137 readonly shadowPath: string;
138 readonly entryName: string;
139}): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {
140 const path = yield* Path.Path;
141 const privatePath = path.join(input.shadowPath, input.entryName);
142 const state = yield* readLinkState(input.fileSystem, privatePath);
143 if (state._tag === "Symlink") {
144 yield* normalizeShadowHomeError(input.fileSystem.remove(privatePath));
145 }
146});
147
148const ensureSymlink = Effect.fn("CodexHomeLayout.ensureSymlink")(function* (input: {
149 readonly fileSystem: FileSystem.FileSystem;
150 readonly shadowPath: string;
151 readonly sharedPath: string;
152 readonly entryName: string;
153}): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {
154 const path = yield* Path.Path;
155 const target = path.join(input.sharedPath, input.entryName);
156 const link = path.join(input.shadowPath, input.entryName);
157 const state = yield* readLinkState(input.fileSystem, link);
158
159 if (state._tag === "NotSymlink") {
160 return yield* new CodexShadowHomeError({
161 detail: `Cannot create Codex shadow home because '${link}' already exists and is not a symlink.`,
162 });
163 }
164
165 if (state._tag === "Missing") {
166 return yield* normalizeShadowHomeError(input.fileSystem.symlink(target, link));
167 }
168
169 const resolvedExisting = path.resolve(path.dirname(link), state.target);
170 if (resolvedExisting !== target) {
171 yield* normalizeShadowHomeError(input.fileSystem.remove(link));
172 yield* normalizeShadowHomeError(input.fileSystem.symlink(target, link));
173 }
174});
175
176const ensureShadowAuthIsPrivate = Effect.fn("CodexHomeLayout.ensureShadowAuthIsPrivate")(function* (
177 fileSystem: FileSystem.FileSystem,
178 shadowPath: string,
179): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {
180 const path = yield* Path.Path;
181 const authPath = path.join(shadowPath, "auth.json");
182 const state = yield* readLinkState(fileSystem, authPath);
183 if (state._tag === "Symlink") {
184 return yield* new CodexShadowHomeError({
185 detail: `Codex shadow auth file '${authPath}' must be a real file, not a symlink.`,
186 });
187 }
188});
189
190export const materializeCodexShadowHome = Effect.fn("materializeCodexShadowHome")(function* (
191 layout: CodexHomeLayout,
192) {
193 if (layout.mode !== "authOverlay") return;
194 const effectiveHomePath = layout.effectiveHomePath;
195 if (!effectiveHomePath) return;
196 if (layout.sharedHomePath === effectiveHomePath) {
197 return yield* new CodexShadowHomeError({
198 detail: "Codex shadow home path must be different from the shared home path.",
199 });
200 }
201
202 const fileSystem = yield* FileSystem.FileSystem;
203 const path = yield* Path.Path;
204
205 yield* normalizeShadowHomeError(
206 Effect.all(
207 [
208 fileSystem.makeDirectory(layout.sharedHomePath, { recursive: true }),
209 fileSystem.makeDirectory(effectiveHomePath, { recursive: true }),
210 ...KNOWN_SHARED_DIRECTORIES.map((directory) =>
211 fileSystem.makeDirectory(path.join(layout.sharedHomePath, directory), {
212 recursive: true,
213 }),
214 ),
215 ],
216 { concurrency: "unbounded" },
217 ),
218 );
219
220 const sharedEntryNames = yield* normalizeShadowHomeError(
221 fileSystem.readDirectory(layout.sharedHomePath),
222 );
223 const entries = new Set<string>(KNOWN_SHARED_DIRECTORIES);
224 for (const entryName of sharedEntryNames) {
225 if (!PRIVATE_ENTRY_NAMES.has(entryName) && !SHADOW_LOCAL_ENTRY_NAMES.has(entryName)) {
226 entries.add(entryName);
227 }
228 }
229
230 yield* Effect.forEach(
231 PRIVATE_ENTRY_NAMES,
232 (entryName) =>
233 entryName === "auth.json"
234 ? Effect.void
235 : removePrivateSymlink({
236 fileSystem,
237 shadowPath: effectiveHomePath,
238 entryName,
239 }),
240 { discard: true },
241 );
242
243 yield* Effect.forEach(
244 entries,
245 (entryName) => {
246 if (PRIVATE_ENTRY_NAMES.has(entryName)) {
247 return Effect.void;
248 }
249 return ensureSymlink({
250 fileSystem,
251 shadowPath: effectiveHomePath,
252 sharedPath: layout.sharedHomePath,
253 entryName,
254 });
255 },
256 { discard: true },
257 );
258
259 yield* ensureShadowAuthIsPrivate(fileSystem, effectiveHomePath);
260});
261
262export function codexContinuationIdentity(layout: CodexHomeLayout) {
263 return {
264 driverKind: ProviderDriverKind.make("codex"),
265 continuationKey: layout.continuationKey,
266 };
267}