Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as EffectAcpErrors from "effect-acp/errors";
5import type * as EffectAcpSchema from "effect-acp/compat";
6import * as NodePath from "node:path";
7
8/**
9 * Client-side handlers for the ACP `fs` capability.
10 *
11 * Agents that prefer client-mediated file access send `fs/read_text_file` and
12 * `fs/write_text_file` instead of touching the disk themselves. The handlers
13 * run with the same privileges as the agent process T3 already spawned, so
14 * they honor absolute paths without extra confinement.
15 */
16
17const fsRequestError = (message: string, cause?: unknown) =>
18 EffectAcpErrors.AcpRequestError.internalError(
19 message,
20 undefined,
21 cause === undefined ? {} : { cause },
22 );
23
24function assertAbsolutePath(path: string) {
25 return NodePath.isAbsolute(path)
26 ? Effect.void
27 : Effect.fail(fsRequestError(`ACP fs requests require an absolute path, received '${path}'.`));
28}
29
30/** Handles `fs/read_text_file`, applying the optional 1-based line window. */
31export const acpReadTextFile = (
32 fileSystem: FileSystem.FileSystem,
33 request: EffectAcpSchema.ReadTextFileRequest,
34): Effect.Effect<EffectAcpSchema.ReadTextFileResponse, EffectAcpErrors.AcpRequestError> =>
35 Effect.gen(function* () {
36 yield* assertAbsolutePath(request.path);
37 const content = yield* fileSystem
38 .readFileString(request.path)
39 .pipe(
40 Effect.mapError((cause) =>
41 fsRequestError(`Could not read text file '${request.path}'.`, cause),
42 ),
43 );
44 const line = request.line ?? undefined;
45 const limit = request.limit ?? undefined;
46 if (line === undefined && limit === undefined) {
47 return { content };
48 }
49 const lines = content.split(/\r?\n/u);
50 const startIndex = Math.max(0, (line ?? 1) - 1);
51 const selected =
52 limit === undefined ? lines.slice(startIndex) : lines.slice(startIndex, startIndex + limit);
53 return { content: selected.join("\n") };
54 });
55
56/** Handles `fs/write_text_file`, creating parent directories when needed. */
57export const acpWriteTextFile = (
58 fileSystem: FileSystem.FileSystem,
59 request: EffectAcpSchema.WriteTextFileRequest,
60): Effect.Effect<EffectAcpSchema.WriteTextFileResponse, EffectAcpErrors.AcpRequestError> =>
61 Effect.gen(function* () {
62 yield* assertAbsolutePath(request.path);
63 yield* fileSystem.makeDirectory(NodePath.dirname(request.path), { recursive: true }).pipe(
64 Effect.andThen(fileSystem.writeFileString(request.path, request.content)),
65 Effect.mapError((cause) =>
66 fsRequestError(`Could not write text file '${request.path}'.`, cause),
67 ),
68 );
69 return {};
70 });