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

CodexHomeLayout.ts

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