Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2/**
3 * WorkspaceFileSystem - Effect service contract for workspace file mutations.
4 *
5 * Owns workspace-root-relative file read/write operations and their associated
6 * safety checks and cache invalidation hooks. Reads also accept absolute host
7 * paths so clients can show files an agent left outside the workspace; writes
8 * never leave the root.
9 *
10 * @module WorkspaceFileSystem
11 */
12import * as NodeFS from "node:fs";
13import * as NodeFSP from "node:fs/promises";
14
15import type {
16 FilesystemEntryMetadata,
17 FilesystemGetMetadataInput,
18 FilesystemGetMetadataResult,
19 ProjectReadFileInput,
20 ProjectReadFileResult,
21 ProjectWriteFileInput,
22 ProjectWriteFileResult,
23} from "@t3tools/contracts";
24import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
25import * as HostProcess from "@t3tools/shared/HostProcess";
26import * as Context from "effect/Context";
27import * as Effect from "effect/Effect";
28import * as FileSystem from "effect/FileSystem";
29import * as Layer from "effect/Layer";
30import * as Path from "effect/Path";
31import * as Schema from "effect/Schema";
32
33import * as WorkspaceEntries from "./WorkspaceEntries.ts";
34import * as WorkspacePaths from "./WorkspacePaths.ts";
35import { fileHeaderMimeType } from "./fileHeaderMimeType.ts";
36
37const PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024;
38
39export class WorkspaceFileSystemOperationError extends Schema.TaggedError<WorkspaceFileSystemOperationError>()(
40 "WorkspaceFileSystemOperationError",
41 {
42 workspaceRoot: Schema.String,
43 relativePath: Schema.String,
44 resolvedPath: Schema.String,
45 operationPath: Schema.String,
46 operation: Schema.Literals([
47 "realpath-workspace-root",
48 "realpath-target",
49 "open",
50 "stat",
51 "read",
52 "close",
53 "make-directory",
54 "write-file",
55 ]),
56 cause: Schema.Defect(),
57 },
58) {
59 override get message(): string {
60 return `Workspace file operation '${this.operation}' failed at '${this.operationPath}' for resolved path '${this.resolvedPath}' (requested as '${this.relativePath}' in '${this.workspaceRoot}').`;
61 }
62}
63
64export class WorkspaceFilePathEscapeError extends Schema.TaggedError<WorkspaceFilePathEscapeError>()(
65 "WorkspaceFilePathEscapeError",
66 {
67 workspaceRoot: Schema.String,
68 relativePath: Schema.String,
69 resolvedWorkspaceRoot: Schema.String,
70 resolvedPath: Schema.String,
71 },
72) {
73 override get message(): string {
74 return `Workspace file '${this.relativePath}' resolves outside workspace root '${this.workspaceRoot}': ${this.resolvedPath}`;
75 }
76}
77
78export class WorkspacePathNotFileError extends Schema.TaggedError<WorkspacePathNotFileError>()(
79 "WorkspacePathNotFileError",
80 {
81 workspaceRoot: Schema.String,
82 relativePath: Schema.String,
83 resolvedPath: Schema.String,
84 },
85) {
86 override get message(): string {
87 return `Workspace path '${this.relativePath}' in '${this.workspaceRoot}' is not a file: ${this.resolvedPath}`;
88 }
89}
90
91export class WorkspaceBinaryFileError extends Schema.TaggedError<WorkspaceBinaryFileError>()(
92 "WorkspaceBinaryFileError",
93 {
94 workspaceRoot: Schema.String,
95 relativePath: Schema.String,
96 resolvedPath: Schema.String,
97 },
98) {
99 override get message(): string {
100 return `Workspace file '${this.relativePath}' in '${this.workspaceRoot}' is binary and cannot be previewed as text.`;
101 }
102}
103
104export const WorkspaceFileSystemError = Schema.Union([
105 WorkspaceFileSystemOperationError,
106 WorkspaceFilePathEscapeError,
107 WorkspacePathNotFileError,
108 WorkspaceBinaryFileError,
109]);
110export type WorkspaceFileSystemError = typeof WorkspaceFileSystemError.Type;
111
112/** Service tag for workspace file operations. */
113export class WorkspaceFileSystem extends Context.Service<
114 WorkspaceFileSystem,
115 {
116 readonly getMetadata: (
117 input: FilesystemGetMetadataInput,
118 ) => Effect.Effect<FilesystemGetMetadataResult>;
119
120 /**
121 * Read a UTF-8 text file relative to the workspace root, or any host file by
122 * absolute path.
123 */
124 readonly readFile: (
125 input: ProjectReadFileInput,
126 ) => Effect.Effect<
127 ProjectReadFileResult,
128 WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
129 >;
130 /**
131 * Write a file relative to the workspace root.
132 *
133 * Creates parent directories as needed and rejects paths that escape the
134 * workspace root.
135 */
136 readonly writeFile: (
137 input: ProjectWriteFileInput,
138 ) => Effect.Effect<
139 ProjectWriteFileResult,
140 WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
141 >;
142 }
143>()("t3/workspace/WorkspaceFileSystem") {}
144
145/** @public Service construction is part of the canonical Effect module API. */
146export const make = Effect.gen(function* () {
147 const fileSystem = yield* FileSystem.FileSystem;
148 const path = yield* Path.Path;
149 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
150 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
151
152 const metadataForPath = Effect.fnUntraced(function* (requestedPath: string) {
153 const expandedPath = expandHomePath(requestedPath, yield* HostProcess.HomeDirectory);
154 if (!path.isAbsolute(expandedPath)) return null;
155 const stat = yield* fileSystem.stat(expandedPath).pipe(Effect.option);
156 if (stat._tag === "None") return null;
157 if (stat.value.type === "Directory") return { kind: "directory" } as const;
158 if (stat.value.type !== "File") return { kind: "other" } as const;
159 let mimeType: string | undefined;
160 // Named extensions already choose the icon without a content read. For an
161 // extensionless regular file, read at most 512 bytes, never the whole file.
162 if (path.extname(expandedPath) === "" && stat.value.size > 0) {
163 mimeType = yield* Effect.tryPromise({
164 try: async () => {
165 const handle = await NodeFSP.open(
166 expandedPath,
167 NodeFS.constants.O_RDONLY | NodeFS.constants.O_NONBLOCK,
168 );
169 try {
170 if (!(await handle.stat()).isFile()) return undefined;
171 const buffer = Buffer.alloc(512);
172 const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
173 return fileHeaderMimeType(buffer.subarray(0, bytesRead));
174 } finally {
175 await handle.close();
176 }
177 },
178 catch: () => undefined,
179 }).pipe(Effect.catch(() => Effect.succeed(undefined)));
180 }
181 return {
182 kind: "file",
183 byteLength: Number(stat.value.size),
184 ...(mimeType === undefined ? {} : { mimeType }),
185 } satisfies FilesystemEntryMetadata;
186 });
187
188 const getMetadata: WorkspaceFileSystem["Service"]["getMetadata"] = Effect.fn(
189 "WorkspaceFileSystem.getMetadata",
190 )(function* (input) {
191 const paths = [...new Set(input.paths)];
192 const entries = yield* Effect.forEach(paths, metadataForPath, { concurrency: 8 });
193 const byPath = new Map(paths.map((value, index) => [value, entries[index] ?? null]));
194 return { entries: input.paths.map((value) => byPath.get(value) ?? null) };
195 });
196
197 /**
198 * Resolves the file a read targets. Workspace-relative paths must stay inside the
199 * root, symlinks included. An absolute path reads a host file in place, such as a
200 * report an agent wrote to a temp directory; it gets no root check.
201 */
202 const resolveReadTarget = Effect.fn("WorkspaceFileSystem.resolveReadTarget")(function* (
203 input: ProjectReadFileInput,
204 ) {
205 const requestedPath = input.relativePath.trim();
206 if (path.isAbsolute(requestedPath)) {
207 const realTargetPath = yield* Effect.tryPromise({
208 try: () => NodeFSP.realpath(requestedPath),
209 catch: (cause) =>
210 new WorkspaceFileSystemOperationError({
211 workspaceRoot: input.cwd,
212 relativePath: input.relativePath,
213 resolvedPath: requestedPath,
214 operationPath: requestedPath,
215 operation: "realpath-target",
216 cause,
217 }),
218 });
219 return { relativePath: requestedPath, realTargetPath };
220 }
221
222 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
223 workspaceRoot: input.cwd,
224 relativePath: input.relativePath,
225 });
226
227 const realWorkspaceRoot = yield* Effect.tryPromise({
228 try: () => NodeFSP.realpath(input.cwd),
229 catch: (cause) =>
230 new WorkspaceFileSystemOperationError({
231 workspaceRoot: input.cwd,
232 relativePath: input.relativePath,
233 resolvedPath: target.absolutePath,
234 operationPath: input.cwd,
235 operation: "realpath-workspace-root",
236 cause,
237 }),
238 });
239 const realTargetPath = yield* Effect.tryPromise({
240 try: () => NodeFSP.realpath(target.absolutePath),
241 catch: (cause) =>
242 new WorkspaceFileSystemOperationError({
243 workspaceRoot: input.cwd,
244 relativePath: input.relativePath,
245 resolvedPath: target.absolutePath,
246 operationPath: target.absolutePath,
247 operation: "realpath-target",
248 cause,
249 }),
250 });
251 const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
252 if (
253 relativeRealPath.startsWith(`..${path.sep}`) ||
254 relativeRealPath === ".." ||
255 path.isAbsolute(relativeRealPath)
256 ) {
257 return yield* new WorkspaceFilePathEscapeError({
258 workspaceRoot: input.cwd,
259 relativePath: input.relativePath,
260 resolvedWorkspaceRoot: realWorkspaceRoot,
261 resolvedPath: realTargetPath,
262 });
263 }
264 return { relativePath: target.relativePath, realTargetPath };
265 });
266
267 const readFile: WorkspaceFileSystem["Service"]["readFile"] = Effect.fn(
268 "WorkspaceFileSystem.readFile",
269 )(function* (input) {
270 const target = yield* resolveReadTarget(input);
271 const realTargetPath = target.realTargetPath;
272
273 return yield* Effect.acquireUseRelease(
274 Effect.tryPromise({
275 // Non-blocking so a FIFO cannot hang the open; the stat below rejects
276 // it. Regular files ignore the flag. Windows lacks it.
277 try: () =>
278 NodeFSP.open(
279 realTargetPath,
280 NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NONBLOCK ?? 0),
281 ),
282 catch: (cause) =>
283 new WorkspaceFileSystemOperationError({
284 workspaceRoot: input.cwd,
285 relativePath: input.relativePath,
286 resolvedPath: realTargetPath,
287 operationPath: realTargetPath,
288 operation: "open",
289 cause,
290 }),
291 }),
292 (handle) =>
293 Effect.gen(function* () {
294 const stat = yield* Effect.tryPromise({
295 try: () => handle.stat(),
296 catch: (cause) =>
297 new WorkspaceFileSystemOperationError({
298 workspaceRoot: input.cwd,
299 relativePath: input.relativePath,
300 resolvedPath: realTargetPath,
301 operationPath: realTargetPath,
302 operation: "stat",
303 cause,
304 }),
305 });
306 if (!stat.isFile()) {
307 return yield* new WorkspacePathNotFileError({
308 workspaceRoot: input.cwd,
309 relativePath: input.relativePath,
310 resolvedPath: realTargetPath,
311 });
312 }
313
314 const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
315 const buffer = Buffer.alloc(bytesToRead);
316 const { bytesRead } = yield* Effect.tryPromise({
317 try: () => handle.read(buffer, 0, bytesToRead, 0),
318 catch: (cause) =>
319 new WorkspaceFileSystemOperationError({
320 workspaceRoot: input.cwd,
321 relativePath: input.relativePath,
322 resolvedPath: realTargetPath,
323 operationPath: realTargetPath,
324 operation: "read",
325 cause,
326 }),
327 });
328 const fileBytes = buffer.subarray(0, bytesRead);
329 if (fileBytes.includes(0)) {
330 return yield* new WorkspaceBinaryFileError({
331 workspaceRoot: input.cwd,
332 relativePath: input.relativePath,
333 resolvedPath: realTargetPath,
334 });
335 }
336
337 return {
338 relativePath: target.relativePath,
339 contents: new TextDecoder("utf-8").decode(fileBytes),
340 byteLength: stat.size,
341 truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
342 };
343 }),
344 (handle) =>
345 Effect.tryPromise({
346 try: () => handle.close(),
347 catch: (cause) =>
348 new WorkspaceFileSystemOperationError({
349 workspaceRoot: input.cwd,
350 relativePath: input.relativePath,
351 resolvedPath: realTargetPath,
352 operationPath: realTargetPath,
353 operation: "close",
354 cause,
355 }),
356 }),
357 );
358 });
359
360 const writeFile: WorkspaceFileSystem["Service"]["writeFile"] = Effect.fn(
361 "WorkspaceFileSystem.writeFile",
362 )(function* (input) {
363 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
364 workspaceRoot: input.cwd,
365 relativePath: input.relativePath,
366 });
367
368 yield* fileSystem.makeDirectory(path.dirname(target.absolutePath), { recursive: true }).pipe(
369 Effect.mapError(
370 (cause) =>
371 new WorkspaceFileSystemOperationError({
372 workspaceRoot: input.cwd,
373 relativePath: input.relativePath,
374 resolvedPath: target.absolutePath,
375 operationPath: path.dirname(target.absolutePath),
376 operation: "make-directory",
377 cause,
378 }),
379 ),
380 );
381 yield* fileSystem.writeFileString(target.absolutePath, input.contents).pipe(
382 Effect.mapError(
383 (cause) =>
384 new WorkspaceFileSystemOperationError({
385 workspaceRoot: input.cwd,
386 relativePath: input.relativePath,
387 resolvedPath: target.absolutePath,
388 operationPath: target.absolutePath,
389 operation: "write-file",
390 cause,
391 }),
392 ),
393 );
394 yield* workspaceEntries.refresh(input.cwd);
395 return { relativePath: target.relativePath };
396 });
397
398 return WorkspaceFileSystem.of({ getMetadata, readFile, writeFile });
399});
400
401export const layer = Layer.effect(WorkspaceFileSystem, make);