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

CodexHomeLayout.ts

423 lines13.0 KB

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