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
66const CodexShadowHomeContext = {
67 sharedHomePath: Schema.String,
68 effectiveHomePath: Schema.String,
69};
70
71export class CodexShadowHomeFileSystemError extends Schema.TaggedErrorClass<CodexShadowHomeFileSystemError>()(
72 "CodexShadowHomeFileSystemError",
73 {
74 ...CodexShadowHomeContext,
75 operation: Schema.Literals(["readLink", "makeDirectory", "readDirectory", "remove", "symlink"]),
76 path: Schema.String,
77 targetPath: Schema.optional(Schema.String),
78 entryName: Schema.optional(Schema.String),
79 cause: Schema.Defect(),
80 },
81) {
82 override get message(): string {
83 const target = this.targetPath === undefined ? "" : ` to '${this.targetPath}'`;
84 return `Codex shadow home filesystem operation '${this.operation}' failed for '${this.path}'${target}.`;
85 }
86}
87
88export class CodexShadowHomePathConflictError extends Schema.TaggedErrorClass<CodexShadowHomePathConflictError>()(
89 "CodexShadowHomePathConflictError",
90 CodexShadowHomeContext,
91) {
92 override get message(): string {
93 return `Codex shadow home path '${this.effectiveHomePath}' must be different from the shared home path '${this.sharedHomePath}'.`;
94 }
95}
96
97export class CodexShadowHomeEntryConflictError extends Schema.TaggedErrorClass<CodexShadowHomeEntryConflictError>()(
98 "CodexShadowHomeEntryConflictError",
99 {
100 ...CodexShadowHomeContext,
101 entryName: Schema.String,
102 linkPath: Schema.String,
103 targetPath: Schema.String,
104 },
105) {
106 override get message(): string {
107 return `Cannot create Codex shadow home entry '${this.entryName}' because '${this.linkPath}' already exists and is not a symlink.`;
108 }
109}
110
111export class CodexShadowHomePrivateEntrySymlinkError extends Schema.TaggedErrorClass<CodexShadowHomePrivateEntrySymlinkError>()(
112 "CodexShadowHomePrivateEntrySymlinkError",
113 {
114 ...CodexShadowHomeContext,
115 entryName: Schema.String,
116 path: Schema.String,
117 },
118) {
119 override get message(): string {
120 return `Codex shadow home private entry '${this.entryName}' at '${this.path}' must be a real file, not a symlink.`;
121 }
122}
123
124export const CodexShadowHomeError = Schema.Union([
125 CodexShadowHomeFileSystemError,
126 CodexShadowHomePathConflictError,
127 CodexShadowHomeEntryConflictError,
128 CodexShadowHomePrivateEntrySymlinkError,
129]);
130export type CodexShadowHomeError = typeof CodexShadowHomeError.Type;
131
132type LinkState =
133 | {
134 readonly _tag: "Missing";
135 }
136 | {
137 readonly _tag: "NotSymlink";
138 }
139 | {
140 readonly _tag: "Symlink";
141 readonly target: string;
142 };
143
144function isNotSymlinkError(error: PlatformError.PlatformError): boolean {
145 const cause = error.reason.cause;
146 return (
147 error.reason._tag === "Unknown" &&
148 typeof cause === "object" &&
149 cause !== null &&
150 "code" in cause &&
151 cause.code === "EINVAL"
152 );
153}
154
155const readLinkState = Effect.fn("CodexHomeLayout.readLinkState")(function* (input: {
156 readonly fileSystem: FileSystem.FileSystem;
157 readonly sharedHomePath: string;
158 readonly effectiveHomePath: string;
159 readonly entryName: string;
160 readonly linkPath: string;
161}): Effect.fn.Return<LinkState, CodexShadowHomeError> {
162 return yield* input.fileSystem.readLink(input.linkPath).pipe(
163 Effect.map((target): LinkState => ({ _tag: "Symlink", target })),
164 Effect.catchTags({
165 PlatformError: (cause) => {
166 if (cause.reason._tag === "NotFound") {
167 return Effect.succeed<LinkState>({ _tag: "Missing" });
168 }
169 if (isNotSymlinkError(cause)) {
170 return Effect.succeed<LinkState>({ _tag: "NotSymlink" });
171 }
172 return new CodexShadowHomeFileSystemError({
173 sharedHomePath: input.sharedHomePath,
174 effectiveHomePath: input.effectiveHomePath,
175 operation: "readLink",
176 path: input.linkPath,
177 entryName: input.entryName,
178 cause,
179 });
180 },
181 }),
182 );
183});
184
185const removePrivateSymlink = Effect.fn("CodexHomeLayout.removePrivateSymlink")(function* (input: {
186 readonly fileSystem: FileSystem.FileSystem;
187 readonly sharedHomePath: string;
188 readonly effectiveHomePath: string;
189 readonly entryName: string;
190}): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {
191 const path = yield* Path.Path;
192 const privatePath = path.join(input.effectiveHomePath, input.entryName);
193 const state = yield* readLinkState({
194 ...input,
195 linkPath: privatePath,
196 });
197 if (state._tag === "Symlink") {
198 yield* input.fileSystem.remove(privatePath).pipe(
199 Effect.catchTags({
200 PlatformError: (cause) =>
201 new CodexShadowHomeFileSystemError({
202 sharedHomePath: input.sharedHomePath,
203 effectiveHomePath: input.effectiveHomePath,
204 operation: "remove",
205 path: privatePath,
206 entryName: input.entryName,
207 cause,
208 }),
209 }),
210 );
211 }
212});
213
214const ensureSymlink = Effect.fn("CodexHomeLayout.ensureSymlink")(function* (input: {
215 readonly fileSystem: FileSystem.FileSystem;
216 readonly sharedHomePath: string;
217 readonly effectiveHomePath: string;
218 readonly entryName: string;
219}): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {
220 const path = yield* Path.Path;
221 const target = path.join(input.sharedHomePath, input.entryName);
222 const link = path.join(input.effectiveHomePath, input.entryName);
223 const state = yield* readLinkState({
224 ...input,
225 linkPath: link,
226 });
227
228 if (state._tag === "NotSymlink") {
229 return yield* new CodexShadowHomeEntryConflictError({
230 sharedHomePath: input.sharedHomePath,
231 effectiveHomePath: input.effectiveHomePath,
232 entryName: input.entryName,
233 linkPath: link,
234 targetPath: target,
235 });
236 }
237
238 const createLink = input.fileSystem.symlink(target, link).pipe(
239 Effect.catchTags({
240 PlatformError: (cause) =>
241 new CodexShadowHomeFileSystemError({
242 sharedHomePath: input.sharedHomePath,
243 effectiveHomePath: input.effectiveHomePath,
244 operation: "symlink",
245 path: link,
246 targetPath: target,
247 entryName: input.entryName,
248 cause,
249 }),
250 }),
251 );
252
253 if (state._tag === "Missing") {
254 return yield* createLink;
255 }
256
257 const resolvedExisting = path.resolve(path.dirname(link), state.target);
258 if (resolvedExisting !== target) {
259 yield* input.fileSystem.remove(link).pipe(
260 Effect.catchTags({
261 PlatformError: (cause) =>
262 new CodexShadowHomeFileSystemError({
263 sharedHomePath: input.sharedHomePath,
264 effectiveHomePath: input.effectiveHomePath,
265 operation: "remove",
266 path: link,
267 entryName: input.entryName,
268 cause,
269 }),
270 }),
271 );
272 yield* createLink;
273 }
274});
275
276const ensureShadowAuthIsPrivate = Effect.fn("CodexHomeLayout.ensureShadowAuthIsPrivate")(
277 function* (input: {
278 readonly fileSystem: FileSystem.FileSystem;
279 readonly sharedHomePath: string;
280 readonly effectiveHomePath: string;
281 }): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {
282 const path = yield* Path.Path;
283 const entryName = "auth.json";
284 const authPath = path.join(input.effectiveHomePath, entryName);
285 const state = yield* readLinkState({
286 ...input,
287 entryName,
288 linkPath: authPath,
289 });
290 if (state._tag === "Symlink") {
291 return yield* new CodexShadowHomePrivateEntrySymlinkError({
292 sharedHomePath: input.sharedHomePath,
293 effectiveHomePath: input.effectiveHomePath,
294 entryName,
295 path: authPath,
296 });
297 }
298 },
299);
300
301export const materializeCodexShadowHome = Effect.fn("materializeCodexShadowHome")(function* (
302 layout: CodexHomeLayout,
303) {
304 if (layout.mode !== "authOverlay") return;
305 const effectiveHomePath = layout.effectiveHomePath;
306 if (!effectiveHomePath) return;
307 if (layout.sharedHomePath === effectiveHomePath) {
308 return yield* new CodexShadowHomePathConflictError({
309 sharedHomePath: layout.sharedHomePath,
310 effectiveHomePath,
311 });
312 }
313
314 const fileSystem = yield* FileSystem.FileSystem;
315 const path = yield* Path.Path;
316
317 const makeDirectory = (directoryPath: string) =>
318 fileSystem.makeDirectory(directoryPath, { recursive: true }).pipe(
319 Effect.catchTags({
320 PlatformError: (cause) =>
321 new CodexShadowHomeFileSystemError({
322 sharedHomePath: layout.sharedHomePath,
323 effectiveHomePath,
324 operation: "makeDirectory",
325 path: directoryPath,
326 cause,
327 }),
328 }),
329 );
330
331 yield* Effect.all(
332 [
333 makeDirectory(layout.sharedHomePath),
334 makeDirectory(effectiveHomePath),
335 ...KNOWN_SHARED_DIRECTORIES.map((directory) =>
336 makeDirectory(path.join(layout.sharedHomePath, directory)),
337 ),
338 ],
339 { concurrency: "unbounded" },
340 );
341
342 const sharedEntryNames = yield* fileSystem.readDirectory(layout.sharedHomePath).pipe(
343 Effect.catchTags({
344 PlatformError: (cause) =>
345 new CodexShadowHomeFileSystemError({
346 sharedHomePath: layout.sharedHomePath,
347 effectiveHomePath,
348 operation: "readDirectory",
349 path: layout.sharedHomePath,
350 cause,
351 }),
352 }),
353 );
354 const entries = new Set<string>(KNOWN_SHARED_DIRECTORIES);
355 for (const entryName of sharedEntryNames) {
356 if (!PRIVATE_ENTRY_NAMES.has(entryName) && !SHADOW_LOCAL_ENTRY_NAMES.has(entryName)) {
357 entries.add(entryName);
358 }
359 }
360
361 yield* Effect.forEach(
362 PRIVATE_ENTRY_NAMES,
363 (entryName) =>
364 entryName === "auth.json"
365 ? Effect.void
366 : removePrivateSymlink({
367 fileSystem,
368 sharedHomePath: layout.sharedHomePath,
369 effectiveHomePath,
370 entryName,
371 }),
372 { discard: true },
373 );
374
375 yield* Effect.forEach(
376 entries,
377 (entryName) => {
378 if (PRIVATE_ENTRY_NAMES.has(entryName)) {
379 return Effect.void;
380 }
381 return ensureSymlink({
382 fileSystem,
383 sharedHomePath: layout.sharedHomePath,
384 effectiveHomePath,
385 entryName,
386 });
387 },
388 { discard: true },
389 );
390
391 yield* ensureShadowAuthIsPrivate({
392 fileSystem,
393 sharedHomePath: layout.sharedHomePath,
394 effectiveHomePath,
395 });
396});
397
398export function codexContinuationIdentity(layout: CodexHomeLayout) {
399 return {
400 driverKind: ProviderDriverKind.make("codex"),
401 continuationKey: layout.continuationKey,
402 };
403}