Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CodexHomeLayout.ts

263 lines7.9 KB

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