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 ProjectReadFileInput,
17 ProjectReadFileResult,
18 ProjectWriteFileInput,
19 ProjectWriteFileResult,
20} from "@t3tools/contracts";
21import * as Context from "effect/Context";
22import * as Effect from "effect/Effect";
23import * as FileSystem from "effect/FileSystem";
24import * as Layer from "effect/Layer";
25import * as Path from "effect/Path";
26import * as Schema from "effect/Schema";
27
28import * as WorkspaceEntries from "./WorkspaceEntries.ts";
29import * as WorkspacePaths from "./WorkspacePaths.ts";
30
31const PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024;
32
33export class WorkspaceFileSystemOperationError extends Schema.TaggedErrorClass<WorkspaceFileSystemOperationError>()(
34 "WorkspaceFileSystemOperationError",
35 {
36 workspaceRoot: Schema.String,
37 relativePath: Schema.String,
38 resolvedPath: Schema.String,
39 operationPath: Schema.String,
40 operation: Schema.Literals([
41 "realpath-workspace-root",
42 "realpath-target",
43 "open",
44 "stat",
45 "read",
46 "close",
47 "make-directory",
48 "write-file",
49 ]),
50 cause: Schema.Defect(),
51 },
52) {
53 override get message(): string {
54 return `Workspace file operation '${this.operation}' failed at '${this.operationPath}' for resolved path '${this.resolvedPath}' (requested as '${this.relativePath}' in '${this.workspaceRoot}').`;
55 }
56}
57
58export class WorkspaceFilePathEscapeError extends Schema.TaggedErrorClass<WorkspaceFilePathEscapeError>()(
59 "WorkspaceFilePathEscapeError",
60 {
61 workspaceRoot: Schema.String,
62 relativePath: Schema.String,
63 resolvedWorkspaceRoot: Schema.String,
64 resolvedPath: Schema.String,
65 },
66) {
67 override get message(): string {
68 return `Workspace file '${this.relativePath}' resolves outside workspace root '${this.workspaceRoot}': ${this.resolvedPath}`;
69 }
70}
71
72export class WorkspacePathNotFileError extends Schema.TaggedErrorClass<WorkspacePathNotFileError>()(
73 "WorkspacePathNotFileError",
74 {
75 workspaceRoot: Schema.String,
76 relativePath: Schema.String,
77 resolvedPath: Schema.String,
78 },
79) {
80 override get message(): string {
81 return `Workspace path '${this.relativePath}' in '${this.workspaceRoot}' is not a file: ${this.resolvedPath}`;
82 }
83}
84
85export class WorkspaceBinaryFileError extends Schema.TaggedErrorClass<WorkspaceBinaryFileError>()(
86 "WorkspaceBinaryFileError",
87 {
88 workspaceRoot: Schema.String,
89 relativePath: Schema.String,
90 resolvedPath: Schema.String,
91 },
92) {
93 override get message(): string {
94 return `Workspace file '${this.relativePath}' in '${this.workspaceRoot}' is binary and cannot be previewed as text.`;
95 }
96}
97
98export const WorkspaceFileSystemError = Schema.Union([
99 WorkspaceFileSystemOperationError,
100 WorkspaceFilePathEscapeError,
101 WorkspacePathNotFileError,
102 WorkspaceBinaryFileError,
103]);
104export type WorkspaceFileSystemError = typeof WorkspaceFileSystemError.Type;
105
106/** Service tag for workspace file operations. */
107export class WorkspaceFileSystem extends Context.Service<
108 WorkspaceFileSystem,
109 {
110 /**
111 * Read a UTF-8 text file relative to the workspace root, or any host file by
112 * absolute path.
113 */
114 readonly readFile: (
115 input: ProjectReadFileInput,
116 ) => Effect.Effect<
117 ProjectReadFileResult,
118 WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
119 >;
120 /**
121 * Write a file relative to the workspace root.
122 *
123 * Creates parent directories as needed and rejects paths that escape the
124 * workspace root.
125 */
126 readonly writeFile: (
127 input: ProjectWriteFileInput,
128 ) => Effect.Effect<
129 ProjectWriteFileResult,
130 WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
131 >;
132 }
133>()("t3/workspace/WorkspaceFileSystem") {}
134
135export const make = Effect.gen(function* () {
136 const fileSystem = yield* FileSystem.FileSystem;
137 const path = yield* Path.Path;
138 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
139 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
140
141 /**
142 * Resolves the file a read targets. Workspace-relative paths must stay inside the
143 * root, symlinks included. An absolute path reads a host file in place, such as a
144 * report an agent wrote to a temp directory; it gets no root check.
145 */
146 const resolveReadTarget = Effect.fn("WorkspaceFileSystem.resolveReadTarget")(function* (
147 input: ProjectReadFileInput,
148 ) {
149 const requestedPath = input.relativePath.trim();
150 if (path.isAbsolute(requestedPath)) {
151 const realTargetPath = yield* Effect.tryPromise({
152 try: () => NodeFSP.realpath(requestedPath),
153 catch: (cause) =>
154 new WorkspaceFileSystemOperationError({
155 workspaceRoot: input.cwd,
156 relativePath: input.relativePath,
157 resolvedPath: requestedPath,
158 operationPath: requestedPath,
159 operation: "realpath-target",
160 cause,
161 }),
162 });
163 return { relativePath: requestedPath, realTargetPath };
164 }
165
166 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
167 workspaceRoot: input.cwd,
168 relativePath: input.relativePath,
169 });
170
171 const realWorkspaceRoot = yield* Effect.tryPromise({
172 try: () => NodeFSP.realpath(input.cwd),
173 catch: (cause) =>
174 new WorkspaceFileSystemOperationError({
175 workspaceRoot: input.cwd,
176 relativePath: input.relativePath,
177 resolvedPath: target.absolutePath,
178 operationPath: input.cwd,
179 operation: "realpath-workspace-root",
180 cause,
181 }),
182 });
183 const realTargetPath = yield* Effect.tryPromise({
184 try: () => NodeFSP.realpath(target.absolutePath),
185 catch: (cause) =>
186 new WorkspaceFileSystemOperationError({
187 workspaceRoot: input.cwd,
188 relativePath: input.relativePath,
189 resolvedPath: target.absolutePath,
190 operationPath: target.absolutePath,
191 operation: "realpath-target",
192 cause,
193 }),
194 });
195 const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
196 if (
197 relativeRealPath.startsWith(`..${path.sep}`) ||
198 relativeRealPath === ".." ||
199 path.isAbsolute(relativeRealPath)
200 ) {
201 return yield* new WorkspaceFilePathEscapeError({
202 workspaceRoot: input.cwd,
203 relativePath: input.relativePath,
204 resolvedWorkspaceRoot: realWorkspaceRoot,
205 resolvedPath: realTargetPath,
206 });
207 }
208 return { relativePath: target.relativePath, realTargetPath };
209 });
210
211 const readFile: WorkspaceFileSystem["Service"]["readFile"] = Effect.fn(
212 "WorkspaceFileSystem.readFile",
213 )(function* (input) {
214 const target = yield* resolveReadTarget(input);
215 const realTargetPath = target.realTargetPath;
216
217 return yield* Effect.acquireUseRelease(
218 Effect.tryPromise({
219 // Non-blocking so a FIFO cannot hang the open; the stat below rejects
220 // it. Regular files ignore the flag. Windows lacks it.
221 try: () =>
222 NodeFSP.open(
223 realTargetPath,
224 NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NONBLOCK ?? 0),
225 ),
226 catch: (cause) =>
227 new WorkspaceFileSystemOperationError({
228 workspaceRoot: input.cwd,
229 relativePath: input.relativePath,
230 resolvedPath: realTargetPath,
231 operationPath: realTargetPath,
232 operation: "open",
233 cause,
234 }),
235 }),
236 (handle) =>
237 Effect.gen(function* () {
238 const stat = yield* Effect.tryPromise({
239 try: () => handle.stat(),
240 catch: (cause) =>
241 new WorkspaceFileSystemOperationError({
242 workspaceRoot: input.cwd,
243 relativePath: input.relativePath,
244 resolvedPath: realTargetPath,
245 operationPath: realTargetPath,
246 operation: "stat",
247 cause,
248 }),
249 });
250 if (!stat.isFile()) {
251 return yield* new WorkspacePathNotFileError({
252 workspaceRoot: input.cwd,
253 relativePath: input.relativePath,
254 resolvedPath: realTargetPath,
255 });
256 }
257
258 const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
259 const buffer = Buffer.alloc(bytesToRead);
260 const { bytesRead } = yield* Effect.tryPromise({
261 try: () => handle.read(buffer, 0, bytesToRead, 0),
262 catch: (cause) =>
263 new WorkspaceFileSystemOperationError({
264 workspaceRoot: input.cwd,
265 relativePath: input.relativePath,
266 resolvedPath: realTargetPath,
267 operationPath: realTargetPath,
268 operation: "read",
269 cause,
270 }),
271 });
272 const fileBytes = buffer.subarray(0, bytesRead);
273 if (fileBytes.includes(0)) {
274 return yield* new WorkspaceBinaryFileError({
275 workspaceRoot: input.cwd,
276 relativePath: input.relativePath,
277 resolvedPath: realTargetPath,
278 });
279 }
280
281 return {
282 relativePath: target.relativePath,
283 contents: new TextDecoder("utf-8").decode(fileBytes),
284 byteLength: stat.size,
285 truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
286 };
287 }),
288 (handle) =>
289 Effect.tryPromise({
290 try: () => handle.close(),
291 catch: (cause) =>
292 new WorkspaceFileSystemOperationError({
293 workspaceRoot: input.cwd,
294 relativePath: input.relativePath,
295 resolvedPath: realTargetPath,
296 operationPath: realTargetPath,
297 operation: "close",
298 cause,
299 }),
300 }),
301 );
302 });
303
304 const writeFile: WorkspaceFileSystem["Service"]["writeFile"] = Effect.fn(
305 "WorkspaceFileSystem.writeFile",
306 )(function* (input) {
307 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
308 workspaceRoot: input.cwd,
309 relativePath: input.relativePath,
310 });
311
312 yield* fileSystem.makeDirectory(path.dirname(target.absolutePath), { recursive: true }).pipe(
313 Effect.mapError(
314 (cause) =>
315 new WorkspaceFileSystemOperationError({
316 workspaceRoot: input.cwd,
317 relativePath: input.relativePath,
318 resolvedPath: target.absolutePath,
319 operationPath: path.dirname(target.absolutePath),
320 operation: "make-directory",
321 cause,
322 }),
323 ),
324 );
325 yield* fileSystem.writeFileString(target.absolutePath, input.contents).pipe(
326 Effect.mapError(
327 (cause) =>
328 new WorkspaceFileSystemOperationError({
329 workspaceRoot: input.cwd,
330 relativePath: input.relativePath,
331 resolvedPath: target.absolutePath,
332 operationPath: target.absolutePath,
333 operation: "write-file",
334 cause,
335 }),
336 ),
337 );
338 yield* workspaceEntries.refresh(input.cwd);
339 return { relativePath: target.relativePath };
340 });
341
342 return WorkspaceFileSystem.of({ readFile, writeFile });
343});
344
345export const layer = Layer.effect(WorkspaceFileSystem, make);