@codeworksh/plugin 0.1.0-canary.18.1.g00a873ad → 0.1.0-canary.20.1.gf5454e1e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,347 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
+ import { posix } from "./posix.mjs";
3
+ import { Context, Effect, Schema } from "effect";
4
+ //#region src/sandbox/scan.ts
5
+ var scan_exports = /* @__PURE__ */ __exportAll({
6
+ LineScanner: () => LineScanner,
7
+ parse: () => parse,
8
+ script: () => script,
9
+ scriptArgs: () => scriptArgs,
10
+ validate: () => validate,
11
+ viaShell: () => viaShell
12
+ });
13
+ /** A defect, not a file error: callers derive these from already-validated input. */
14
+ const validate = (options) => {
15
+ const { startLine, endLine, maxBytes } = options;
16
+ if (!Number.isSafeInteger(startLine) || startLine < 0) throw new RangeError(`Invalid startLine: ${startLine}`);
17
+ if (endLine !== void 0 && (!Number.isSafeInteger(endLine) || endLine <= startLine)) throw new RangeError(`Invalid endLine: ${endLine}`);
18
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) throw new RangeError(`Invalid maxBytes: ${maxBytes}`);
19
+ };
20
+ const NEWLINE = 10;
21
+ const BOM = [
22
+ 239,
23
+ 187,
24
+ 191
25
+ ];
26
+ /**
27
+ * Computes a {@link LineScan} from a file's bytes fed in order, in memory
28
+ * bounded by `maxBytes`. Feed at most the file size observed when the read
29
+ * started, so a file that keeps growing cannot keep the scan going.
30
+ */
31
+ var LineScanner = class {
32
+ start;
33
+ end;
34
+ maxBytes;
35
+ decoder = new TextDecoder("utf-8", { ignoreBOM: true });
36
+ /** The first bytes, held until it is known whether they are a byte-order mark. */
37
+ head = [];
38
+ totalBytes = 0;
39
+ line = 0;
40
+ lineLength = 0;
41
+ lineOpen = false;
42
+ /** The current line's bytes, kept only while it is selected and could still fit. */
43
+ pieces = [];
44
+ selected = [];
45
+ selectedBytes = 0;
46
+ firstLineBytes = 0;
47
+ full = false;
48
+ constructor(options) {
49
+ validate(options);
50
+ this.start = options.startLine;
51
+ this.end = options.endLine ?? Number.POSITIVE_INFINITY;
52
+ this.maxBytes = options.maxBytes;
53
+ }
54
+ push(chunk) {
55
+ this.totalBytes += chunk.length;
56
+ if (this.head !== void 0) {
57
+ const take = Math.min(BOM.length - this.head.length, chunk.length);
58
+ this.head.push(...chunk.subarray(0, take));
59
+ if (this.head.length < BOM.length) return;
60
+ this.releaseHead();
61
+ chunk = chunk.subarray(take);
62
+ }
63
+ this.scan(chunk);
64
+ }
65
+ finish() {
66
+ if (this.head !== void 0) this.releaseHead();
67
+ if (this.lineOpen) this.endLine();
68
+ return {
69
+ text: this.selected.map((line) => this.decoder.decode(line)).join("\n"),
70
+ lines: this.selected.length,
71
+ totalLines: this.line,
72
+ totalBytes: this.totalBytes,
73
+ firstLineBytes: this.firstLineBytes
74
+ };
75
+ }
76
+ releaseHead() {
77
+ const head = Uint8Array.from(this.head ?? []);
78
+ this.head = void 0;
79
+ if (!(head.length === BOM.length && BOM.every((byte, index) => head[index] === byte))) this.scan(head);
80
+ }
81
+ scan(chunk) {
82
+ let from = 0;
83
+ while (from < chunk.length) {
84
+ const newline = chunk.indexOf(NEWLINE, from);
85
+ const to = newline === -1 ? chunk.length : newline;
86
+ this.append(chunk.subarray(from, to));
87
+ if (newline === -1) return;
88
+ this.endLine();
89
+ from = newline + 1;
90
+ }
91
+ }
92
+ isSelected() {
93
+ return !this.full && this.line >= this.start && this.line < this.end;
94
+ }
95
+ append(bytes) {
96
+ if (bytes.length === 0) {
97
+ this.lineOpen = true;
98
+ return;
99
+ }
100
+ this.lineOpen = true;
101
+ if (this.isSelected() && this.lineLength + bytes.length <= this.maxBytes) this.pieces.push(new Uint8Array(bytes));
102
+ this.lineLength += bytes.length;
103
+ }
104
+ endLine() {
105
+ if (this.isSelected()) {
106
+ const first = this.selected.length === 0;
107
+ if (first) this.firstLineBytes = this.lineLength;
108
+ const added = first ? this.lineLength : this.lineLength + 1;
109
+ if (this.selectedBytes + added > this.maxBytes) this.full = true;
110
+ else {
111
+ this.selected.push(concat(this.pieces, this.lineLength));
112
+ this.selectedBytes += added;
113
+ }
114
+ }
115
+ this.pieces = [];
116
+ this.lineLength = 0;
117
+ this.lineOpen = false;
118
+ this.line++;
119
+ }
120
+ };
121
+ const concat = (pieces, length) => {
122
+ if (pieces.length === 1) return pieces[0];
123
+ const out = new Uint8Array(length);
124
+ let offset = 0;
125
+ for (const piece of pieces) {
126
+ out.set(piece, offset);
127
+ offset += piece.length;
128
+ }
129
+ return out;
130
+ };
131
+ /**
132
+ * {@link LineScanner} as a POSIX shell script, for backends that only expose a
133
+ * process API. Run as `sh -c <script> _ <path> <startLine> <endLine|-1> <maxBytes>`.
134
+ * The whole file is read inside the sandbox; only the window is printed, after a
135
+ * header line `<lines> <totalLines> <totalBytes> <firstLineBytes>` and before a
136
+ * closing `|` — see {@link parse}.
137
+ * Exits 2 when the path does not exist.
138
+ */
139
+ const script = [
140
+ "[ -e \"$1\" ] || exit 2",
141
+ "size=$(($(wc -c < \"$1\"))) || exit 1",
142
+ "head -c \"$size\" -- \"$1\" | LC_ALL=C awk -v s=\"$2\" -v e=\"$3\" -v m=\"$4\" -v size=\"$size\" '",
143
+ "NR == 1 && $0 == \"\\357\\273\\277\" && size == 3 { exit }",
144
+ "NR == 1 && substr($0, 1, 3) == \"\\357\\273\\277\" { $0 = substr($0, 4) }",
145
+ "{ total = NR }",
146
+ "NR > s && (e < 0 || NR <= e) && !full {",
147
+ " len = length($0)",
148
+ " added = lines == 0 ? len : len + 1",
149
+ " if (lines == 0 && !seen) { seen = 1; first = len }",
150
+ " if (bytes + added > m) { full = 1; next }",
151
+ " out = lines == 0 ? $0 : out \"\\n\" $0",
152
+ " bytes += added; lines++",
153
+ "}",
154
+ "END { printf \"%.0f %.0f %.0f %.0f\\n%s|\", lines, total, size, first, out }",
155
+ "'"
156
+ ].join("\n");
157
+ /** Arguments for {@link script} after the path. */
158
+ const scriptArgs = (options) => {
159
+ validate(options);
160
+ return [
161
+ String(options.startLine),
162
+ String(options.endLine ?? -1),
163
+ String(options.maxBytes)
164
+ ];
165
+ };
166
+ /** Read {@link script}'s output. */
167
+ const parse = (stdout) => {
168
+ const body = stdout.trimEnd();
169
+ const newline = body.indexOf("\n");
170
+ const header = (newline === -1 ? "" : body.slice(0, newline)).trim().split(/\s+/).map(Number);
171
+ const [lines, totalLines, totalBytes, firstLineBytes] = header;
172
+ if (!body.endsWith("|") || header.length !== 4 || header.some((value) => !Number.isSafeInteger(value))) throw new Error(`Unexpected scanLines output: ${stdout.slice(0, 200)}`);
173
+ return {
174
+ text: body.slice(newline + 1, -1),
175
+ lines,
176
+ totalLines,
177
+ totalBytes,
178
+ firstLineBytes
179
+ };
180
+ };
181
+ /**
182
+ * `Provider.scanLines` for a backend that runs an argument vector and collects
183
+ * its output: runs {@link script} in the sandbox and reads the result. A missing
184
+ * path rejects with `ENOENT`, the shape `isNotFoundError` recognises.
185
+ */
186
+ const viaShell = (run) => async (path, options) => {
187
+ const result = await run([
188
+ "sh",
189
+ "-c",
190
+ script,
191
+ "_",
192
+ path,
193
+ ...scriptArgs(options)
194
+ ]);
195
+ if (result.exitCode === 2) throw Object.assign(/* @__PURE__ */ new Error(`ENOENT: no such file or directory, scanLines '${path}'`), { code: "ENOENT" });
196
+ if (result.exitCode !== 0) throw new Error(`scanLines failed (exit ${result.exitCode}): ${(result.stderr ?? result.stdout).trim()}`);
197
+ return parse(result.stdout);
198
+ };
199
+ //#endregion
200
+ //#region src/sandbox/filesystem.ts
201
+ var filesystem_exports = /* @__PURE__ */ __exportAll({
202
+ FileSystemError: () => FileSystemError,
203
+ OperationUnsupportedError: () => OperationUnsupportedError,
204
+ SandboxFileSystem: () => filesystem_exports,
205
+ Scan: () => scan_exports,
206
+ Service: () => Service,
207
+ fromProvider: () => fromProvider,
208
+ isNotFoundError: () => isNotFoundError,
209
+ realpathScripts: () => realpathScripts,
210
+ validateRmOptions: () => validateRmOptions,
211
+ withCwd: () => withCwd
212
+ });
213
+ /**
214
+ * The runtime filesystem contract, independent of any backend.
215
+ *
216
+ * Two surfaces, deliberately:
217
+ * - {@link Provider} is what a backend implements — plain promises that reject,
218
+ * matching every SDK we wrap.
219
+ * - {@link Interface} is what the harness consumes — Effect with a typed error
220
+ * channel and tracing spans. {@link fromProvider} bridges the two exactly
221
+ * once, so no consumer ever writes `Effect.tryPromise` against a filesystem.
222
+ *
223
+ * Implementations:
224
+ * - Local:
225
+ * implement it over a VFS (`./local`);
226
+ * local filesystem use OS primitives; hence have broader filesytem capabilities.
227
+ *
228
+ * - Remote:
229
+ * implement it over a provider (`./remote`).
230
+ * remote filesytems depends on the interface provided by the remote provider; hence can have limited filesytem capabilities.
231
+ *
232
+ * `isFile`/`isDirectory` are required booleans; size, mtime, and isSymbolicLink are omitted when the
233
+ * backend cannot report them — never fabricated.
234
+ *
235
+ * **Paths are POSIX, and the harness is Unix-only (for now!).** Every path uses `/`
236
+ * separators on both the host and inside a sandbox — Windows is not supported,
237
+ * so no translation layer exists. Consumers must use the shared Effect POSIX
238
+ * path implementation, never the platform default, or a host running the harness would
239
+ * impose its own flavour on a remote sandbox's paths. Relative paths resolve
240
+ * against the backend's configured `cwd`.
241
+ */
242
+ var OperationUnsupportedError = class extends Schema.TaggedError()("OperationUnsupportedError", {
243
+ operation: Schema.String,
244
+ message: Schema.String
245
+ }) {};
246
+ /** A backend operation failed. `cause` carries the provider's own rejection. */
247
+ var FileSystemError = class extends Schema.TaggedError()("SandboxFileSystemError", {
248
+ method: Schema.String,
249
+ path: Schema.String,
250
+ cause: Schema.optional(Schema.Defect())
251
+ }) {};
252
+ /** Whether a provider failure means the path itself is definitively absent. */
253
+ const isNotFoundError = (cause) => {
254
+ const code = cause?.code;
255
+ return code === "ENOENT" || code === "ENOTDIR";
256
+ };
257
+ /**
258
+ * Shell forms of `realpath` for backends that only expose a process API. Run as
259
+ * `sh -c <script> _ <path>`, trying each in turn. `realpath -e` (coreutils)
260
+ * resolves every component, a symlinked file included, and fails on a missing
261
+ * path. Where it is absent, `pwd -P` is the portable primitive: directories
262
+ * resolve directly, anything else resolves its parent and keeps the final name
263
+ * as given — so a symlinked *file* stays unresolved there.
264
+ */
265
+ const realpathScripts = [
266
+ "realpath -e -- \"$1\"",
267
+ "cd -- \"$1\" && pwd -P",
268
+ "cd -- \"$(dirname -- \"$1\")\" && printf '%s/%s' \"$(pwd -P)\" \"$(basename -- \"$1\")\""
269
+ ];
270
+ /** The runtime filesystem service — the live {@link Interface} for the active sandbox. */
271
+ var Service = class extends Context.Service()("@codeworksh/plugin/sandbox/filesystem/Service") {};
272
+ /**
273
+ * Reject `rm` options a provider does not implement, before any mutation. Only
274
+ * `recursive` and `force` are part of the contract; anything else is refused
275
+ * loudly rather than silently ignored.
276
+ */
277
+ const validateRmOptions = (options, operation = "rm") => Effect.suspend(() => {
278
+ for (const option of Object.keys(options ?? {})) {
279
+ if (option === "recursive" || option === "force") continue;
280
+ return Effect.fail(new OperationUnsupportedError({
281
+ operation,
282
+ message: `Unsupported rm option: ${option}`
283
+ }));
284
+ }
285
+ return Effect.void;
286
+ });
287
+ /**
288
+ * Lift a {@link Provider} into the runtime {@link Interface}: one place that
289
+ * converts rejections into {@link FileSystemError}, validates `rm` options,
290
+ * creates missing parents on write, and names a tracing span per operation.
291
+ */
292
+ const fromProvider = (provider) => {
293
+ const attempt = (method, path, run) => Effect.tryPromise({
294
+ try: run,
295
+ catch: (cause) => new FileSystemError({
296
+ method,
297
+ path,
298
+ cause
299
+ })
300
+ });
301
+ const writeCreatingParents = (path, content) => {
302
+ const write = attempt("writeFile", path, () => provider.writeFile(path, content));
303
+ const parent = posix.dirname(path);
304
+ return write.pipe(Effect.catch(() => attempt("mkdir", parent, () => provider.mkdir(parent, { recursive: true })).pipe(Effect.ignore, Effect.andThen(write))));
305
+ };
306
+ return {
307
+ readFile: Effect.fn("SandboxFileSystem.readFile")((path) => attempt("readFile", path, () => provider.readFile(path))),
308
+ readFileBuffer: Effect.fn("SandboxFileSystem.readFileBuffer")((path) => attempt("readFileBuffer", path, () => provider.readFileBuffer(path))),
309
+ writeFile: Effect.fn("SandboxFileSystem.writeFile")(writeCreatingParents),
310
+ stat: Effect.fn("SandboxFileSystem.stat")((path) => attempt("stat", path, () => provider.stat(path))),
311
+ ...provider.lstat === void 0 ? {} : { lstat: Effect.fn("SandboxFileSystem.lstat")((path) => attempt("lstat", path, () => provider.lstat(path))) },
312
+ readdir: Effect.fn("SandboxFileSystem.readdir")((path) => attempt("readdir", path, () => provider.readdir(path))),
313
+ exists: Effect.fn("SandboxFileSystem.exists")((path) => attempt("exists", path, () => provider.exists(path))),
314
+ mkdir: Effect.fn("SandboxFileSystem.mkdir")((path, options) => attempt("mkdir", path, () => provider.mkdir(path, options))),
315
+ rm: Effect.fn("SandboxFileSystem.rm")((path, options) => validateRmOptions(options).pipe(Effect.andThen(attempt("rm", path, () => provider.rm(path, options))))),
316
+ realpath: Effect.fn("SandboxFileSystem.realpath")((path) => attempt("realpath", path, () => provider.realpath(path))),
317
+ scanLines: Effect.fn("SandboxFileSystem.scanLines")((path, options) => Effect.sync(() => validate(options)).pipe(Effect.andThen(attempt("scanLines", path, () => provider.scanLines(path, options)))))
318
+ };
319
+ };
320
+ /**
321
+ * Bind a cwd-neutral filesystem to one mount's working directory.
322
+ *
323
+ * The counterpart of `Shell.withCwd`, and the reason relative paths mean the
324
+ * same thing to both: a shared transport stays rooted at the namespace root, so
325
+ * resolution happens here, per mount, rather than inside a VFS whose `chdir` is
326
+ * global state two mounts would fight over.
327
+ */
328
+ const withCwd = (fs, cwd) => {
329
+ const at = (path) => posix.resolve(cwd, path);
330
+ return {
331
+ readFile: (path) => fs.readFile(at(path)),
332
+ readFileBuffer: (path) => fs.readFileBuffer(at(path)),
333
+ writeFile: (path, content) => fs.writeFile(at(path), content),
334
+ stat: (path) => fs.stat(at(path)),
335
+ readdir: (path) => fs.readdir(at(path)),
336
+ exists: (path) => fs.exists(at(path)),
337
+ mkdir: (path, options) => fs.mkdir(at(path), options),
338
+ rm: (path, options) => fs.rm(at(path), options),
339
+ realpath: (path) => fs.realpath(at(path)),
340
+ scanLines: (path, options) => fs.scanLines(at(path), options),
341
+ ...fs.lstat === void 0 ? {} : { lstat: (path) => fs.lstat(at(path)) }
342
+ };
343
+ };
344
+ //#endregion
345
+ export { fromProvider as a, validateRmOptions as c, filesystem_exports as i, withCwd as l, OperationUnsupportedError as n, isNotFoundError as o, Service as r, realpathScripts as s, FileSystemError as t, scan_exports as u };
346
+
347
+ //# sourceMappingURL=filesystem-BFCKzgND.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"filesystem-BFCKzgND.mjs","names":["validateScan"],"sources":["../../src/sandbox/scan.ts","../../src/sandbox/filesystem.ts"],"sourcesContent":["/**\n * Bounded line reads: one pass over a file that returns a window of its lines\n * without ever holding more than that window.\n *\n * Lines are the file split on `\\n`, where a trailing newline ends the last line\n * rather than starting an empty one: `\"\"` has 0 lines, `\"a\"` and `\"a\\n\"` have 1,\n * `\"a\\n\\n\"` has 2. A UTF-8 byte-order mark at the start of the file is not part\n * of the first line. Line lengths are in bytes.\n *\n * Two implementations share these rules, and a backend uses whichever fits:\n * {@link LineScanner} over a byte stream, or {@link script} run inside the\n * sandbox so only the window crosses the network.\n */\n\nexport interface LineScanOptions {\n\t/** First selected line, 0-based. */\n\treadonly startLine: number;\n\t/** End of the selection, exclusive; absent selects to the end of the file. */\n\treadonly endLine?: number;\n\t/** Most UTF-8 bytes of selected text to return; selection stops at the last whole line that fits. */\n\treadonly maxBytes: number;\n}\n\nexport interface LineScan {\n\t/**\n\t * The selected whole lines that fit `maxBytes`, joined with `\\n`. Invalid\n\t * UTF-8 becomes U+FFFD; how many per bad sequence depends on the decoder of\n\t * the backend's transport.\n\t */\n\treadonly text: string;\n\t/** Lines in {@link text}. */\n\treadonly lines: number;\n\t/** Lines in the whole file. */\n\treadonly totalLines: number;\n\t/** Bytes in the whole file, byte-order mark included. */\n\treadonly totalBytes: number;\n\t/**\n\t * Bytes of the first selected line, 0 when nothing is selected. Larger than\n\t * `maxBytes` exactly when that line alone does not fit, and `text` is empty.\n\t */\n\treadonly firstLineBytes: number;\n}\n\n/** A defect, not a file error: callers derive these from already-validated input. */\nexport const validate = (options: LineScanOptions): void => {\n\tconst { startLine, endLine, maxBytes } = options;\n\tif (!Number.isSafeInteger(startLine) || startLine < 0) throw new RangeError(`Invalid startLine: ${startLine}`);\n\tif (endLine !== undefined && (!Number.isSafeInteger(endLine) || endLine <= startLine))\n\t\tthrow new RangeError(`Invalid endLine: ${endLine}`);\n\tif (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) throw new RangeError(`Invalid maxBytes: ${maxBytes}`);\n};\n\nconst NEWLINE = 0x0a;\nconst BOM = [0xef, 0xbb, 0xbf] as const;\n\n/**\n * Computes a {@link LineScan} from a file's bytes fed in order, in memory\n * bounded by `maxBytes`. Feed at most the file size observed when the read\n * started, so a file that keeps growing cannot keep the scan going.\n */\nexport class LineScanner {\n\tprivate readonly start: number;\n\tprivate readonly end: number;\n\tprivate readonly maxBytes: number;\n\t// Only a mark at the very start of the file is dropped, and that happens on\n\t// the bytes; one starting a later line is text.\n\tprivate readonly decoder = new TextDecoder(\"utf-8\", { ignoreBOM: true });\n\n\t/** The first bytes, held until it is known whether they are a byte-order mark. */\n\tprivate head: Array<number> | undefined = [];\n\tprivate totalBytes = 0;\n\tprivate line = 0;\n\tprivate lineLength = 0;\n\tprivate lineOpen = false;\n\t/** The current line's bytes, kept only while it is selected and could still fit. */\n\tprivate pieces: Array<Uint8Array> = [];\n\tprivate selected: Array<Uint8Array> = [];\n\tprivate selectedBytes = 0;\n\tprivate firstLineBytes = 0;\n\tprivate full = false;\n\n\tconstructor(options: LineScanOptions) {\n\t\tvalidate(options);\n\t\tthis.start = options.startLine;\n\t\tthis.end = options.endLine ?? Number.POSITIVE_INFINITY;\n\t\tthis.maxBytes = options.maxBytes;\n\t}\n\n\tpush(chunk: Uint8Array): void {\n\t\tthis.totalBytes += chunk.length;\n\t\tif (this.head !== undefined) {\n\t\t\tconst take = Math.min(BOM.length - this.head.length, chunk.length);\n\t\t\tthis.head.push(...chunk.subarray(0, take));\n\t\t\tif (this.head.length < BOM.length) return;\n\t\t\tthis.releaseHead();\n\t\t\tchunk = chunk.subarray(take);\n\t\t}\n\t\tthis.scan(chunk);\n\t}\n\n\tfinish(): LineScan {\n\t\tif (this.head !== undefined) this.releaseHead();\n\t\tif (this.lineOpen) this.endLine();\n\t\tconst text = this.selected.map((line) => this.decoder.decode(line)).join(\"\\n\");\n\t\treturn {\n\t\t\ttext,\n\t\t\tlines: this.selected.length,\n\t\t\ttotalLines: this.line,\n\t\t\ttotalBytes: this.totalBytes,\n\t\t\tfirstLineBytes: this.firstLineBytes,\n\t\t};\n\t}\n\n\tprivate releaseHead(): void {\n\t\tconst head = Uint8Array.from(this.head ?? []);\n\t\tthis.head = undefined;\n\t\tconst bom = head.length === BOM.length && BOM.every((byte, index) => head[index] === byte);\n\t\tif (!bom) this.scan(head);\n\t}\n\n\tprivate scan(chunk: Uint8Array): void {\n\t\tlet from = 0;\n\t\twhile (from < chunk.length) {\n\t\t\tconst newline = chunk.indexOf(NEWLINE, from);\n\t\t\tconst to = newline === -1 ? chunk.length : newline;\n\t\t\tthis.append(chunk.subarray(from, to));\n\t\t\tif (newline === -1) return;\n\t\t\tthis.endLine();\n\t\t\tfrom = newline + 1;\n\t\t}\n\t}\n\n\tprivate isSelected(): boolean {\n\t\treturn !this.full && this.line >= this.start && this.line < this.end;\n\t}\n\n\tprivate append(bytes: Uint8Array): void {\n\t\tif (bytes.length === 0) {\n\t\t\tthis.lineOpen = true;\n\t\t\treturn;\n\t\t}\n\t\tthis.lineOpen = true;\n\t\t// Past `maxBytes` the line cannot fit, so its bytes are only counted. Copied,\n\t\t// not sliced: a Node `Buffer` slice is a view the reader may overwrite.\n\t\tif (this.isSelected() && this.lineLength + bytes.length <= this.maxBytes) this.pieces.push(new Uint8Array(bytes));\n\t\tthis.lineLength += bytes.length;\n\t}\n\n\tprivate endLine(): void {\n\t\tif (this.isSelected()) {\n\t\t\tconst first = this.selected.length === 0;\n\t\t\tif (first) this.firstLineBytes = this.lineLength;\n\t\t\tconst added = first ? this.lineLength : this.lineLength + 1;\n\t\t\tif (this.selectedBytes + added > this.maxBytes) this.full = true;\n\t\t\telse {\n\t\t\t\tthis.selected.push(concat(this.pieces, this.lineLength));\n\t\t\t\tthis.selectedBytes += added;\n\t\t\t}\n\t\t}\n\t\tthis.pieces = [];\n\t\tthis.lineLength = 0;\n\t\tthis.lineOpen = false;\n\t\tthis.line++;\n\t}\n}\n\nconst concat = (pieces: ReadonlyArray<Uint8Array>, length: number): Uint8Array => {\n\tif (pieces.length === 1) return pieces[0]!;\n\tconst out = new Uint8Array(length);\n\tlet offset = 0;\n\tfor (const piece of pieces) {\n\t\tout.set(piece, offset);\n\t\toffset += piece.length;\n\t}\n\treturn out;\n};\n\n/**\n * {@link LineScanner} as a POSIX shell script, for backends that only expose a\n * process API. Run as `sh -c <script> _ <path> <startLine> <endLine|-1> <maxBytes>`.\n * The whole file is read inside the sandbox; only the window is printed, after a\n * header line `<lines> <totalLines> <totalBytes> <firstLineBytes>` and before a\n * closing `|` — see {@link parse}.\n * Exits 2 when the path does not exist.\n */\nexport const script = [\n\t'[ -e \"$1\" ] || exit 2',\n\t// Arithmetic expansion drops the padding some `wc` builds print.\n\t'size=$(($(wc -c < \"$1\"))) || exit 1',\n\t// `C` makes awk's `length` count bytes; `head -c` bounds a file that is still growing.\n\t'head -c \"$size\" -- \"$1\" | LC_ALL=C awk -v s=\"$2\" -v e=\"$3\" -v m=\"$4\" -v size=\"$size\" \\'',\n\t// A file that is only a byte-order mark has no lines; anything after one keeps its own.\n\t'NR == 1 && $0 == \"\\\\357\\\\273\\\\277\" && size == 3 { exit }',\n\t'NR == 1 && substr($0, 1, 3) == \"\\\\357\\\\273\\\\277\" { $0 = substr($0, 4) }',\n\t\"{ total = NR }\",\n\t\"NR > s && (e < 0 || NR <= e) && !full {\",\n\t\" len = length($0)\",\n\t\" added = lines == 0 ? len : len + 1\",\n\t\" if (lines == 0 && !seen) { seen = 1; first = len }\",\n\t\" if (bytes + added > m) { full = 1; next }\",\n\t' out = lines == 0 ? $0 : out \"\\\\n\" $0',\n\t\" bytes += added; lines++\",\n\t\"}\",\n\t// The trailing `|` survives a transport that trims trailing whitespace off stdout.\n\t// `%.0f`, not `%d`: some mawk builds clamp `%d` to a 32-bit integer.\n\t'END { printf \"%.0f %.0f %.0f %.0f\\\\n%s|\", lines, total, size, first, out }',\n\t\"'\",\n].join(\"\\n\");\n\n/** Arguments for {@link script} after the path. */\nexport const scriptArgs = (options: LineScanOptions): Array<string> => {\n\tvalidate(options);\n\treturn [String(options.startLine), String(options.endLine ?? -1), String(options.maxBytes)];\n};\n\n/** Read {@link script}'s output. */\nexport const parse = (stdout: string): LineScan => {\n\tconst body = stdout.trimEnd();\n\tconst newline = body.indexOf(\"\\n\");\n\tconst header = (newline === -1 ? \"\" : body.slice(0, newline)).trim().split(/\\s+/).map(Number);\n\tconst [lines, totalLines, totalBytes, firstLineBytes] = header;\n\tif (!body.endsWith(\"|\") || header.length !== 4 || header.some((value) => !Number.isSafeInteger(value)))\n\t\tthrow new Error(`Unexpected scanLines output: ${stdout.slice(0, 200)}`);\n\treturn {\n\t\ttext: body.slice(newline + 1, -1),\n\t\tlines: lines!,\n\t\ttotalLines: totalLines!,\n\t\ttotalBytes: totalBytes!,\n\t\tfirstLineBytes: firstLineBytes!,\n\t};\n};\n\nexport interface ShellRun {\n\treadonly exitCode: number;\n\treadonly stdout: string;\n\treadonly stderr?: string;\n}\n\n/**\n * `Provider.scanLines` for a backend that runs an argument vector and collects\n * its output: runs {@link script} in the sandbox and reads the result. A missing\n * path rejects with `ENOENT`, the shape `isNotFoundError` recognises.\n */\nexport const viaShell =\n\t(run: (argv: ReadonlyArray<string>) => Promise<ShellRun>) =>\n\t// oxlint-disable-next-line effecttsgo/async-function -- the Provider contract is Promise-based\n\tasync (path: string, options: LineScanOptions): Promise<LineScan> => {\n\t\tconst result = await run([\"sh\", \"-c\", script, \"_\", path, ...scriptArgs(options)]);\n\t\tif (result.exitCode === 2)\n\t\t\tthrow Object.assign(new Error(`ENOENT: no such file or directory, scanLines '${path}'`), { code: \"ENOENT\" });\n\t\tif (result.exitCode !== 0)\n\t\t\tthrow new Error(`scanLines failed (exit ${result.exitCode}): ${(result.stderr ?? result.stdout).trim()}`);\n\t\treturn parse(result.stdout);\n\t};\n","import { Context, Effect, Schema } from \"effect\";\nimport { posix } from \"../posix.ts\";\nimport { type LineScan, type LineScanOptions, validate as validateScan } from \"./scan.ts\";\n\nexport type { LineScan, LineScanOptions } from \"./scan.ts\";\n/** The shared line-scan rules: `LineScanner` for byte streams, `script` for shell-only backends. */\nexport * as Scan from \"./scan.ts\";\n\n/**\n * The runtime filesystem contract, independent of any backend.\n *\n * Two surfaces, deliberately:\n * - {@link Provider} is what a backend implements — plain promises that reject,\n * matching every SDK we wrap.\n * - {@link Interface} is what the harness consumes — Effect with a typed error\n * channel and tracing spans. {@link fromProvider} bridges the two exactly\n * once, so no consumer ever writes `Effect.tryPromise` against a filesystem.\n *\n * Implementations:\n * - Local:\n * implement it over a VFS (`./local`);\n * local filesystem use OS primitives; hence have broader filesytem capabilities.\n *\n * - Remote:\n * implement it over a provider (`./remote`).\n * remote filesytems depends on the interface provided by the remote provider; hence can have limited filesytem capabilities.\n *\n * `isFile`/`isDirectory` are required booleans; size, mtime, and isSymbolicLink are omitted when the\n * backend cannot report them — never fabricated.\n *\n * **Paths are POSIX, and the harness is Unix-only (for now!).** Every path uses `/`\n * separators on both the host and inside a sandbox — Windows is not supported,\n * so no translation layer exists. Consumers must use the shared Effect POSIX\n * path implementation, never the platform default, or a host running the harness would\n * impose its own flavour on a remote sandbox's paths. Relative paths resolve\n * against the backend's configured `cwd`.\n */\n\nexport class OperationUnsupportedError extends Schema.TaggedError<OperationUnsupportedError>()(\n\t\"OperationUnsupportedError\",\n\t{\n\t\toperation: Schema.String,\n\t\tmessage: Schema.String,\n\t},\n) {}\n\n/** A backend operation failed. `cause` carries the provider's own rejection. */\nexport class FileSystemError extends Schema.TaggedError<FileSystemError>()(\"SandboxFileSystemError\", {\n\tmethod: Schema.String,\n\tpath: Schema.String,\n\tcause: Schema.optional(Schema.Defect()),\n}) {}\n\nexport interface FileStat {\n\treadonly isFile: boolean;\n\treadonly isDirectory: boolean;\n\treadonly isSymbolicLink?: boolean;\n\treadonly size?: number;\n\treadonly mtime?: Date;\n}\n\nexport interface RmOptions {\n\treadonly recursive?: boolean;\n\treadonly force?: boolean;\n}\n\n/** Whether a provider failure means the path itself is definitively absent. */\nexport const isNotFoundError = (cause: unknown) => {\n\tconst code = (cause as NodeJS.ErrnoException | undefined)?.code;\n\treturn code === \"ENOENT\" || code === \"ENOTDIR\";\n};\n\n/**\n * Shell forms of `realpath` for backends that only expose a process API. Run as\n * `sh -c <script> _ <path>`, trying each in turn. `realpath -e` (coreutils)\n * resolves every component, a symlinked file included, and fails on a missing\n * path. Where it is absent, `pwd -P` is the portable primitive: directories\n * resolve directly, anything else resolves its parent and keeps the final name\n * as given — so a symlinked *file* stays unresolved there.\n */\nexport const realpathScripts = [\n\t'realpath -e -- \"$1\"',\n\t'cd -- \"$1\" && pwd -P',\n\t'cd -- \"$(dirname -- \"$1\")\" && printf \\'%s/%s\\' \"$(pwd -P)\" \"$(basename -- \"$1\")\"',\n] as const;\n\n/**\n * The backend-facing contract. Backends author plain promises and let them\n * reject; {@link fromProvider} turns rejections into typed failures.\n */\nexport interface Provider {\n\treadonly readFile: (path: string) => Promise<string>;\n\treadonly readFileBuffer: (path: string) => Promise<Uint8Array>;\n\t/**\n\t * Write the file. Parents may be missing — do not create them here;\n\t * {@link fromProvider} owns that guarantee for every backend.\n\t */\n\treadonly writeFile: (path: string, content: string | Uint8Array) => Promise<void>;\n\treadonly stat: (path: string) => Promise<FileStat>;\n\treadonly readdir: (path: string) => Promise<string[]>;\n\treadonly exists: (path: string) => Promise<boolean>;\n\treadonly mkdir: (path: string, options?: { recursive?: boolean }) => Promise<void>;\n\treadonly rm: (path: string, options?: RmOptions) => Promise<void>;\n\t/** Canonical absolute path with symlinks resolved; rejects when the path does not exist. */\n\treadonly realpath: (path: string) => Promise<string>;\n\t/**\n\t * A window of the file's lines, by the rules in `Scan`. Bounded: never\n\t * returns, or holds, more than the window. A remote backend runs the scan\n\t * inside the sandbox (`Scan.script`) so only the window crosses the network.\n\t */\n\treadonly scanLines: (path: string, options: LineScanOptions) => Promise<LineScan>;\n\t/**\n\t * Metadata for the directory entry itself rather than a symlink's target.\n\t * Optional: a backend whose `stat` has mixed symlink semantics implements it\n\t * so symlink identity is asked for explicitly, never inferred.\n\t */\n\treadonly lstat?: (path: string) => Promise<FileStat>;\n}\n\n/**\n * The consumer-facing contract. `exists` distinguishes \"absent\" from \"could not\n * tell\": a backend failure is a typed failure, not `false`, so a caller acting\n * on absence never acts on a network blip. Use `SandboxFs.existsOrFalse` where\n * a best-effort answer really is wanted.\n */\nexport interface Interface {\n\treadonly readFile: (path: string) => Effect.Effect<string, FileSystemError>;\n\treadonly readFileBuffer: (path: string) => Effect.Effect<Uint8Array, FileSystemError>;\n\t/** Creates missing parent directories, on every backend. */\n\treadonly writeFile: (path: string, content: string | Uint8Array) => Effect.Effect<void, FileSystemError>;\n\treadonly stat: (path: string) => Effect.Effect<FileStat, FileSystemError>;\n\treadonly readdir: (path: string) => Effect.Effect<string[], FileSystemError>;\n\treadonly exists: (path: string) => Effect.Effect<boolean, FileSystemError>;\n\treadonly mkdir: (path: string, options?: { recursive?: boolean }) => Effect.Effect<void, FileSystemError>;\n\treadonly rm: (path: string, options?: RmOptions) => Effect.Effect<void, FileSystemError | OperationUnsupportedError>;\n\t/** Canonical absolute path with symlinks resolved; fails when the path does not exist. */\n\treadonly realpath: (path: string) => Effect.Effect<string, FileSystemError>;\n\t/** A bounded window of the file's lines; see `Scan`. Invalid options are a defect. */\n\treadonly scanLines: (path: string, options: LineScanOptions) => Effect.Effect<LineScan, FileSystemError>;\n\t// `lstat` is present only when the backend supports it; check before calling.\n\treadonly lstat?: (path: string) => Effect.Effect<FileStat, FileSystemError>;\n}\n\n/** The runtime filesystem service — the live {@link Interface} for the active sandbox. */\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/plugin/sandbox/filesystem/Service\") {}\n\n/**\n * Reject `rm` options a provider does not implement, before any mutation. Only\n * `recursive` and `force` are part of the contract; anything else is refused\n * loudly rather than silently ignored.\n */\nexport const validateRmOptions = (\n\toptions: RmOptions | undefined,\n\toperation = \"rm\",\n): Effect.Effect<void, OperationUnsupportedError> =>\n\tEffect.suspend(() => {\n\t\tfor (const option of Object.keys((options ?? {}) as Record<string, unknown>)) {\n\t\t\tif (option === \"recursive\" || option === \"force\") continue;\n\t\t\treturn Effect.fail(new OperationUnsupportedError({ operation, message: `Unsupported rm option: ${option}` }));\n\t\t}\n\t\treturn Effect.void;\n\t});\n\n/**\n * Lift a {@link Provider} into the runtime {@link Interface}: one place that\n * converts rejections into {@link FileSystemError}, validates `rm` options,\n * creates missing parents on write, and names a tracing span per operation.\n */\nexport const fromProvider = (provider: Provider): Interface => {\n\tconst attempt = <A>(method: string, path: string, run: () => Promise<A>) =>\n\t\tEffect.tryPromise({ try: run, catch: (cause) => new FileSystemError({ method, path, cause }) });\n\n\t// The parent-creation guarantee, installed once for every backend instead of\n\t// re-implemented per provider: anything that reaches `Interface` reaches it\n\t// through here, so a backend cannot forget it.\n\t//\n\t// Lazy by design — try the write first, so the happy path stays a single call\n\t// and no remote backend pays a round-trip per write. A failure is usually a\n\t// missing parent, so create it and retry once. The mkdir's own error is\n\t// dropped on purpose: when the write failed for some other reason (EACCES,\n\t// EROFS, a dropped connection), the retry reproduces it, and *that* is the\n\t// failure the caller must see rather than a misleading mkdir error standing\n\t// in for it.\n\tconst writeCreatingParents = (path: string, content: string | Uint8Array) => {\n\t\tconst write = attempt(\"writeFile\", path, () => provider.writeFile(path, content));\n\t\tconst parent = posix.dirname(path);\n\t\treturn write.pipe(\n\t\t\tEffect.catch(() =>\n\t\t\t\tattempt(\"mkdir\", parent, () => provider.mkdir(parent, { recursive: true })).pipe(\n\t\t\t\t\tEffect.ignore,\n\t\t\t\t\tEffect.andThen(write),\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\t};\n\n\treturn {\n\t\treadFile: Effect.fn(\"SandboxFileSystem.readFile\")((path: string) =>\n\t\t\tattempt(\"readFile\", path, () => provider.readFile(path)),\n\t\t),\n\t\treadFileBuffer: Effect.fn(\"SandboxFileSystem.readFileBuffer\")((path: string) =>\n\t\t\tattempt(\"readFileBuffer\", path, () => provider.readFileBuffer(path)),\n\t\t),\n\t\twriteFile: Effect.fn(\"SandboxFileSystem.writeFile\")(writeCreatingParents),\n\t\tstat: Effect.fn(\"SandboxFileSystem.stat\")((path: string) => attempt(\"stat\", path, () => provider.stat(path))),\n\t\t// carried through only when the backend actually implements it\n\t\t...(provider.lstat === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tlstat: Effect.fn(\"SandboxFileSystem.lstat\")((path: string) =>\n\t\t\t\t\t\tattempt(\"lstat\", path, () => provider.lstat!(path)),\n\t\t\t\t\t),\n\t\t\t\t}),\n\t\treaddir: Effect.fn(\"SandboxFileSystem.readdir\")((path: string) =>\n\t\t\tattempt(\"readdir\", path, () => provider.readdir(path)),\n\t\t),\n\t\t// A backend that cannot answer fails; it does not report \"absent\". A\n\t\t// caller acting on absence — deleting a record, say — must not be told\n\t\t// the path is gone because a token expired or a request timed out.\n\t\texists: Effect.fn(\"SandboxFileSystem.exists\")((path: string) =>\n\t\t\tattempt(\"exists\", path, () => provider.exists(path)),\n\t\t),\n\t\tmkdir: Effect.fn(\"SandboxFileSystem.mkdir\")((path: string, options?: { recursive?: boolean }) =>\n\t\t\tattempt(\"mkdir\", path, () => provider.mkdir(path, options)),\n\t\t),\n\t\trm: Effect.fn(\"SandboxFileSystem.rm\")((path: string, options?: RmOptions) =>\n\t\t\tvalidateRmOptions(options).pipe(Effect.andThen(attempt(\"rm\", path, () => provider.rm(path, options)))),\n\t\t),\n\t\trealpath: Effect.fn(\"SandboxFileSystem.realpath\")((path: string) =>\n\t\t\tattempt(\"realpath\", path, () => provider.realpath(path)),\n\t\t),\n\t\tscanLines: Effect.fn(\"SandboxFileSystem.scanLines\")((path: string, options: LineScanOptions) =>\n\t\t\tEffect.sync(() => validateScan(options)).pipe(\n\t\t\t\tEffect.andThen(attempt(\"scanLines\", path, () => provider.scanLines(path, options))),\n\t\t\t),\n\t\t),\n\t};\n};\n\n/**\n * Bind a cwd-neutral filesystem to one mount's working directory.\n *\n * The counterpart of `Shell.withCwd`, and the reason relative paths mean the\n * same thing to both: a shared transport stays rooted at the namespace root, so\n * resolution happens here, per mount, rather than inside a VFS whose `chdir` is\n * global state two mounts would fight over.\n */\nexport const withCwd = (fs: Interface, cwd: string): Interface => {\n\tconst at = (path: string) => posix.resolve(cwd, path);\n\treturn {\n\t\treadFile: (path) => fs.readFile(at(path)),\n\t\treadFileBuffer: (path) => fs.readFileBuffer(at(path)),\n\t\twriteFile: (path, content) => fs.writeFile(at(path), content),\n\t\tstat: (path) => fs.stat(at(path)),\n\t\treaddir: (path) => fs.readdir(at(path)),\n\t\texists: (path) => fs.exists(at(path)),\n\t\tmkdir: (path, options) => fs.mkdir(at(path), options),\n\t\trm: (path, options) => fs.rm(at(path), options),\n\t\trealpath: (path) => fs.realpath(at(path)),\n\t\tscanLines: (path, options) => fs.scanLines(at(path), options),\n\t\t// carried through only when the backend implements it, so a caller can\n\t\t// still detect absence by checking the property\n\t\t...(fs.lstat === undefined ? {} : { lstat: (path: string) => fs.lstat!(at(path)) }),\n\t};\n};\n\nexport * as SandboxFileSystem from \"./filesystem.ts\";\n"],"mappings":";;;;;;;;;;;;;AA4CA,MAAa,YAAY,YAAmC;CAC3D,MAAM,EAAE,WAAW,SAAS,aAAa;CACzC,IAAI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G,MAAO,GAAG,IAAI,CAAC,EAAE;CAClF;AACD"}
@@ -1,6 +1,106 @@
1
1
  import { Context, Effect, Schema } from "effect";
2
+ declare namespace scan_d_exports {
3
+ export { LineScan, LineScanOptions, LineScanner, ShellRun, parse, script, scriptArgs, validate, viaShell };
4
+ }
5
+ /**
6
+ * Bounded line reads: one pass over a file that returns a window of its lines
7
+ * without ever holding more than that window.
8
+ *
9
+ * Lines are the file split on `\n`, where a trailing newline ends the last line
10
+ * rather than starting an empty one: `""` has 0 lines, `"a"` and `"a\n"` have 1,
11
+ * `"a\n\n"` has 2. A UTF-8 byte-order mark at the start of the file is not part
12
+ * of the first line. Line lengths are in bytes.
13
+ *
14
+ * Two implementations share these rules, and a backend uses whichever fits:
15
+ * {@link LineScanner} over a byte stream, or {@link script} run inside the
16
+ * sandbox so only the window crosses the network.
17
+ */
18
+ interface LineScanOptions {
19
+ /** First selected line, 0-based. */
20
+ readonly startLine: number;
21
+ /** End of the selection, exclusive; absent selects to the end of the file. */
22
+ readonly endLine?: number;
23
+ /** Most UTF-8 bytes of selected text to return; selection stops at the last whole line that fits. */
24
+ readonly maxBytes: number;
25
+ }
26
+ interface LineScan {
27
+ /**
28
+ * The selected whole lines that fit `maxBytes`, joined with `\n`. Invalid
29
+ * UTF-8 becomes U+FFFD; how many per bad sequence depends on the decoder of
30
+ * the backend's transport.
31
+ */
32
+ readonly text: string;
33
+ /** Lines in {@link text}. */
34
+ readonly lines: number;
35
+ /** Lines in the whole file. */
36
+ readonly totalLines: number;
37
+ /** Bytes in the whole file, byte-order mark included. */
38
+ readonly totalBytes: number;
39
+ /**
40
+ * Bytes of the first selected line, 0 when nothing is selected. Larger than
41
+ * `maxBytes` exactly when that line alone does not fit, and `text` is empty.
42
+ */
43
+ readonly firstLineBytes: number;
44
+ }
45
+ /** A defect, not a file error: callers derive these from already-validated input. */
46
+ declare const validate: (options: LineScanOptions) => void;
47
+ /**
48
+ * Computes a {@link LineScan} from a file's bytes fed in order, in memory
49
+ * bounded by `maxBytes`. Feed at most the file size observed when the read
50
+ * started, so a file that keeps growing cannot keep the scan going.
51
+ */
52
+ declare class LineScanner {
53
+ private readonly start;
54
+ private readonly end;
55
+ private readonly maxBytes;
56
+ private readonly decoder;
57
+ /** The first bytes, held until it is known whether they are a byte-order mark. */
58
+ private head;
59
+ private totalBytes;
60
+ private line;
61
+ private lineLength;
62
+ private lineOpen;
63
+ /** The current line's bytes, kept only while it is selected and could still fit. */
64
+ private pieces;
65
+ private selected;
66
+ private selectedBytes;
67
+ private firstLineBytes;
68
+ private full;
69
+ constructor(options: LineScanOptions);
70
+ push(chunk: Uint8Array): void;
71
+ finish(): LineScan;
72
+ private releaseHead;
73
+ private scan;
74
+ private isSelected;
75
+ private append;
76
+ private endLine;
77
+ }
78
+ /**
79
+ * {@link LineScanner} as a POSIX shell script, for backends that only expose a
80
+ * process API. Run as `sh -c <script> _ <path> <startLine> <endLine|-1> <maxBytes>`.
81
+ * The whole file is read inside the sandbox; only the window is printed, after a
82
+ * header line `<lines> <totalLines> <totalBytes> <firstLineBytes>` and before a
83
+ * closing `|` — see {@link parse}.
84
+ * Exits 2 when the path does not exist.
85
+ */
86
+ declare const script: string;
87
+ /** Arguments for {@link script} after the path. */
88
+ declare const scriptArgs: (options: LineScanOptions) => Array<string>;
89
+ /** Read {@link script}'s output. */
90
+ declare const parse: (stdout: string) => LineScan;
91
+ interface ShellRun {
92
+ readonly exitCode: number;
93
+ readonly stdout: string;
94
+ readonly stderr?: string;
95
+ }
96
+ /**
97
+ * `Provider.scanLines` for a backend that runs an argument vector and collects
98
+ * its output: runs {@link script} in the sandbox and reads the result. A missing
99
+ * path rejects with `ENOENT`, the shape `isNotFoundError` recognises.
100
+ */
101
+ declare const viaShell: (run: (argv: ReadonlyArray<string>) => Promise<ShellRun>) => (path: string, options: LineScanOptions) => Promise<LineScan>;
2
102
  declare namespace filesystem_d_exports {
3
- export { FileStat, FileSystemError, Interface, OperationUnsupportedError, Provider, RmOptions, filesystem_d_exports as SandboxFileSystem, Service, fromProvider, isNotFoundError, realpathScripts, validateRmOptions, withCwd };
103
+ export { FileStat, FileSystemError, Interface, LineScan, LineScanOptions, OperationUnsupportedError, Provider, RmOptions, filesystem_d_exports as SandboxFileSystem, scan_d_exports as Scan, Service, fromProvider, isNotFoundError, realpathScripts, validateRmOptions, withCwd };
4
104
  }
5
105
  declare const OperationUnsupportedError_base: Schema.Class<OperationUnsupportedError, Schema.TaggedStruct<"OperationUnsupportedError", {
6
106
  readonly operation: Schema.String;
@@ -86,6 +186,12 @@ interface Provider {
86
186
  readonly rm: (path: string, options?: RmOptions) => Promise<void>;
87
187
  /** Canonical absolute path with symlinks resolved; rejects when the path does not exist. */
88
188
  readonly realpath: (path: string) => Promise<string>;
189
+ /**
190
+ * A window of the file's lines, by the rules in `Scan`. Bounded: never
191
+ * returns, or holds, more than the window. A remote backend runs the scan
192
+ * inside the sandbox (`Scan.script`) so only the window crosses the network.
193
+ */
194
+ readonly scanLines: (path: string, options: LineScanOptions) => Promise<LineScan>;
89
195
  /**
90
196
  * Metadata for the directory entry itself rather than a symlink's target.
91
197
  * Optional: a backend whose `stat` has mixed symlink semantics implements it
@@ -113,6 +219,8 @@ interface Interface {
113
219
  readonly rm: (path: string, options?: RmOptions) => Effect.Effect<void, FileSystemError | OperationUnsupportedError>;
114
220
  /** Canonical absolute path with symlinks resolved; fails when the path does not exist. */
115
221
  readonly realpath: (path: string) => Effect.Effect<string, FileSystemError>;
222
+ /** A bounded window of the file's lines; see `Scan`. Invalid options are a defect. */
223
+ readonly scanLines: (path: string, options: LineScanOptions) => Effect.Effect<LineScan, FileSystemError>;
116
224
  readonly lstat?: (path: string) => Effect.Effect<FileStat, FileSystemError>;
117
225
  }
118
226
  declare const Service_base: Context.ServiceClass<Service, "@codeworksh/plugin/sandbox/filesystem/Service", Interface>;
@@ -140,5 +248,5 @@ declare const fromProvider: (provider: Provider) => Interface;
140
248
  */
141
249
  declare const withCwd: (fs: Interface, cwd: string) => Interface;
142
250
  //#endregion
143
- export { Provider as a, filesystem_d_exports as c, realpathScripts as d, validateRmOptions as f, OperationUnsupportedError as i, fromProvider as l, FileSystemError as n, RmOptions as o, withCwd as p, Interface as r, Service as s, FileStat as t, isNotFoundError as u };
144
- //# sourceMappingURL=filesystem-Cv2gjOJa.d.mts.map
251
+ export { Provider as a, filesystem_d_exports as c, realpathScripts as d, validateRmOptions as f, scan_d_exports as g, LineScanOptions as h, OperationUnsupportedError as i, fromProvider as l, LineScan as m, FileSystemError as n, RmOptions as o, withCwd as p, Interface as r, Service as s, FileStat as t, isNotFoundError as u };
252
+ //# sourceMappingURL=filesystem-BYaEdL14.d.mts.map
package/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
1
  import { t as section_d_exports } from "./plugin/section.mjs";
2
2
  import { g as tool_d_exports } from "./tool-DuYBgiJf.mjs";
3
- import { t as plugin_d_exports } from "./plugin-Bc2vSo2k.mjs";
3
+ import { t as plugin_d_exports } from "./plugin-C5HDBWGL.mjs";
4
4
  export { plugin_d_exports as Plugin, section_d_exports as Section, tool_d_exports as Tool };
@@ -1,4 +1,4 @@
1
- import { c as filesystem_d_exports, n as FileSystemError, r as Interface$1, s as Service$1 } from "./filesystem-Cv2gjOJa.mjs";
1
+ import { c as filesystem_d_exports, n as FileSystemError, r as Interface$1, s as Service$1 } from "./filesystem-BYaEdL14.mjs";
2
2
  import { i as Shell$1 } from "./shell-CZ6Y4lNU.mjs";
3
3
  import { Context, Effect, Layer, Option, Schema } from "effect";
4
4
  declare namespace instance_d_exports {
@@ -528,4 +528,4 @@ declare const remote: (input: {
528
528
  }) => Identity;
529
529
  //#endregion
530
530
  export { SandboxRemovedError as $, RuntimeInput as A, SandboxCreateError as B, ModuleDefinition as C, toColumn as Ct, Registered as D, Provisioned as E, driver_d_exports as F, SandboxDriverRegistrationError as G, SandboxDriverLoadError as H, erase as I, SandboxNotFoundError as J, SandboxMountError as K, withSource as L, apiVersion as M, defineModule as N, Registration as O, driver as P, SandboxRegisterError as Q, Redactor as R, Module as S, mountable as St, Observed as T, SandboxDriverLoadPhase as U, SandboxDestroyError as V, SandboxDriverNotRegisteredError as W, SandboxReadError as X, SandboxProviderError as Y, SandboxRefreshError as Z, AbsolutePath as _, Usage as _t, Mutation as a, errors_d_exports as at, Definition as b, instance_d_exports as bt, host as c, providerErrorCause as ct, io_d_exports as d, ID as dt, SandboxStopError as et, mount as f, Info as ft, withMutation as g, Status as gt, virtual as h, PersistedError as ht, Layer$1 as i, SandboxWakeError as it, Source as j, RuntimeConfigBase as k, hostLayer as l, providerErrorIsNotFound as lt, resolveMountCwd as m, Ownership as mt, FileSystem as n, SandboxUnavailError as nt, Provides as o, makeRedactor as ot, remote as p, Kind as pt, SandboxMustBeStoppedError as q, Identity as r, SandboxUnsupportedError as rt, Shell as s, providerError as st, Current as t, SandboxTransitionConflictError as tt, identityLayer as u, sanitizeError as ut, ApiVersion as v, fromColumn as vt, Name as w, toField as wt, Driver as x, isMountable as xt, Capabilities as y, fromField as yt, SandboxBusyError as z };
531
- //# sourceMappingURL=io-DhT4Y0Lw.d.mts.map
531
+ //# sourceMappingURL=io-BarV4hvG.d.mts.map
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
2
  import { ID } from "./sandbox/instance.mjs";
3
3
  import { posix } from "./posix.mjs";
4
- import { Service as Service$1, isNotFoundError, withCwd } from "./sandbox/filesystem.mjs";
4
+ import { l as withCwd, o as isNotFoundError, r as Service$1 } from "./filesystem-BFCKzgND.mjs";
5
5
  import { Shell as Shell$1, withCwd as withCwd$1 } from "./sandbox/shell.mjs";
6
6
  import { Context, Deferred, Effect, Layer } from "effect";
7
7
  //#region src/sandbox/mutation.ts
@@ -179,4 +179,4 @@ const remote = (input) => ({
179
179
  //#endregion
180
180
  export { host as a, io_exports as c, resolveMountCwd as d, virtual as f, Shell as i, mount as l, FileSystem as n, hostLayer as o, withMutation as p, Mutation as r, identityLayer as s, Current as t, remote as u };
181
181
 
182
- //# sourceMappingURL=io-5PrgzDTe.mjs.map
182
+ //# sourceMappingURL=io-CFWrEV0O.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"io-5PrgzDTe.mjs","names":["SandboxFileSystem.Service","ShellTag","SandboxMutation.Service","EffectLayer","SandboxMutation.make","SandboxFileSystem.withCwd","shellWithCwd"],"sources":["../../src/sandbox/mutation.ts","../../src/sandbox/io.ts"],"sourcesContent":["import { Context, Deferred, Effect } from \"effect\";\nimport { posix } from \"../posix.ts\";\nimport { type FileSystemError, type Interface as FileSystem, isNotFoundError } from \"./filesystem.ts\";\nimport type { SandboxInstance } from \"./instance.ts\";\n\n/**\n * Serializes mutations of one file.\n *\n * Tool calls may run in parallel, and a file-mutating tool does read → modify →\n * write. Two of those on one file interleave and the first write is lost, so a\n * tool holds the file for its whole read-modify-write.\n *\n * A file is its sandbox instance plus its canonical path: two mounts of one\n * instance share files, and a symlinked spelling of a path is the same file.\n * Other files never wait. This orders the harness's own tools within this\n * process only; it is not a lock against `bash` or other processes.\n */\nexport interface Interface {\n\t/**\n\t * Run `effect` as the only mutation of `path` in flight. Calls queue in the\n\t * order their paths resolve, which for one spelling is the order they were made.\n\t */\n\treadonly withFile: <A, E, R>(\n\t\tpath: string,\n\t\teffect: Effect.Effect<A, E, R>,\n\t) => Effect.Effect<A, E | FileSystemError, R>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/plugin/sandbox/mutation/Service\") {}\n\ninterface Lock {\n\treadonly waiters: Array<Deferred.Deferred<void>>;\n}\n\n// Process-wide on purpose: every mount of one instance must meet in the same\n// queue, whichever layer built it. A key is present exactly while its file is held.\nconst locks = new Map<string, Lock>();\n\n/** Hand the file to the next waiter, or free it. Ownership moves directly, so no newcomer can barge in. */\nconst release = (key: string, lock: Lock): void => {\n\tconst next = lock.waiters.shift();\n\tif (next === undefined) locks.delete(key);\n\telse Deferred.doneUnsafe(next, Effect.void);\n};\n\n/** Take the file, waiting interruptibly; must run uninterruptibly so taking and releasing pair up. */\nconst acquire = (key: string, restore: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>) =>\n\tEffect.suspend(() => {\n\t\tconst lock = locks.get(key);\n\t\tif (lock === undefined) {\n\t\t\tlocks.set(key, { waiters: [] });\n\t\t\treturn Effect.void;\n\t\t}\n\t\tconst turn = Deferred.makeUnsafe<void>();\n\t\tlock.waiters.push(turn);\n\t\treturn restore(Deferred.await(turn)).pipe(\n\t\t\tEffect.onInterrupt(() =>\n\t\t\t\tEffect.sync(() => {\n\t\t\t\t\tconst index = lock.waiters.indexOf(turn);\n\t\t\t\t\t// Still queued: leave. Already handed the file: pass it on.\n\t\t\t\t\tif (index !== -1) lock.waiters.splice(index, 1);\n\t\t\t\t\telse release(key, lock);\n\t\t\t\t}),\n\t\t\t),\n\t\t);\n\t});\n\n/**\n * The canonical path. A file that does not exist yet takes its canonical\n * parent joined with its name, walking up as far as needed, so a write that\n * creates a file (and its directories) shares a key with later mutations of it.\n */\nconst canonical = (fs: FileSystem, path: string): Effect.Effect<string, FileSystemError> =>\n\tfs.realpath(path).pipe(\n\t\tEffect.catchIf(\n\t\t\t(error) => isNotFoundError(error.cause),\n\t\t\t(error) => {\n\t\t\t\tconst parent = posix.dirname(path);\n\t\t\t\tif (parent === path) return Effect.fail(error);\n\t\t\t\treturn Effect.map(canonical(fs, parent), (resolved) => posix.join(resolved, posix.basename(path)));\n\t\t\t},\n\t\t),\n\t);\n\nexport const make = (instance: SandboxInstance.ID, cwd: string, fs: FileSystem): Interface => ({\n\twithFile: (path, effect) =>\n\t\tEffect.flatMap(canonical(fs, posix.resolve(cwd, path)), (resolved) => {\n\t\t\tconst key = `${instance}\\0${resolved}`;\n\t\t\t// Held from the moment `acquire` returns: nothing can interrupt between\n\t\t\t// taking the file and installing its release.\n\t\t\treturn Effect.uninterruptibleMask((restore) =>\n\t\t\t\tEffect.andThen(\n\t\t\t\t\tacquire(key, restore),\n\t\t\t\t\trestore(effect).pipe(\n\t\t\t\t\t\tEffect.ensuring(\n\t\t\t\t\t\t\tEffect.sync(() => {\n\t\t\t\t\t\t\t\tconst lock = locks.get(key);\n\t\t\t\t\t\t\t\tif (lock !== undefined) release(key, lock);\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t);\n\t\t}),\n});\n\nexport * as SandboxMutation from \"./mutation.ts\";\n","import { Context, Effect, Layer as EffectLayer } from \"effect\";\nimport { posix } from \"../posix.ts\";\nimport type { SandboxDriver } from \"./driver.ts\";\nimport { SandboxFileSystem } from \"./filesystem.ts\";\nimport { SandboxInstance } from \"./instance.ts\";\nimport { SandboxMutation } from \"./mutation.ts\";\nimport { type ISandboxExe, Shell as ShellTag, withCwd as shellWithCwd } from \"./shell.ts\";\n\n/**\n * `SandboxIO` is a **mount**: a filesystem, a shell, and the identity and\n * working directory they act on.\n *\n * It is the whole vocabulary a consumer needs. Project, Git, Copy, Location, and\n * every tool ask for `SandboxIO.FileSystem`, `SandboxIO.Shell`, and\n * `SandboxIO.Current` — never for a driver, an address, or a provider SDK — so\n * a host directory, an in-memory VFS, and a remote microVM are interchangeable\n * behind one contract.\n *\n * The mount neither creates nor destroys infrastructure. `SandboxInstance` is\n * the durable namespace it acts on — a device, which exists whether or not\n * anything has it mounted — and `Sandbox.Controller` is the only path that\n * creates, stops, or destroys one.\n */\n\n/**\n * The filesystem tag. Re-exported here so consumers import one namespace —\n * Project, Git, Copy, and the runner ask for `SandboxIO.FileSystem`, never for\n * the module that happens to define it. Code *inside* `sandbox/` keeps importing\n * the tag directly, since `io.ts` is built on top of it.\n */\nexport const FileSystem = SandboxFileSystem.Service;\nexport type FileSystem = SandboxFileSystem.Service;\n\n/** The shell tag. Re-exported here so consumers import one namespace. */\nexport const Shell = ShellTag;\nexport type Shell = ShellTag;\n\n/** Per-file mutation ordering for this mount's instance. Re-exported here so consumers import one namespace. */\nexport const Mutation = SandboxMutation.Service;\nexport type Mutation = SandboxMutation.Service;\n\n/**\n * What a mount sees: immutable identity, plus the working directory resolved for\n * *this* mount.\n *\n * Nothing mutable belongs here. `status`, `usage`, and reference counts all\n * change while a mount is open, so a mount-time snapshot of them would be wrong\n * by construction — runtime code that needs live management state asks the\n * control plane. The driver's own resource locator is likewise absent: consumers\n * never parse a Vercel name or a Daytona id.\n */\nexport interface Identity {\n\treadonly id: SandboxInstance.ID;\n\treadonly driver: SandboxDriver.Name;\n\treadonly kind: SandboxInstance.Kind;\n\t/** Absolute, and always a path in *this* namespace. */\n\treadonly cwd: string;\n}\n\n/** Identity and working directory of the current mount. */\nexport class Current extends Context.Service<Current, Identity>()(\"@codeworksh/plugin/sandbox/io/Current\") {}\n\n/** Everything a mount provides. */\nexport type Provides = Current | SandboxFileSystem.Service | ShellTag | SandboxMutation.Service;\n\n/** A built mount. */\nexport type Layer<E = never, RIn = never> = EffectLayer.Layer<Provides, E, RIn>;\n\n/**\n * Resolve a mount's cwd without consulting ambient process state.\n *\n * The default is supplied by the namespace adapter:\n * provider metadata remotely, `/` for a virtual filesystem, and `process.cwd()` for the host adapter.\n * An explicit absolute cwd replaces it; a relative cwd is resolved inside it. The\n * result is therefore always the one concrete absolute path `Current` requires.\n *\n * A non-absolute default throws rather than failing typed. It is the one\n * defect-level guard in this module, and deliberately so:\n * Adapters reading a value from a provider call this inside their own error channel,\n * where the throw becomes their typed failure (see `EnvDaytona.mountCwd`).\n */\nexport const resolveMountCwd = (defaultCwd: string, cwd?: string): string => {\n\tif (!posix.isAbsolute(defaultCwd)) {\n\t\tthrow new TypeError(`Sandbox default cwd must be absolute: ${defaultCwd}`);\n\t}\n\t// `resolve`, not `normalize`: normalize keeps a trailing slash, and `cwd` is\n\t// persisted — `space.location` and its id hash would read\n\t// `/workspace/` and `/workspace` as two directories and keep a row for each.\n\t//\n\t// A provider-reported default (`getWorkDir()`) or a config value is free to\n\t// carry one, so it is stripped here rather than at every reader.\n\tif (cwd === undefined) return posix.resolve(defaultCwd);\n\treturn posix.isAbsolute(cwd) ? posix.resolve(cwd) : posix.resolve(defaultCwd, cwd);\n};\n\n/**\n * Complete a mount with its {@link Mutation} queue, derived from the mount's own\n * identity and filesystem. Every layer that provides a mount goes through here,\n * so mounts of one instance always meet in the same queue.\n */\nexport const withMutation = <E, R>(\n\tlayer: EffectLayer.Layer<Current | SandboxFileSystem.Service | ShellTag, E, R>,\n): EffectLayer.Layer<Provides, E, R> =>\n\tEffectLayer.provideMerge(\n\t\tEffectLayer.effect(\n\t\t\tMutation,\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst current = yield* Current;\n\t\t\t\treturn SandboxMutation.make(current.id, current.cwd, yield* SandboxFileSystem.Service);\n\t\t\t}),\n\t\t),\n\t\tlayer,\n\t);\n\n/**\n * Bind a cwd-neutral transport to one mount.\n *\n * The transport underneath is shared between\n * mounts and stays rooted at the namespace root, and everything directory-shaped\n * happens here, once per mount. Two mounts of one namespace at different working\n * directories therefore coexist without seeing or moving each other's.\n *\n * It consumes the same two tags it provides — the transport is supplied by the\n * layer this is composed over, not by itself.\n */\nexport const mount = (identity: Identity): EffectLayer.Layer<Provides, never, SandboxFileSystem.Service | ShellTag> =>\n\tEffectLayer.mergeAll(\n\t\tEffectLayer.succeed(Current, identity),\n\t\tEffectLayer.effect(\n\t\t\tSandboxFileSystem.Service,\n\t\t\tEffect.map(SandboxFileSystem.Service, (fs) => SandboxFileSystem.withCwd(fs, identity.cwd)),\n\t\t),\n\t\tEffectLayer.effect(\n\t\t\tShellTag,\n\t\t\tEffect.map(ShellTag, (shell: ISandboxExe) => shellWithCwd(shell, identity.cwd)),\n\t\t),\n\t).pipe(withMutation);\n\n/**\n * Just the identity tag, with no filesystem or shell beneath it. For consumers\n * assembled from stubs — a test that runs `Project` over a fake filesystem still\n * needs to know which namespace it is in.\n */\nexport const identityLayer = (identity: Identity) => EffectLayer.succeed(Current, identity);\n\n/** The host identity alone. See {@link identityLayer}. */\nexport const hostLayer = (cwd: string) => identityLayer(host(cwd));\n\n/**\n * The host, rooted at `cwd`. Always `SandboxInstance.ID.local`: the working\n * directory selects where relative paths resolve, it does not make a second host\n * namespace — two mounts rooted at different directories still agree on absolute\n * paths.\n *\n * The host coordinate is explicit so a caller cannot accidentally substitute ambient process\n * state for the application or session directory it owns.\n */\nexport const host = (cwd: string): Identity => ({\n\tid: SandboxInstance.ID.local,\n\tdriver: \"local\" as SandboxDriver.Name,\n\tkind: \"local\",\n\tcwd: resolveMountCwd(cwd),\n});\n\n/**\n * A VFS-backed namespace. The id is minted per call unless one is named, because\n * building one of these builds a fresh VFS: N unnamed calls are N distinct\n * namespaces, none of which outlives the process. A file-backed store is the\n * exception — its file is the state, so whoever knows the file supplies the id\n * it was registered under.\n */\nexport const virtual = (input: {\n\treadonly driver: string;\n\treadonly id?: SandboxInstance.ID;\n\treadonly defaultCwd?: string;\n\treadonly cwd?: string;\n}): Identity => ({\n\tid: input.id ?? SandboxInstance.ID.create(),\n\tdriver: input.driver as SandboxDriver.Name,\n\tkind: \"virtual\",\n\tcwd: resolveMountCwd(input.defaultCwd ?? \"/\", input.cwd),\n});\n\n/**\n * A provider-hosted namespace. The id is always supplied: a remote resource's\n * durable identity is minted and recorded by whoever provisioned it, never\n * derived here from the provider's own locator.\n */\nexport const remote = (input: {\n\treadonly driver: string;\n\treadonly id: SandboxInstance.ID;\n\t/** Namespace-intrinsic default supplied or discovered by the driver. */\n\treadonly defaultCwd: string;\n\treadonly cwd?: string;\n}): Identity => ({\n\tid: input.id,\n\tdriver: input.driver as SandboxDriver.Name,\n\tkind: \"remote\",\n\tcwd: resolveMountCwd(input.defaultCwd, input.cwd),\n});\n\nexport * as SandboxIO from \"./io.ts\";\n"],"mappings":";;;;;;;AA4BA,IAAa,UAAb,cAA6B,QAAQ,QAA4B,CAAC,CAAC,6CAA6C,CAAC,CAAC,CAAC;AAQnH,MAAM,wBAAQ,IAAI,IAAkB;;AAGpC,MAAM,WAAW,KAAa,SAAqB;CAClD,MAAM,OAAO,KAAK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AAA,GAAuB;CACvB,QAAQ;CACR,MAAM;CACN,KAAK,gBAAgB,GAAG;AACzB;;;;;;;;AASA,MAAa,WAAW,WAKP;CAChB,IAAI,MAAM,MAAA,GAAyB,OAAO;CAC1C,QAAQ,MAAM;CACd,MAAM;CACN,KAAK,gBAAgB,MAAM,cAAc,KAAK,MAAM,GAAG;AACxD;;;;;;AAOA,MAAa,UAAU,WAMN;CAChB,IAAI,MAAM;CACV,QAAQ,MAAM;CACd,MAAM;CACN,KAAK,gBAAgB,MAAM,YAAY,MAAM,GAAG;AACjD"}
1
+ {"version":3,"file":"io-CFWrEV0O.mjs","names":["SandboxFileSystem.Service","ShellTag","SandboxMutation.Service","EffectLayer","SandboxMutation.make","SandboxFileSystem.withCwd","shellWithCwd"],"sources":["../../src/sandbox/mutation.ts","../../src/sandbox/io.ts"],"sourcesContent":["import { Context, Deferred, Effect } from \"effect\";\nimport { posix } from \"../posix.ts\";\nimport { type FileSystemError, type Interface as FileSystem, isNotFoundError } from \"./filesystem.ts\";\nimport type { SandboxInstance } from \"./instance.ts\";\n\n/**\n * Serializes mutations of one file.\n *\n * Tool calls may run in parallel, and a file-mutating tool does read → modify →\n * write. Two of those on one file interleave and the first write is lost, so a\n * tool holds the file for its whole read-modify-write.\n *\n * A file is its sandbox instance plus its canonical path: two mounts of one\n * instance share files, and a symlinked spelling of a path is the same file.\n * Other files never wait. This orders the harness's own tools within this\n * process only; it is not a lock against `bash` or other processes.\n */\nexport interface Interface {\n\t/**\n\t * Run `effect` as the only mutation of `path` in flight. Calls queue in the\n\t * order their paths resolve, which for one spelling is the order they were made.\n\t */\n\treadonly withFile: <A, E, R>(\n\t\tpath: string,\n\t\teffect: Effect.Effect<A, E, R>,\n\t) => Effect.Effect<A, E | FileSystemError, R>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/plugin/sandbox/mutation/Service\") {}\n\ninterface Lock {\n\treadonly waiters: Array<Deferred.Deferred<void>>;\n}\n\n// Process-wide on purpose: every mount of one instance must meet in the same\n// queue, whichever layer built it. A key is present exactly while its file is held.\nconst locks = new Map<string, Lock>();\n\n/** Hand the file to the next waiter, or free it. Ownership moves directly, so no newcomer can barge in. */\nconst release = (key: string, lock: Lock): void => {\n\tconst next = lock.waiters.shift();\n\tif (next === undefined) locks.delete(key);\n\telse Deferred.doneUnsafe(next, Effect.void);\n};\n\n/** Take the file, waiting interruptibly; must run uninterruptibly so taking and releasing pair up. */\nconst acquire = (key: string, restore: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>) =>\n\tEffect.suspend(() => {\n\t\tconst lock = locks.get(key);\n\t\tif (lock === undefined) {\n\t\t\tlocks.set(key, { waiters: [] });\n\t\t\treturn Effect.void;\n\t\t}\n\t\tconst turn = Deferred.makeUnsafe<void>();\n\t\tlock.waiters.push(turn);\n\t\treturn restore(Deferred.await(turn)).pipe(\n\t\t\tEffect.onInterrupt(() =>\n\t\t\t\tEffect.sync(() => {\n\t\t\t\t\tconst index = lock.waiters.indexOf(turn);\n\t\t\t\t\t// Still queued: leave. Already handed the file: pass it on.\n\t\t\t\t\tif (index !== -1) lock.waiters.splice(index, 1);\n\t\t\t\t\telse release(key, lock);\n\t\t\t\t}),\n\t\t\t),\n\t\t);\n\t});\n\n/**\n * The canonical path. A file that does not exist yet takes its canonical\n * parent joined with its name, walking up as far as needed, so a write that\n * creates a file (and its directories) shares a key with later mutations of it.\n */\nconst canonical = (fs: FileSystem, path: string): Effect.Effect<string, FileSystemError> =>\n\tfs.realpath(path).pipe(\n\t\tEffect.catchIf(\n\t\t\t(error) => isNotFoundError(error.cause),\n\t\t\t(error) => {\n\t\t\t\tconst parent = posix.dirname(path);\n\t\t\t\tif (parent === path) return Effect.fail(error);\n\t\t\t\treturn Effect.map(canonical(fs, parent), (resolved) => posix.join(resolved, posix.basename(path)));\n\t\t\t},\n\t\t),\n\t);\n\nexport const make = (instance: SandboxInstance.ID, cwd: string, fs: FileSystem): Interface => ({\n\twithFile: (path, effect) =>\n\t\tEffect.flatMap(canonical(fs, posix.resolve(cwd, path)), (resolved) => {\n\t\t\tconst key = `${instance}\\0${resolved}`;\n\t\t\t// Held from the moment `acquire` returns: nothing can interrupt between\n\t\t\t// taking the file and installing its release.\n\t\t\treturn Effect.uninterruptibleMask((restore) =>\n\t\t\t\tEffect.andThen(\n\t\t\t\t\tacquire(key, restore),\n\t\t\t\t\trestore(effect).pipe(\n\t\t\t\t\t\tEffect.ensuring(\n\t\t\t\t\t\t\tEffect.sync(() => {\n\t\t\t\t\t\t\t\tconst lock = locks.get(key);\n\t\t\t\t\t\t\t\tif (lock !== undefined) release(key, lock);\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t);\n\t\t}),\n});\n\nexport * as SandboxMutation from \"./mutation.ts\";\n","import { Context, Effect, Layer as EffectLayer } from \"effect\";\nimport { posix } from \"../posix.ts\";\nimport type { SandboxDriver } from \"./driver.ts\";\nimport { SandboxFileSystem } from \"./filesystem.ts\";\nimport { SandboxInstance } from \"./instance.ts\";\nimport { SandboxMutation } from \"./mutation.ts\";\nimport { type ISandboxExe, Shell as ShellTag, withCwd as shellWithCwd } from \"./shell.ts\";\n\n/**\n * `SandboxIO` is a **mount**: a filesystem, a shell, and the identity and\n * working directory they act on.\n *\n * It is the whole vocabulary a consumer needs. Project, Git, Copy, Location, and\n * every tool ask for `SandboxIO.FileSystem`, `SandboxIO.Shell`, and\n * `SandboxIO.Current` — never for a driver, an address, or a provider SDK — so\n * a host directory, an in-memory VFS, and a remote microVM are interchangeable\n * behind one contract.\n *\n * The mount neither creates nor destroys infrastructure. `SandboxInstance` is\n * the durable namespace it acts on — a device, which exists whether or not\n * anything has it mounted — and `Sandbox.Controller` is the only path that\n * creates, stops, or destroys one.\n */\n\n/**\n * The filesystem tag. Re-exported here so consumers import one namespace —\n * Project, Git, Copy, and the runner ask for `SandboxIO.FileSystem`, never for\n * the module that happens to define it. Code *inside* `sandbox/` keeps importing\n * the tag directly, since `io.ts` is built on top of it.\n */\nexport const FileSystem = SandboxFileSystem.Service;\nexport type FileSystem = SandboxFileSystem.Service;\n\n/** The shell tag. Re-exported here so consumers import one namespace. */\nexport const Shell = ShellTag;\nexport type Shell = ShellTag;\n\n/** Per-file mutation ordering for this mount's instance. Re-exported here so consumers import one namespace. */\nexport const Mutation = SandboxMutation.Service;\nexport type Mutation = SandboxMutation.Service;\n\n/**\n * What a mount sees: immutable identity, plus the working directory resolved for\n * *this* mount.\n *\n * Nothing mutable belongs here. `status`, `usage`, and reference counts all\n * change while a mount is open, so a mount-time snapshot of them would be wrong\n * by construction — runtime code that needs live management state asks the\n * control plane. The driver's own resource locator is likewise absent: consumers\n * never parse a Vercel name or a Daytona id.\n */\nexport interface Identity {\n\treadonly id: SandboxInstance.ID;\n\treadonly driver: SandboxDriver.Name;\n\treadonly kind: SandboxInstance.Kind;\n\t/** Absolute, and always a path in *this* namespace. */\n\treadonly cwd: string;\n}\n\n/** Identity and working directory of the current mount. */\nexport class Current extends Context.Service<Current, Identity>()(\"@codeworksh/plugin/sandbox/io/Current\") {}\n\n/** Everything a mount provides. */\nexport type Provides = Current | SandboxFileSystem.Service | ShellTag | SandboxMutation.Service;\n\n/** A built mount. */\nexport type Layer<E = never, RIn = never> = EffectLayer.Layer<Provides, E, RIn>;\n\n/**\n * Resolve a mount's cwd without consulting ambient process state.\n *\n * The default is supplied by the namespace adapter:\n * provider metadata remotely, `/` for a virtual filesystem, and `process.cwd()` for the host adapter.\n * An explicit absolute cwd replaces it; a relative cwd is resolved inside it. The\n * result is therefore always the one concrete absolute path `Current` requires.\n *\n * A non-absolute default throws rather than failing typed. It is the one\n * defect-level guard in this module, and deliberately so:\n * Adapters reading a value from a provider call this inside their own error channel,\n * where the throw becomes their typed failure (see `EnvDaytona.mountCwd`).\n */\nexport const resolveMountCwd = (defaultCwd: string, cwd?: string): string => {\n\tif (!posix.isAbsolute(defaultCwd)) {\n\t\tthrow new TypeError(`Sandbox default cwd must be absolute: ${defaultCwd}`);\n\t}\n\t// `resolve`, not `normalize`: normalize keeps a trailing slash, and `cwd` is\n\t// persisted — `space.location` and its id hash would read\n\t// `/workspace/` and `/workspace` as two directories and keep a row for each.\n\t//\n\t// A provider-reported default (`getWorkDir()`) or a config value is free to\n\t// carry one, so it is stripped here rather than at every reader.\n\tif (cwd === undefined) return posix.resolve(defaultCwd);\n\treturn posix.isAbsolute(cwd) ? posix.resolve(cwd) : posix.resolve(defaultCwd, cwd);\n};\n\n/**\n * Complete a mount with its {@link Mutation} queue, derived from the mount's own\n * identity and filesystem. Every layer that provides a mount goes through here,\n * so mounts of one instance always meet in the same queue.\n */\nexport const withMutation = <E, R>(\n\tlayer: EffectLayer.Layer<Current | SandboxFileSystem.Service | ShellTag, E, R>,\n): EffectLayer.Layer<Provides, E, R> =>\n\tEffectLayer.provideMerge(\n\t\tEffectLayer.effect(\n\t\t\tMutation,\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst current = yield* Current;\n\t\t\t\treturn SandboxMutation.make(current.id, current.cwd, yield* SandboxFileSystem.Service);\n\t\t\t}),\n\t\t),\n\t\tlayer,\n\t);\n\n/**\n * Bind a cwd-neutral transport to one mount.\n *\n * The transport underneath is shared between\n * mounts and stays rooted at the namespace root, and everything directory-shaped\n * happens here, once per mount. Two mounts of one namespace at different working\n * directories therefore coexist without seeing or moving each other's.\n *\n * It consumes the same two tags it provides — the transport is supplied by the\n * layer this is composed over, not by itself.\n */\nexport const mount = (identity: Identity): EffectLayer.Layer<Provides, never, SandboxFileSystem.Service | ShellTag> =>\n\tEffectLayer.mergeAll(\n\t\tEffectLayer.succeed(Current, identity),\n\t\tEffectLayer.effect(\n\t\t\tSandboxFileSystem.Service,\n\t\t\tEffect.map(SandboxFileSystem.Service, (fs) => SandboxFileSystem.withCwd(fs, identity.cwd)),\n\t\t),\n\t\tEffectLayer.effect(\n\t\t\tShellTag,\n\t\t\tEffect.map(ShellTag, (shell: ISandboxExe) => shellWithCwd(shell, identity.cwd)),\n\t\t),\n\t).pipe(withMutation);\n\n/**\n * Just the identity tag, with no filesystem or shell beneath it. For consumers\n * assembled from stubs — a test that runs `Project` over a fake filesystem still\n * needs to know which namespace it is in.\n */\nexport const identityLayer = (identity: Identity) => EffectLayer.succeed(Current, identity);\n\n/** The host identity alone. See {@link identityLayer}. */\nexport const hostLayer = (cwd: string) => identityLayer(host(cwd));\n\n/**\n * The host, rooted at `cwd`. Always `SandboxInstance.ID.local`: the working\n * directory selects where relative paths resolve, it does not make a second host\n * namespace — two mounts rooted at different directories still agree on absolute\n * paths.\n *\n * The host coordinate is explicit so a caller cannot accidentally substitute ambient process\n * state for the application or session directory it owns.\n */\nexport const host = (cwd: string): Identity => ({\n\tid: SandboxInstance.ID.local,\n\tdriver: \"local\" as SandboxDriver.Name,\n\tkind: \"local\",\n\tcwd: resolveMountCwd(cwd),\n});\n\n/**\n * A VFS-backed namespace. The id is minted per call unless one is named, because\n * building one of these builds a fresh VFS: N unnamed calls are N distinct\n * namespaces, none of which outlives the process. A file-backed store is the\n * exception — its file is the state, so whoever knows the file supplies the id\n * it was registered under.\n */\nexport const virtual = (input: {\n\treadonly driver: string;\n\treadonly id?: SandboxInstance.ID;\n\treadonly defaultCwd?: string;\n\treadonly cwd?: string;\n}): Identity => ({\n\tid: input.id ?? SandboxInstance.ID.create(),\n\tdriver: input.driver as SandboxDriver.Name,\n\tkind: \"virtual\",\n\tcwd: resolveMountCwd(input.defaultCwd ?? \"/\", input.cwd),\n});\n\n/**\n * A provider-hosted namespace. The id is always supplied: a remote resource's\n * durable identity is minted and recorded by whoever provisioned it, never\n * derived here from the provider's own locator.\n */\nexport const remote = (input: {\n\treadonly driver: string;\n\treadonly id: SandboxInstance.ID;\n\t/** Namespace-intrinsic default supplied or discovered by the driver. */\n\treadonly defaultCwd: string;\n\treadonly cwd?: string;\n}): Identity => ({\n\tid: input.id,\n\tdriver: input.driver as SandboxDriver.Name,\n\tkind: \"remote\",\n\tcw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AAO,IAAIA,UAAW,UAAuBK,UAAa,OAAO,SAAS,GAAG,CAAC,CAC/E,CACD,CAAC,CAAC,KAAK,YAAY;;;;;;AAOpB,MAAa,iBAAiB,aAAuBH,MAAY,QAAQ,SAAS,QAAQ;;AAG1F,MAAa,aAAa,QAAgB,cAAc,KAAK,GAAG,CAAC;;;;;;;;;;AAWjE,MAAa,QAAQ,SAA2B;CAC/C,IAAA,GAAuB;CACvB,QAAQ;CACR,MAAM;CACN,KAAK,gBAAgB,GAAG;AACzB;;;;;;;;AASA,MAAa,WAAW,WAKP;CAChB,IAAI,MAAM,MAAA,GAAyB,OAAO;CAC1C,QAAQ,MAAM;CACd,MAAM;CACN,KAAK,gBAAgB,MAAM,cAAc,KAAK,MAAM,GAAG;AACxD;;;;;;AAOA,MAAa,UAAU,WAMN;CAChB,IAAI,MAAM;CACV,QAAQ,MAAM;CACd,MAAM;CACN,KAAK,gBAAgB,MAAM,YAAY,MAAM,GAAG;AACjD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codeworksh/plugin",
3
- "version": "0.1.0-canary.18.1.g00a873ad",
3
+ "version": "0.1.0-canary.20.1.gf5454e1e",
4
4
  "description": "SDK for building CodeWork plugins — the plugin, tool, and sandbox contracts shared with @codeworksh/harness.",
5
5
  "keywords": [
6
6
  "agent",
@@ -168,7 +168,7 @@
168
168
  "uuidv7": "^1.2.1"
169
169
  },
170
170
  "peerDependencies": {
171
- "@codeworksh/aikit": "0.10.0-canary.18.1.g00a873ad",
171
+ "@codeworksh/aikit": "0.10.0-canary.20.1.gf5454e1e",
172
172
  "effect": "4.0.1"
173
173
  }
174
174
  }
@@ -1,7 +1,7 @@
1
1
  import { i as Definition, o as Payload, r as Data, s as PublishOptions } from "./event-6sTQ_4bq.mjs";
2
2
  import { n as SessionID } from "./ids-CHjmAdTc.mjs";
3
3
  import { o as Service, r as Info } from "./location-Q39els63.mjs";
4
- import { d as io_d_exports, o as Provides, r as Identity } from "./io-DhT4Y0Lw.mjs";
4
+ import { d as io_d_exports, o as Provides, r as Identity } from "./io-BarV4hvG.mjs";
5
5
  import { i as Info$1 } from "./settings-B6-grSTA.mjs";
6
6
  import { t as section_d_exports } from "./plugin/section.mjs";
7
7
  import { n as prompt_d_exports, t as PromptRegistry } from "./prompt-DWaA5ZXj.mjs";
@@ -138,4 +138,4 @@ declare namespace plugin_d_exports {
138
138
  }
139
139
  //#endregion
140
140
  export { define as a, PluginOptions as c, PluginSpec as d, Config as f, PluginRegistry as g, SharedPluginContext as h, PluginKind as i, PluginPatch as l, PromptResolver as m, Mount as n, domains as o, Events as p, Plugin as r, rank as s, plugin_d_exports as t, PluginRef as u };
141
- //# sourceMappingURL=plugin-Bc2vSo2k.d.mts.map
141
+ //# sourceMappingURL=plugin-C5HDBWGL.d.mts.map
package/plugin.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as section_d_exports } from "./plugin/section.mjs";
2
2
  import { n as prompt_d_exports } from "./prompt-DWaA5ZXj.mjs";
3
3
  import { p as tool_d_exports } from "./tool-BoVqkYvL.mjs";
4
- import { a as define, c as PluginOptions, d as PluginSpec, f as Config, g as PluginRegistry, h as SharedPluginContext, i as PluginKind, l as PluginPatch, m as PromptResolver, n as Mount, o as domains, p as Events, r as Plugin, s as rank, u as PluginRef } from "./plugin-Bc2vSo2k.mjs";
4
+ import { a as define, c as PluginOptions, d as PluginSpec, f as Config, g as PluginRegistry, h as SharedPluginContext, i as PluginKind, l as PluginPatch, m as PromptResolver, n as Mount, o as domains, p as Events, r as Plugin, s as rank, u as PluginRef } from "./plugin-C5HDBWGL.mjs";
5
5
  export { type Config, type Events, type Mount, type Plugin, type PluginKind, type PluginOptions, type PluginPatch, type PluginRef, type PluginRegistry, type PluginSpec, prompt_d_exports as Prompt, type PromptResolver, section_d_exports as Section, type SharedPluginContext, tool_d_exports as Tool, define, domains, rank };
@@ -1,2 +1,2 @@
1
- import { A as RuntimeInput, C as ModuleDefinition, D as Registered, E as Provisioned, F as driver_d_exports, I as erase, L as withSource, M as apiVersion, N as defineModule, O as Registration, P as driver, S as Module, T as Observed, _ as AbsolutePath, b as Definition, j as Source, k as RuntimeConfigBase, v as ApiVersion, w as Name, x as Driver, y as Capabilities } from "../io-DhT4Y0Lw.mjs";
1
+ import { A as RuntimeInput, C as ModuleDefinition, D as Registered, E as Provisioned, F as driver_d_exports, I as erase, L as withSource, M as apiVersion, N as defineModule, O as Registration, P as driver, S as Module, T as Observed, _ as AbsolutePath, b as Definition, j as Source, k as RuntimeConfigBase, v as ApiVersion, w as Name, x as Driver, y as Capabilities } from "../io-BarV4hvG.mjs";
2
2
  export { AbsolutePath, ApiVersion, Capabilities, Definition, Driver, Module, ModuleDefinition, Name, Observed, Provisioned, Registered, Registration, RuntimeConfigBase, RuntimeInput, driver_d_exports as SandboxDriver, Source, apiVersion, driver, erase, defineModule as module, withSource };
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "../rolldown-runtime-D7D4PA-g.mjs";
2
2
  import "./instance.mjs";
3
- import "../io-5PrgzDTe.mjs";
3
+ import "../io-CFWrEV0O.mjs";
4
4
  import { Schema } from "effect";
5
5
  //#region src/sandbox/driver.ts
6
6
  var driver_exports = /* @__PURE__ */ __exportAll({
@@ -1,2 +1,2 @@
1
- import { $ as SandboxRemovedError, B as SandboxCreateError, G as SandboxDriverRegistrationError, H as SandboxDriverLoadError, J as SandboxNotFoundError, K as SandboxMountError, Q as SandboxRegisterError, R as Redactor, U as SandboxDriverLoadPhase, V as SandboxDestroyError, W as SandboxDriverNotRegisteredError, X as SandboxReadError, Y as SandboxProviderError, Z as SandboxRefreshError, at as errors_d_exports, ct as providerErrorCause, et as SandboxStopError, it as SandboxWakeError, lt as providerErrorIsNotFound, nt as SandboxUnavailError, ot as makeRedactor, q as SandboxMustBeStoppedError, rt as SandboxUnsupportedError, st as providerError, tt as SandboxTransitionConflictError, ut as sanitizeError, z as SandboxBusyError } from "../io-DhT4Y0Lw.mjs";
1
+ import { $ as SandboxRemovedError, B as SandboxCreateError, G as SandboxDriverRegistrationError, H as SandboxDriverLoadError, J as SandboxNotFoundError, K as SandboxMountError, Q as SandboxRegisterError, R as Redactor, U as SandboxDriverLoadPhase, V as SandboxDestroyError, W as SandboxDriverNotRegisteredError, X as SandboxReadError, Y as SandboxProviderError, Z as SandboxRefreshError, at as errors_d_exports, ct as providerErrorCause, et as SandboxStopError, it as SandboxWakeError, lt as providerErrorIsNotFound, nt as SandboxUnavailError, ot as makeRedactor, q as SandboxMustBeStoppedError, rt as SandboxUnsupportedError, st as providerError, tt as SandboxTransitionConflictError, ut as sanitizeError, z as SandboxBusyError } from "../io-BarV4hvG.mjs";
2
2
  export { Redactor, SandboxBusyError, SandboxCreateError, SandboxDestroyError, SandboxDriverLoadError, SandboxDriverLoadPhase, SandboxDriverNotRegisteredError, SandboxDriverRegistrationError, errors_d_exports as SandboxError, SandboxMountError, SandboxMustBeStoppedError, SandboxNotFoundError, SandboxProviderError, SandboxReadError, SandboxRefreshError, SandboxRegisterError, SandboxRemovedError, SandboxStopError, SandboxTransitionConflictError, SandboxUnavailError, SandboxUnsupportedError, SandboxWakeError, makeRedactor, providerError, providerErrorCause, providerErrorIsNotFound, sanitizeError };
@@ -1,2 +1,2 @@
1
- import { a as Provider, c as filesystem_d_exports, d as realpathScripts, f as validateRmOptions, i as OperationUnsupportedError, l as fromProvider, n as FileSystemError, o as RmOptions, p as withCwd, r as Interface, s as Service, t as FileStat, u as isNotFoundError } from "../filesystem-Cv2gjOJa.mjs";
2
- export { FileStat, FileSystemError, Interface, OperationUnsupportedError, Provider, RmOptions, filesystem_d_exports as SandboxFileSystem, Service, fromProvider, isNotFoundError, realpathScripts, validateRmOptions, withCwd };
1
+ import { a as Provider, c as filesystem_d_exports, d as realpathScripts, f as validateRmOptions, g as scan_d_exports, h as LineScanOptions, i as OperationUnsupportedError, l as fromProvider, m as LineScan, n as FileSystemError, o as RmOptions, p as withCwd, r as Interface, s as Service, t as FileStat, u as isNotFoundError } from "../filesystem-BYaEdL14.mjs";
2
+ export { FileStat, FileSystemError, Interface, type LineScan, type LineScanOptions, OperationUnsupportedError, Provider, RmOptions, filesystem_d_exports as SandboxFileSystem, scan_d_exports as Scan, Service, fromProvider, isNotFoundError, realpathScripts, validateRmOptions, withCwd };
@@ -1,148 +1,2 @@
1
- import { t as __exportAll } from "../rolldown-runtime-D7D4PA-g.mjs";
2
- import { posix } from "../posix.mjs";
3
- import { Context, Effect, Schema } from "effect";
4
- //#region src/sandbox/filesystem.ts
5
- var filesystem_exports = /* @__PURE__ */ __exportAll({
6
- FileSystemError: () => FileSystemError,
7
- OperationUnsupportedError: () => OperationUnsupportedError,
8
- SandboxFileSystem: () => filesystem_exports,
9
- Service: () => Service,
10
- fromProvider: () => fromProvider,
11
- isNotFoundError: () => isNotFoundError,
12
- realpathScripts: () => realpathScripts,
13
- validateRmOptions: () => validateRmOptions,
14
- withCwd: () => withCwd
15
- });
16
- /**
17
- * The runtime filesystem contract, independent of any backend.
18
- *
19
- * Two surfaces, deliberately:
20
- * - {@link Provider} is what a backend implements — plain promises that reject,
21
- * matching every SDK we wrap.
22
- * - {@link Interface} is what the harness consumes — Effect with a typed error
23
- * channel and tracing spans. {@link fromProvider} bridges the two exactly
24
- * once, so no consumer ever writes `Effect.tryPromise` against a filesystem.
25
- *
26
- * Implementations:
27
- * - Local:
28
- * implement it over a VFS (`./local`);
29
- * local filesystem use OS primitives; hence have broader filesytem capabilities.
30
- *
31
- * - Remote:
32
- * implement it over a provider (`./remote`).
33
- * remote filesytems depends on the interface provided by the remote provider; hence can have limited filesytem capabilities.
34
- *
35
- * `isFile`/`isDirectory` are required booleans; size, mtime, and isSymbolicLink are omitted when the
36
- * backend cannot report them — never fabricated.
37
- *
38
- * **Paths are POSIX, and the harness is Unix-only (for now!).** Every path uses `/`
39
- * separators on both the host and inside a sandbox — Windows is not supported,
40
- * so no translation layer exists. Consumers must use the shared Effect POSIX
41
- * path implementation, never the platform default, or a host running the harness would
42
- * impose its own flavour on a remote sandbox's paths. Relative paths resolve
43
- * against the backend's configured `cwd`.
44
- */
45
- var OperationUnsupportedError = class extends Schema.TaggedError()("OperationUnsupportedError", {
46
- operation: Schema.String,
47
- message: Schema.String
48
- }) {};
49
- /** A backend operation failed. `cause` carries the provider's own rejection. */
50
- var FileSystemError = class extends Schema.TaggedError()("SandboxFileSystemError", {
51
- method: Schema.String,
52
- path: Schema.String,
53
- cause: Schema.optional(Schema.Defect())
54
- }) {};
55
- /** Whether a provider failure means the path itself is definitively absent. */
56
- const isNotFoundError = (cause) => {
57
- const code = cause?.code;
58
- return code === "ENOENT" || code === "ENOTDIR";
59
- };
60
- /**
61
- * Shell forms of `realpath` for backends that only expose a process API. Run as
62
- * `sh -c <script> _ <path>`, trying each in turn. `realpath -e` (coreutils)
63
- * resolves every component, a symlinked file included, and fails on a missing
64
- * path. Where it is absent, `pwd -P` is the portable primitive: directories
65
- * resolve directly, anything else resolves its parent and keeps the final name
66
- * as given — so a symlinked *file* stays unresolved there.
67
- */
68
- const realpathScripts = [
69
- "realpath -e -- \"$1\"",
70
- "cd -- \"$1\" && pwd -P",
71
- "cd -- \"$(dirname -- \"$1\")\" && printf '%s/%s' \"$(pwd -P)\" \"$(basename -- \"$1\")\""
72
- ];
73
- /** The runtime filesystem service — the live {@link Interface} for the active sandbox. */
74
- var Service = class extends Context.Service()("@codeworksh/plugin/sandbox/filesystem/Service") {};
75
- /**
76
- * Reject `rm` options a provider does not implement, before any mutation. Only
77
- * `recursive` and `force` are part of the contract; anything else is refused
78
- * loudly rather than silently ignored.
79
- */
80
- const validateRmOptions = (options, operation = "rm") => Effect.suspend(() => {
81
- for (const option of Object.keys(options ?? {})) {
82
- if (option === "recursive" || option === "force") continue;
83
- return Effect.fail(new OperationUnsupportedError({
84
- operation,
85
- message: `Unsupported rm option: ${option}`
86
- }));
87
- }
88
- return Effect.void;
89
- });
90
- /**
91
- * Lift a {@link Provider} into the runtime {@link Interface}: one place that
92
- * converts rejections into {@link FileSystemError}, validates `rm` options,
93
- * creates missing parents on write, and names a tracing span per operation.
94
- */
95
- const fromProvider = (provider) => {
96
- const attempt = (method, path, run) => Effect.tryPromise({
97
- try: run,
98
- catch: (cause) => new FileSystemError({
99
- method,
100
- path,
101
- cause
102
- })
103
- });
104
- const writeCreatingParents = (path, content) => {
105
- const write = attempt("writeFile", path, () => provider.writeFile(path, content));
106
- const parent = posix.dirname(path);
107
- return write.pipe(Effect.catch(() => attempt("mkdir", parent, () => provider.mkdir(parent, { recursive: true })).pipe(Effect.ignore, Effect.andThen(write))));
108
- };
109
- return {
110
- readFile: Effect.fn("SandboxFileSystem.readFile")((path) => attempt("readFile", path, () => provider.readFile(path))),
111
- readFileBuffer: Effect.fn("SandboxFileSystem.readFileBuffer")((path) => attempt("readFileBuffer", path, () => provider.readFileBuffer(path))),
112
- writeFile: Effect.fn("SandboxFileSystem.writeFile")(writeCreatingParents),
113
- stat: Effect.fn("SandboxFileSystem.stat")((path) => attempt("stat", path, () => provider.stat(path))),
114
- ...provider.lstat === void 0 ? {} : { lstat: Effect.fn("SandboxFileSystem.lstat")((path) => attempt("lstat", path, () => provider.lstat(path))) },
115
- readdir: Effect.fn("SandboxFileSystem.readdir")((path) => attempt("readdir", path, () => provider.readdir(path))),
116
- exists: Effect.fn("SandboxFileSystem.exists")((path) => attempt("exists", path, () => provider.exists(path))),
117
- mkdir: Effect.fn("SandboxFileSystem.mkdir")((path, options) => attempt("mkdir", path, () => provider.mkdir(path, options))),
118
- rm: Effect.fn("SandboxFileSystem.rm")((path, options) => validateRmOptions(options).pipe(Effect.andThen(attempt("rm", path, () => provider.rm(path, options))))),
119
- realpath: Effect.fn("SandboxFileSystem.realpath")((path) => attempt("realpath", path, () => provider.realpath(path)))
120
- };
121
- };
122
- /**
123
- * Bind a cwd-neutral filesystem to one mount's working directory.
124
- *
125
- * The counterpart of `Shell.withCwd`, and the reason relative paths mean the
126
- * same thing to both: a shared transport stays rooted at the namespace root, so
127
- * resolution happens here, per mount, rather than inside a VFS whose `chdir` is
128
- * global state two mounts would fight over.
129
- */
130
- const withCwd = (fs, cwd) => {
131
- const at = (path) => posix.resolve(cwd, path);
132
- return {
133
- readFile: (path) => fs.readFile(at(path)),
134
- readFileBuffer: (path) => fs.readFileBuffer(at(path)),
135
- writeFile: (path, content) => fs.writeFile(at(path), content),
136
- stat: (path) => fs.stat(at(path)),
137
- readdir: (path) => fs.readdir(at(path)),
138
- exists: (path) => fs.exists(at(path)),
139
- mkdir: (path, options) => fs.mkdir(at(path), options),
140
- rm: (path, options) => fs.rm(at(path), options),
141
- realpath: (path) => fs.realpath(at(path)),
142
- ...fs.lstat === void 0 ? {} : { lstat: (path) => fs.lstat(at(path)) }
143
- };
144
- };
145
- //#endregion
146
- export { FileSystemError, OperationUnsupportedError, filesystem_exports as SandboxFileSystem, Service, fromProvider, isNotFoundError, realpathScripts, validateRmOptions, withCwd };
147
-
148
- //# sourceMappingURL=filesystem.mjs.map
1
+ import { a as fromProvider, c as validateRmOptions, i as filesystem_exports, l as withCwd, n as OperationUnsupportedError, o as isNotFoundError, r as Service, s as realpathScripts, t as FileSystemError, u as scan_exports } from "../filesystem-BFCKzgND.mjs";
2
+ export { FileSystemError, OperationUnsupportedError, filesystem_exports as SandboxFileSystem, scan_exports as Scan, Service, fromProvider, isNotFoundError, realpathScripts, validateRmOptions, withCwd };
@@ -1,2 +1,2 @@
1
- import { Ct as toColumn, St as mountable, _t as Usage, bt as instance_d_exports, dt as ID, ft as Info, gt as Status, ht as PersistedError, mt as Ownership, pt as Kind, vt as fromColumn, wt as toField, xt as isMountable, yt as fromField } from "../io-DhT4Y0Lw.mjs";
1
+ import { Ct as toColumn, St as mountable, _t as Usage, bt as instance_d_exports, dt as ID, ft as Info, gt as Status, ht as PersistedError, mt as Ownership, pt as Kind, vt as fromColumn, wt as toField, xt as isMountable, yt as fromField } from "../io-BarV4hvG.mjs";
2
2
  export { ID, Info, Kind, Ownership, PersistedError, instance_d_exports as SandboxInstance, Status, Usage, fromColumn, fromField, isMountable, mountable, toColumn, toField };
package/sandbox/io.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as Mutation, c as host, d as io_d_exports, f as mount, g as withMutation, h as virtual, i as Layer, l as hostLayer, m as resolveMountCwd, n as FileSystem, o as Provides, p as remote, r as Identity, s as Shell, t as Current, u as identityLayer } from "../io-DhT4Y0Lw.mjs";
1
+ import { a as Mutation, c as host, d as io_d_exports, f as mount, g as withMutation, h as virtual, i as Layer, l as hostLayer, m as resolveMountCwd, n as FileSystem, o as Provides, p as remote, r as Identity, s as Shell, t as Current, u as identityLayer } from "../io-BarV4hvG.mjs";
2
2
  export { Current, FileSystem, Identity, Layer, Mutation, Provides, io_d_exports as SandboxIO, Shell, host, hostLayer, identityLayer, mount, remote, resolveMountCwd, virtual, withMutation };
package/sandbox/io.mjs CHANGED
@@ -1,3 +1,3 @@
1
1
  import "./instance.mjs";
2
- import { a as host, c as io_exports, d as resolveMountCwd, f as virtual, i as Shell, l as mount, n as FileSystem, o as hostLayer, p as withMutation, r as Mutation, s as identityLayer, t as Current, u as remote } from "../io-5PrgzDTe.mjs";
2
+ import { a as host, c as io_exports, d as resolveMountCwd, f as virtual, i as Shell, l as mount, n as FileSystem, o as hostLayer, p as withMutation, r as Mutation, s as identityLayer, t as Current, u as remote } from "../io-CFWrEV0O.mjs";
3
3
  export { Current, FileSystem, Mutation, io_exports as SandboxIO, Shell, host, hostLayer, identityLayer, mount, remote, resolveMountCwd, virtual, withMutation };
package/sandbox.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as RuntimeInput, C as ModuleDefinition, E as Provisioned, M as apiVersion, N as defineModule, O as Registration, P as driver, R as Redactor, S as Module, T as Observed, Y as SandboxProviderError, _ as AbsolutePath, a as Mutation, b as Definition, bt as instance_d_exports, ct as providerErrorCause, g as withMutation, i as Layer, k as RuntimeConfigBase, lt as providerErrorIsNotFound, n as FileSystem, o as Provides, ot as makeRedactor, r as Identity, s as Shell, st as providerError, t as Current, ut as sanitizeError, v as ApiVersion, w as Name, x as Driver, y as Capabilities } from "./io-DhT4Y0Lw.mjs";
2
- import { c as filesystem_d_exports } from "./filesystem-Cv2gjOJa.mjs";
1
+ import { A as RuntimeInput, C as ModuleDefinition, E as Provisioned, M as apiVersion, N as defineModule, O as Registration, P as driver, R as Redactor, S as Module, T as Observed, Y as SandboxProviderError, _ as AbsolutePath, a as Mutation, b as Definition, bt as instance_d_exports, ct as providerErrorCause, g as withMutation, i as Layer, k as RuntimeConfigBase, lt as providerErrorIsNotFound, n as FileSystem, o as Provides, ot as makeRedactor, r as Identity, s as Shell, st as providerError, t as Current, ut as sanitizeError, v as ApiVersion, w as Name, x as Driver, y as Capabilities } from "./io-BarV4hvG.mjs";
2
+ import { c as filesystem_d_exports } from "./filesystem-BYaEdL14.mjs";
3
3
  import { a as ShellError, i as Shell$1, l as quote, n as ExecResult, o as ShellOptions, r as ISandboxExe, s as fromExec, t as ExecChunk, u as quoteArgv } from "./shell-CZ6Y4lNU.mjs";
4
4
  import { SandboxResource as resource_d_exports } from "./sandbox/resource.mjs";
5
5
  declare namespace driver_d_exports {
package/sandbox.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
2
  import { SandboxInstance as instance_exports } from "./sandbox/instance.mjs";
3
- import { SandboxFileSystem as filesystem_exports } from "./sandbox/filesystem.mjs";
4
- import { i as Shell, n as FileSystem, p as withMutation, r as Mutation, t as Current } from "./io-5PrgzDTe.mjs";
3
+ import { i as filesystem_exports } from "./filesystem-BFCKzgND.mjs";
4
+ import { i as Shell, n as FileSystem, p as withMutation, r as Mutation, t as Current } from "./io-CFWrEV0O.mjs";
5
5
  import { Shell as Shell$1, ShellError, fromExec, quote, quoteArgv } from "./sandbox/shell.mjs";
6
6
  import { AbsolutePath, Name, RuntimeConfigBase, driver, module as defineModule } from "./sandbox/driver.mjs";
7
7
  import { SandboxProviderError, makeRedactor, providerError, providerErrorCause, providerErrorIsNotFound, sanitizeError } from "./sandbox/errors.mjs";
@@ -1 +0,0 @@
1
- {"version":3,"file":"filesystem.mjs","names":[],"sources":["../../../src/sandbox/filesystem.ts"],"sourcesContent":["import { Context, Effect, Schema } from \"effect\";\nimport { posix } from \"../posix.ts\";\n\n/**\n * The runtime filesystem contract, independent of any backend.\n *\n * Two surfaces, deliberately:\n * - {@link Provider} is what a backend implements — plain promises that reject,\n * matching every SDK we wrap.\n * - {@link Interface} is what the harness consumes — Effect with a typed error\n * channel and tracing spans. {@link fromProvider} bridges the two exactly\n * once, so no consumer ever writes `Effect.tryPromise` against a filesystem.\n *\n * Implementations:\n * - Local:\n * implement it over a VFS (`./local`);\n * local filesystem use OS primitives; hence have broader filesytem capabilities.\n *\n * - Remote:\n * implement it over a provider (`./remote`).\n * remote filesytems depends on the interface provided by the remote provider; hence can have limited filesytem capabilities.\n *\n * `isFile`/`isDirectory` are required booleans; size, mtime, and isSymbolicLink are omitted when the\n * backend cannot report them — never fabricated.\n *\n * **Paths are POSIX, and the harness is Unix-only (for now!).** Every path uses `/`\n * separators on both the host and inside a sandbox — Windows is not supported,\n * so no translation layer exists. Consumers must use the shared Effect POSIX\n * path implementation, never the platform default, or a host running the harness would\n * impose its own flavour on a remote sandbox's paths. Relative paths resolve\n * against the backend's configured `cwd`.\n */\n\nexport class OperationUnsupportedError extends Schema.TaggedError<OperationUnsupportedError>()(\n\t\"OperationUnsupportedError\",\n\t{\n\t\toperation: Schema.String,\n\t\tmessage: Schema.String,\n\t},\n) {}\n\n/** A backend operation failed. `cause` carries the provider's own rejection. */\nexport class FileSystemError extends Schema.TaggedError<FileSystemError>()(\"SandboxFileSystemError\", {\n\tmethod: Schema.String,\n\tpath: Schema.String,\n\tcause: Schema.optional(Schema.Defect()),\n}) {}\n\nexport interface FileStat {\n\treadonly isFile: boolean;\n\treadonly isDirectory: boolean;\n\treadonly isSymbolicLink?: boolean;\n\treadonly size?: number;\n\treadonly mtime?: Date;\n}\n\nexport interface RmOptions {\n\treadonly recursive?: boolean;\n\treadonly force?: boolean;\n}\n\n/** Whether a provider failure means the path itself is definitively absent. */\nexport const isNotFoundError = (cause: unknown) => {\n\tconst code = (cause as NodeJS.ErrnoException | undefined)?.code;\n\treturn code === \"ENOENT\" || code === \"ENOTDIR\";\n};\n\n/**\n * Shell forms of `realpath` for backends that only expose a process API. Run as\n * `sh -c <script> _ <path>`, trying each in turn. `realpath -e` (coreutils)\n * resolves every component, a symlinked file included, and fails on a missing\n * path. Where it is absent, `pwd -P` is the portable primitive: directories\n * resolve directly, anything else resolves its parent and keeps the final name\n * as given — so a symlinked *file* stays unresolved there.\n */\nexport const realpathScripts = [\n\t'realpath -e -- \"$1\"',\n\t'cd -- \"$1\" && pwd -P',\n\t'cd -- \"$(dirname -- \"$1\")\" && printf \\'%s/%s\\' \"$(pwd -P)\" \"$(basename -- \"$1\")\"',\n] as const;\n\n/**\n * The backend-facing contract. Backends author plain promises and let them\n * reject; {@link fromProvider} turns rejections into typed failures.\n */\nexport interface Provider {\n\treadonly readFile: (path: string) => Promise<string>;\n\treadonly readFileBuffer: (path: string) => Promise<Uint8Array>;\n\t/**\n\t * Write the file. Parents may be missing — do not create them here;\n\t * {@link fromProvider} owns that guarantee for every backend.\n\t */\n\treadonly writeFile: (path: string, content: string | Uint8Array) => Promise<void>;\n\treadonly stat: (path: string) => Promise<FileStat>;\n\treadonly readdir: (path: string) => Promise<string[]>;\n\treadonly exists: (path: string) => Promise<boolean>;\n\treadonly mkdir: (path: string, options?: { recursive?: boolean }) => Promise<void>;\n\treadonly rm: (path: string, options?: RmOptions) => Promise<void>;\n\t/** Canonical absolute path with symlinks resolved; rejects when the path does not exist. */\n\treadonly realpath: (path: string) => Promise<string>;\n\t/**\n\t * Metadata for the directory entry itself rather than a symlink's target.\n\t * Optional: a backend whose `stat` has mixed symlink semantics implements it\n\t * so symlink identity is asked for explicitly, never inferred.\n\t */\n\treadonly lstat?: (path: string) => Promise<FileStat>;\n}\n\n/**\n * The consumer-facing contract. `exists` distinguishes \"absent\" from \"could not\n * tell\": a backend failure is a typed failure, not `false`, so a caller acting\n * on absence never acts on a network blip. Use `SandboxFs.existsOrFalse` where\n * a best-effort answer really is wanted.\n */\nexport interface Interface {\n\treadonly readFile: (path: string) => Effect.Effect<string, FileSystemError>;\n\treadonly readFileBuffer: (path: string) => Effect.Effect<Uint8Array, FileSystemError>;\n\t/** Creates missing parent directories, on every backend. */\n\treadonly writeFile: (path: string, content: string | Uint8Array) => Effect.Effect<void, FileSystemError>;\n\treadonly stat: (path: string) => Effect.Effect<FileStat, FileSystemError>;\n\treadonly readdir: (path: string) => Effect.Effect<string[], FileSystemError>;\n\treadonly exists: (path: string) => Effect.Effect<boolean, FileSystemError>;\n\treadonly mkdir: (path: string, options?: { recursive?: boolean }) => Effect.Effect<void, FileSystemError>;\n\treadonly rm: (path: string, options?: RmOptions) => Effect.Effect<void, FileSystemError | OperationUnsupportedError>;\n\t/** Canonical absolute path with symlinks resolved; fails when the path does not exist. */\n\treadonly realpath: (path: string) => Effect.Effect<string, FileSystemError>;\n\t// `lstat` is present only when the backend supports it; check before calling.\n\treadonly lstat?: (path: string) => Effect.Effect<FileStat, FileSystemError>;\n}\n\n/** The runtime filesystem service — the live {@link Interface} for the active sandbox. */\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/plugin/sandbox/filesystem/Service\") {}\n\n/**\n * Reject `rm` options a provider does not implement, before any mutation. Only\n * `recursive` and `force` are part of the contract; anything else is refused\n * loudly rather than silently ignored.\n */\nexport const validateRmOptions = (\n\toptions: RmOptions | undefined,\n\toperation = \"rm\",\n): Effect.Effect<void, OperationUnsupportedError> =>\n\tEffect.suspend(() => {\n\t\tfor (const option of Object.keys((options ?? {}) as Record<string, unknown>)) {\n\t\t\tif (option === \"recursive\" || option === \"force\") continue;\n\t\t\treturn Effect.fail(new OperationUnsupportedError({ operation, message: `Unsupported rm option: ${option}` }));\n\t\t}\n\t\treturn Effect.void;\n\t});\n\n/**\n * Lift a {@link Provider} into the runtime {@link Interface}: one place that\n * converts rejections into {@link FileSystemError}, validates `rm` options,\n * creates missing parents on write, and names a tracing span per operation.\n */\nexport const fromProvider = (provider: Provider): Interface => {\n\tconst attempt = <A>(method: string, path: string, run: () => Promise<A>) =>\n\t\tEffect.tryPromise({ try: run, catch: (cause) => new FileSystemError({ method, path, cause }) });\n\n\t// The parent-creation guarantee, installed once for every backend instead of\n\t// re-implemented per provider: anything that reaches `Interface` reaches it\n\t// through here, so a backend cannot forget it.\n\t//\n\t// Lazy by design — try the write first, so the happy path stays a single call\n\t// and no remote backend pays a round-trip per write. A failure is usually a\n\t// missing parent, so create it and retry once. The mkdir's own error is\n\t// dropped on purpose: when the write failed for some other reason (EACCES,\n\t// EROFS, a dropped connection), the retry reproduces it, and *that* is the\n\t// failure the caller must see rather than a misleading mkdir error standing\n\t// in for it.\n\tconst writeCreatingParents = (path: string, content: string | Uint8Array) => {\n\t\tconst write = attempt(\"writeFile\", path, () => provider.writeFile(path, content));\n\t\tconst parent = posix.dirname(path);\n\t\treturn write.pipe(\n\t\t\tEffect.catch(() =>\n\t\t\t\tattempt(\"mkdir\", parent, () => provider.mkdir(parent, { recursive: true })).pipe(\n\t\t\t\t\tEffect.ignore,\n\t\t\t\t\tEffect.andThen(write),\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\t};\n\n\treturn {\n\t\treadFile: Effect.fn(\"SandboxFileSystem.readFile\")((path: string) =>\n\t\t\tattempt(\"readFile\", path, () => provider.readFile(path)),\n\t\t),\n\t\treadFileBuffer: Effect.fn(\"SandboxFileSystem.readFileBuffer\")((path: string) =>\n\t\t\tattempt(\"readFileBuffer\", path, () => provider.readFileBuffer(path)),\n\t\t),\n\t\twriteFile: Effect.fn(\"SandboxFileSystem.writeFile\")(writeCreatingParents),\n\t\tstat: Effect.fn(\"SandboxFileSystem.stat\")((path: string) => attempt(\"stat\", path, () => provider.stat(path))),\n\t\t// carried through only when the backend actually implements it\n\t\t...(provider.lstat === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tlstat: Effect.fn(\"SandboxFileSystem.lstat\")((path: string) =>\n\t\t\t\t\t\tattempt(\"lstat\", path, () => provider.lstat!(path)),\n\t\t\t\t\t),\n\t\t\t\t}),\n\t\treaddir: Effect.fn(\"SandboxFileSystem.readdir\")((path: string) =>\n\t\t\tattempt(\"readdir\", path, () => provider.readdir(path)),\n\t\t),\n\t\t// A backend that cannot answer fails; it does not report \"absent\". A\n\t\t// caller acting on absence — deleting a record, say — must not be told\n\t\t// the path is gone because a token expired or a request timed out.\n\t\texists: Effect.fn(\"SandboxFileSystem.exists\")((path: string) =>\n\t\t\tattempt(\"exists\", path, () => provider.exists(path)),\n\t\t),\n\t\tmkdir: Effect.fn(\"SandboxFileSystem.mkdir\")((path: string, options?: { recursive?: boolean }) =>\n\t\t\tattempt(\"mkdir\", path, () => provider.mkdir(path, options)),\n\t\t),\n\t\trm: Effect.fn(\"SandboxFileSystem.rm\")((path: string, options?: RmOptions) =>\n\t\t\tvalidateRmOptions(options).pipe(Effect.andThen(attempt(\"rm\", path, () => provider.rm(path, options)))),\n\t\t),\n\t\trealpath: Effect.fn(\"SandboxFileSystem.realpath\")((path: string) =>\n\t\t\tattempt(\"realpath\", path, () => provider.realpath(path)),\n\t\t),\n\t};\n};\n\n/**\n * Bind a cwd-neutral filesystem to one mount's working directory.\n *\n * The counterpart of `Shell.withCwd`, and the reason relative paths mean the\n * same thing to both: a shared transport stays rooted at the namespace root, so\n * resolution happens here, per mount, rather than inside a VFS whose `chdir` is\n * global state two mounts would fight over.\n */\nexport const withCwd = (fs: Interface, cwd: string): Interface => {\n\tconst at = (path: string) => posix.resolve(cwd, path);\n\treturn {\n\t\treadFile: (path) => fs.readFile(at(path)),\n\t\treadFileBuffer: (path) => fs.readFileBuffer(at(path)),\n\t\twriteFile: (path, content) => fs.writeFile(at(path), content),\n\t\tstat: (path) => fs.stat(at(path)),\n\t\treaddir: (path) => fs.readdir(at(path)),\n\t\texists: (path) => fs.exists(at(path)),\n\t\tmkdir: (path, options) => fs.mkdir(at(path), options),\n\t\trm: (path, options) => fs.rm(at(path), options),\n\t\trealpath: (path) => fs.realpath(at(path)),\n\t\t// carried through only when the backend implements it, so a caller can\n\t\t// still detect absence by checking the property\n\t\t...(fs.lstat === undefined ? {} : { lstat: (path: string) => fs.lstat!(at(path)) }),\n\t};\n};\n\nexport * as SandboxFileSystem from \"./filesystem.ts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,IAAa,4BAAb,cAA+C,OAAO,YAAuC,CAAC,CAC7F,6BACA;CACC,WAAW,OAAO;CAClB,SAAS,OAAO;AACjB,CACD,CAAC,CAAC,CAAC;;AAGH,IAAa,kBAAb,cAAqC,OAAO,YAA6B,CAAC,CAAC,0BAA0B;CACpG,QAAQ,OAAO;CACf,MAAM,OAAO;CACb,OAAO,OAAO,SAAS,OAAO,OAAO,CAAC;AACvC,CAAC,CAAC,CAAC,CAAC;;AAgBJ,MAAa,mBAAmB,UAAmB;CAClD,MAAM,OAAQ,OAA6C;CAC3D,OAAO,SAAS,YAAY,SAAS;AACtC;;;;;;;;;AAUA,MAAa,kBAAkB;CAC9B;CACA;CACA;AACD;;AAoDA,IAAa,UAAb,cAA6B,QAAQ,QAA4B,CAAC,CAAC,+CAA+C,CAAC,CAAC,CAAC;;;;;;AAOrH,MAAa,qBACZ,SACA,YAAY,SAEZ,OAAO,cAAc;CACpB,KAAK,MAAM,UAAU,OAAO,KAAM,WAAW,CAAC,CAA6B,GAAG;EAC7E,IAAI,WAAW,eAAe,WAAW,SAAS;EAClD,OAAO,OAAO,KAAK,IAAI,0BAA0B;GAAE;GAAW,SAAS,0BAA0B;EAAS,CAAC,CAAC;CAC7G;CACA,OAAO,OAAO;AACf,CAAC;;;;;;AAOF,MAAa,gBAAgB,aAAkC;CAC9D,MAAM,WAAc,QAAgB,MAAc,QACjD,OAAO,WAAW;EAAE,KAAK;EA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