Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as Option from "effect/Option";
3import type * as FileSystem from "effect/FileSystem";
4import type * as Path from "effect/Path";
5import * as EffectAcpErrors from "effect-acp/errors";
6import type * as EffectAcpSchema from "effect-acp/compat";
7
8const CLIENT_FILE_MAX_BYTES = 8 * 1024 * 1024;
9
10function isInsideRoot(path: Path.Path, root: string, candidate: string): boolean {
11 const relative = path.relative(root, candidate);
12 return (
13 relative === "" ||
14 (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
15 );
16}
17
18/** Resolve all symlinks, including the final component, before checking workspace containment. */
19const resolveClientFilePath = Effect.fn("AntigravityClientFiles.resolveClientFilePath")(
20 function* (input: {
21 readonly fileSystem: FileSystem.FileSystem;
22 readonly path: Path.Path;
23 readonly cwd?: string | null;
24 readonly allowedRoots: ReadonlyArray<string>;
25 readonly requestPath: string;
26 }) {
27 const { path } = input;
28 const outside = EffectAcpErrors.AcpRequestError.invalidParams(
29 `Path '${input.requestPath}' is outside the session workspace.`,
30 );
31 let resolved: string;
32 if (path.isAbsolute(input.requestPath)) {
33 resolved = path.resolve(input.requestPath);
34 } else if (input.cwd !== null && input.cwd !== undefined) {
35 resolved = path.resolve(input.cwd, input.requestPath);
36 } else {
37 return yield* outside;
38 }
39 // Canonicalize the deepest existing ancestor, so a link above missing directories cannot escape.
40 let candidate = resolved;
41 const missingSuffix: Array<string> = [];
42 let real: string;
43 while (true) {
44 const canonical = yield* input.fileSystem.realPath(candidate).pipe(Effect.option);
45 if (Option.isSome(canonical)) {
46 real = path.join(canonical.value, ...missingSuffix);
47 break;
48 }
49 // Walk up only past missing entries, never dangling or unreadable links.
50 const entryExists = yield* input.fileSystem.readLink(candidate).pipe(
51 Effect.as(true),
52 Effect.catch(() => input.fileSystem.exists(candidate)),
53 Effect.orElseSucceed(() => true),
54 );
55 const parent = path.dirname(candidate);
56 if (entryExists || parent === candidate) return yield* outside;
57 missingSuffix.unshift(path.basename(candidate));
58 candidate = parent;
59 }
60 const roots = yield* Effect.forEach(input.allowedRoots, (root) =>
61 input.fileSystem.realPath(root).pipe(Effect.orElseSucceed(() => root)),
62 );
63 if (!roots.some((root) => isInsideRoot(path, root, real))) {
64 return yield* outside;
65 }
66 return real;
67 },
68);
69
70export const readAntigravityClientTextFile = Effect.fn("AntigravityClientFiles.readTextFile")(
71 function* (input: {
72 readonly fileSystem: FileSystem.FileSystem;
73 readonly path: Path.Path;
74 readonly cwd?: string | null;
75 readonly allowedRoots: ReadonlyArray<string>;
76 readonly request: EffectAcpSchema.ReadTextFileRequest;
77 }): Effect.fn.Return<EffectAcpSchema.ReadTextFileResponse, EffectAcpErrors.AcpError> {
78 const filePath = yield* resolveClientFilePath({ ...input, requestPath: input.request.path });
79 const info = yield* input.fileSystem
80 .stat(filePath)
81 .pipe(
82 Effect.mapError(() =>
83 EffectAcpErrors.AcpRequestError.resourceNotFound(
84 `File '${input.request.path}' not found.`,
85 ),
86 ),
87 );
88 if (info.type !== "File" || Number(info.size) > CLIENT_FILE_MAX_BYTES) {
89 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
90 `File '${input.request.path}' is not a readable text file under ${CLIENT_FILE_MAX_BYTES} bytes.`,
91 );
92 }
93 const bytes = yield* input.fileSystem
94 .readFile(filePath)
95 .pipe(
96 Effect.mapError(() =>
97 EffectAcpErrors.AcpRequestError.internalError(`Could not read '${input.request.path}'.`),
98 ),
99 );
100 const text = yield* Effect.try({
101 try: () => new TextDecoder("utf-8", { fatal: true }).decode(bytes),
102 catch: () =>
103 EffectAcpErrors.AcpRequestError.invalidParams(
104 `File '${input.request.path}' is not a UTF-8 text file.`,
105 ),
106 });
107 if (text.includes("\0")) {
108 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
109 `File '${input.request.path}' contains binary data.`,
110 );
111 }
112 const line = input.request.line ?? undefined;
113 const limit = input.request.limit ?? undefined;
114 if (line === undefined && limit === undefined) {
115 return { content: text };
116 }
117 // ACP lines are 1-indexed. `limit` is a line count.
118 const lines = text.split("\n");
119 const start = Math.max(0, (line ?? 1) - 1);
120 const end = limit === undefined ? lines.length : Math.min(lines.length, start + limit);
121 return { content: lines.slice(start, end).join("\n") };
122 },
123);