Repository navigation
Expand file tree
/
Copy pathWorkspaceFileSystem.ts
More file actions
185 lines (177 loc) · 6.08 KB
/
Copy pathWorkspaceFileSystem.ts
File metadata and controls
185 lines (177 loc) · 6.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
/**
* Effect's `FileSystem` over a session's Computer, so fold's file tools and skill loader work on the
* workspace unchanged. It covers what they call: reading, writing, making directories, removing,
* `stat`, `access`, `exists`, `realPath` and listing a directory, and appending, which fold's output store
* does. Every other method is Effect's no-op.
*
* The workspace has no permissions, so `access` only checks the path exists. It has symlinks, but
* `realPath` returns the path unchanged: fold only uses it to key its per-file write lock.
*/
import type { RpcCallError } from 'alchemy'
import { ByteSize, Effect, FileSystem, Option, PlatformError } from 'effect'
import type { FileInfo, ComputerResult } from './computer/Contract'
/** The Computer's file methods, as its RPC stub returns them. */
export type ComputerFiles = {
readonly readFile: (path: string) => Effect.Effect<ComputerResult<Uint8Array>, RpcCallError>
readonly writeFile: (path: string, content: string) => Effect.Effect<ComputerResult<null>, RpcCallError>
readonly mkdir: (path: string, recursive: boolean) => Effect.Effect<ComputerResult<null>, RpcCallError>
readonly rm: (path: string, recursive: boolean, force: boolean) => Effect.Effect<ComputerResult<null>, RpcCallError>
readonly stat: (path: string) => Effect.Effect<ComputerResult<FileInfo>, RpcCallError>
readonly readdir: (path: string) => Effect.Effect<ComputerResult<ReadonlyArray<string>>, RpcCallError>
}
const SYSTEM_ERROR_TAGS = new Map<string, PlatformError.SystemErrorTag>([
['ENOENT', 'NotFound'],
['EEXIST', 'AlreadyExists'],
['EACCES', 'PermissionDenied'],
['EPERM', 'PermissionDenied'],
['EISDIR', 'BadResource'],
['ENOTDIR', 'BadResource'],
['EINVAL', 'InvalidData'],
])
/** A failed workspace file call, as the `FileSystem` error fold's tools read. */
const workspaceFileError = (input: {
readonly kind: PlatformError.SystemErrorTag
readonly method: string
readonly path: string
readonly description: string
readonly cause: RpcCallError | { readonly code: string }
}) =>
PlatformError.systemError({
_tag: input.kind,
module: 'FileSystem',
method: input.method,
pathOrDescriptor: input.path,
description: input.description,
cause: input.cause,
})
/**
* One Computer call as an Effect. A failed operation keeps its code in `cause.code`, where fold's tools
* read it; a failed RPC is `Unknown`, so the tool call fails and the session goes on.
*/
const run = <A>(
method: string,
path: string,
call: Effect.Effect<ComputerResult<A>, RpcCallError>,
): Effect.Effect<A, PlatformError.PlatformError> =>
call.pipe(
Effect.mapError((cause) =>
workspaceFileError({ kind: 'Unknown', method, path, description: cause.message, cause }),
),
Effect.flatMap((result) =>
result.ok
? Effect.succeed(result.value)
: Effect.fail(
workspaceFileError({
kind: SYSTEM_ERROR_TAGS.get(result.code) ?? 'Unknown',
method,
path,
description: result.message,
cause: { code: result.code },
}),
),
),
Effect.tap(() => Effect.logInfo('workspace.file').pipe(Effect.annotateLogs({ method, path, outcome: 'ok' }))),
Effect.tapError((error) =>
Effect.logInfo('workspace.file').pipe(
Effect.annotateLogs({ method, path, outcome: error.reason._tag, error: error.message }),
),
),
)
const toInfo = (info: FileInfo): FileSystem.File.Info => ({
type: info.type,
mtime: Option.some(new Date(info.mtime)),
atime: Option.none(),
birthtime: Option.none(),
dev: 0,
ino: Option.some(info.inode),
mode: info.mode,
nlink: Option.none(),
uid: Option.none(),
gid: Option.none(),
rdev: Option.none(),
size: ByteSize.bytes(info.size),
blksize: Option.none(),
blocks: Option.none(),
})
/** The workspace as a `FileSystem`, over `computer`, which looks up the session's Computer. */
export const workspaceFileSystem = (computer: Effect.Effect<ComputerFiles>): FileSystem.FileSystem => {
const stat = (path: string) =>
run(
'stat',
path,
Effect.flatMap(computer, (files) => files.stat(path)),
).pipe(Effect.map(toInfo))
const readFile = (path: string) =>
run(
'readFile',
path,
Effect.flatMap(computer, (files) => files.readFile(path)),
)
return FileSystem.makeNoop({
readFile,
readFileString: (path, encoding) =>
Effect.flatMap(readFile(path), (bytes) =>
Effect.try({
try: () => new TextDecoder(encoding).decode(bytes),
catch: (cause) =>
PlatformError.badArgument({
module: 'FileSystem',
method: 'readFileString',
description: 'invalid encoding',
cause,
}),
}),
),
/** The workspace has no append, so appending (flag `a`) rewrites the file with `data` added. */
writeFileString: (path, data, options) =>
Effect.gen(function* () {
const existing = options?.flag?.startsWith('a')
? yield* readFile(path).pipe(
Effect.map((bytes) => new TextDecoder().decode(bytes)),
Effect.catchReason('PlatformError', 'NotFound', () => Effect.succeed('')),
)
: ''
yield* run(
'writeFileString',
path,
Effect.flatMap(computer, (files) => files.writeFile(path, existing + data)),
)
}),
makeDirectory: (path, options) =>
run(
'makeDirectory',
path,
Effect.flatMap(computer, (files) => files.mkdir(path, options?.recursive ?? false)),
),
remove: (path, options) =>
run(
'remove',
path,
Effect.flatMap(computer, (files) =>
files.rm(path, options?.recursive ?? false, options?.force ?? false),
),
),
stat,
access: (path) => Effect.asVoid(stat(path)),
exists: (path) =>
stat(path).pipe(
Effect.as(true),
Effect.catchReasons('PlatformError', { NotFound: () => Effect.succeed(false) }),
),
realPath: (path) => Effect.as(stat(path), path),
readDirectory: (path, options) =>
options?.recursive === true
? Effect.fail(
PlatformError.badArgument({
module: 'FileSystem',
method: 'readDirectory',
description: 'recursive listing is not supported',
}),
)
: run(
'readDirectory',
path,
Effect.flatMap(computer, (files) => files.readdir(path)),
).pipe(Effect.map((names) => [...names])),
})
}