@clearideas/agent-runtime-sandbox 0.5.0 → 0.6.0
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.
- package/README.md +20 -2
- package/assets/agent-fs.py +555 -0
- package/dist/bubblewrap.d.ts +59 -0
- package/dist/bubblewrap.js +408 -0
- package/dist/contracts.d.ts +21 -0
- package/dist/contracts.js +3 -0
- package/dist/docker.d.ts +3 -1
- package/dist/docker.js +31 -2
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/policy.d.ts +114 -0
- package/dist/policy.js +649 -0
- package/dist/run-sandbox.d.ts +69 -0
- package/dist/run-sandbox.js +852 -0
- package/dist/testing/host-process-provider.d.ts +28 -0
- package/dist/testing/host-process-provider.js +153 -0
- package/dist/testing/index.d.ts +1 -0
- package/dist/testing/index.js +1 -0
- package/package.json +8 -3
package/README.md
CHANGED
|
@@ -7,5 +7,23 @@ allowlists, and artifact persistence.
|
|
|
7
7
|
|
|
8
8
|
`DockerSandboxProvider` launches containers with networking disabled, a
|
|
9
9
|
read-only root filesystem, process and memory limits, and an isolated
|
|
10
|
-
`/workspace` tmpfs.
|
|
11
|
-
|
|
10
|
+
`/workspace` tmpfs. `BubblewrapSandboxProvider` provides equivalent isolation
|
|
11
|
+
on Linux without a container daemon (user, PID, IPC, UTS, cgroup, and network
|
|
12
|
+
namespaces plus `prlimit` limits) and is the reference provider for local
|
|
13
|
+
development and continuous integration. Remote and application-specific
|
|
14
|
+
services can implement the same `SandboxProvider` contract.
|
|
15
|
+
|
|
16
|
+
`ProviderRunSandbox` implements the run sandbox: one sandbox per run attempt
|
|
17
|
+
in which every workspace operation executes as one command admitted by the
|
|
18
|
+
host command policy (`commands`, `shell`, `limits`), reported through
|
|
19
|
+
`sandbox.*` events, and recorded in the transcript. It stages bound
|
|
20
|
+
workspaces, serves the built-in `list_files`, `read_file`, `search_files`,
|
|
21
|
+
`write_file`, and `delete_file` operations through the bundled `agent-fs`
|
|
22
|
+
helper (`assets/agent-fs.py`, replaceable by a host-supplied program with the
|
|
23
|
+
same protocol), syncs read-write mounts back to their stores after each
|
|
24
|
+
command, and runs code steps that declare `workspaces`.
|
|
25
|
+
|
|
26
|
+
`@clearideas/agent-runtime-sandbox/testing` exports `HostProcessTestProvider`,
|
|
27
|
+
a **test-only** provider with no isolation that runs commands as host
|
|
28
|
+
processes so the run sandbox can be exercised where neither bubblewrap nor
|
|
29
|
+
Docker is available. Never use it outside tests.
|
|
@@ -0,0 +1,555 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Agent Runtime workspace helper.
|
|
3
|
+
|
|
4
|
+
Executed inside the run sandbox by Agent Runtime to implement the built-in
|
|
5
|
+
workspace operations. It never runs in the host process. Every operation
|
|
6
|
+
prints exactly one JSON document on stdout and exits with:
|
|
7
|
+
|
|
8
|
+
0 success
|
|
9
|
+
2 usage error
|
|
10
|
+
3 path invalid, not visible, or not found
|
|
11
|
+
4 limit exceeded
|
|
12
|
+
5 read-only mount
|
|
13
|
+
|
|
14
|
+
Paths are relative POSIX paths whose segments match [A-Za-z0-9][A-Za-z0-9._-]*.
|
|
15
|
+
Symbolic links are never followed. Content is never interpreted beyond UTF-8
|
|
16
|
+
decoding for text windows and literal substring search.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import argparse
|
|
20
|
+
import base64
|
|
21
|
+
import hashlib
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
import sys
|
|
26
|
+
import tempfile
|
|
27
|
+
|
|
28
|
+
PROTOCOL_VERSION = 1
|
|
29
|
+
HELPER_VERSION = "1.0.0"
|
|
30
|
+
SEGMENT = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
|
|
31
|
+
MAX_PATH_LENGTH = 1024
|
|
32
|
+
MAX_PATH_DEPTH = 64
|
|
33
|
+
TEXT_SNIFF_BYTES = 8192
|
|
34
|
+
DEFAULT_LINE_COUNT = 400
|
|
35
|
+
MAX_LINE_COUNT = 2000
|
|
36
|
+
|
|
37
|
+
MEDIA_TYPES = {
|
|
38
|
+
".txt": "text/plain",
|
|
39
|
+
".md": "text/markdown",
|
|
40
|
+
".markdown": "text/markdown",
|
|
41
|
+
".json": "application/json",
|
|
42
|
+
".yaml": "application/yaml",
|
|
43
|
+
".yml": "application/yaml",
|
|
44
|
+
".toml": "application/toml",
|
|
45
|
+
".xml": "application/xml",
|
|
46
|
+
".html": "text/html",
|
|
47
|
+
".htm": "text/html",
|
|
48
|
+
".css": "text/css",
|
|
49
|
+
".csv": "text/csv",
|
|
50
|
+
".js": "text/javascript",
|
|
51
|
+
".mjs": "text/javascript",
|
|
52
|
+
".cjs": "text/javascript",
|
|
53
|
+
".jsx": "text/javascript",
|
|
54
|
+
".ts": "text/typescript",
|
|
55
|
+
".tsx": "text/typescript",
|
|
56
|
+
".py": "text/x-python",
|
|
57
|
+
".rb": "text/x-ruby",
|
|
58
|
+
".go": "text/x-go",
|
|
59
|
+
".rs": "text/x-rust",
|
|
60
|
+
".java": "text/x-java",
|
|
61
|
+
".kt": "text/x-kotlin",
|
|
62
|
+
".c": "text/x-c",
|
|
63
|
+
".h": "text/x-c",
|
|
64
|
+
".cpp": "text/x-c++",
|
|
65
|
+
".hpp": "text/x-c++",
|
|
66
|
+
".cs": "text/x-csharp",
|
|
67
|
+
".sh": "text/x-shellscript",
|
|
68
|
+
".sql": "application/sql",
|
|
69
|
+
".png": "image/png",
|
|
70
|
+
".jpg": "image/jpeg",
|
|
71
|
+
".jpeg": "image/jpeg",
|
|
72
|
+
".gif": "image/gif",
|
|
73
|
+
".webp": "image/webp",
|
|
74
|
+
".svg": "image/svg+xml",
|
|
75
|
+
".pdf": "application/pdf",
|
|
76
|
+
".zip": "application/zip",
|
|
77
|
+
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
78
|
+
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
79
|
+
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
80
|
+
}
|
|
81
|
+
TEXT_MEDIA_TYPES = {
|
|
82
|
+
"application/json",
|
|
83
|
+
"application/yaml",
|
|
84
|
+
"application/toml",
|
|
85
|
+
"application/xml",
|
|
86
|
+
"application/sql",
|
|
87
|
+
"image/svg+xml",
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class HelperError(Exception):
|
|
92
|
+
def __init__(self, code, message, exit_code):
|
|
93
|
+
super().__init__(message)
|
|
94
|
+
self.code = code
|
|
95
|
+
self.exit_code = exit_code
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def usage_error(message):
|
|
99
|
+
return HelperError("usage", message, 2)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def path_error(message):
|
|
103
|
+
return HelperError("path_invalid", message, 3)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def limit_error(message):
|
|
107
|
+
return HelperError("limit_exceeded", message, 4)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def read_only_error():
|
|
111
|
+
return HelperError("read_only", "Mount is read-only.", 5)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def is_safe_path(value):
|
|
115
|
+
if not value or len(value) > MAX_PATH_LENGTH:
|
|
116
|
+
return False
|
|
117
|
+
segments = value.split("/")
|
|
118
|
+
if len(segments) > MAX_PATH_DEPTH:
|
|
119
|
+
return False
|
|
120
|
+
return all(SEGMENT.match(segment) for segment in segments)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def assert_safe_path(value):
|
|
124
|
+
if not is_safe_path(value):
|
|
125
|
+
raise path_error("Path must be a relative POSIX path with safe segments: %s" % value)
|
|
126
|
+
return value
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def compile_glob(pattern):
|
|
130
|
+
if not pattern.strip() or len(pattern) > 512:
|
|
131
|
+
raise usage_error("Invalid glob: %s" % pattern)
|
|
132
|
+
source = ""
|
|
133
|
+
index = 0
|
|
134
|
+
while index < len(pattern):
|
|
135
|
+
character = pattern[index]
|
|
136
|
+
if character == "*":
|
|
137
|
+
if index + 1 < len(pattern) and pattern[index + 1] == "*":
|
|
138
|
+
if index + 2 < len(pattern) and pattern[index + 2] == "/":
|
|
139
|
+
source += "(?:.*/)?"
|
|
140
|
+
index += 3
|
|
141
|
+
else:
|
|
142
|
+
source += ".*"
|
|
143
|
+
index += 2
|
|
144
|
+
continue
|
|
145
|
+
source += "[^/]*"
|
|
146
|
+
index += 1
|
|
147
|
+
continue
|
|
148
|
+
if character == "?":
|
|
149
|
+
source += "[^/]"
|
|
150
|
+
index += 1
|
|
151
|
+
continue
|
|
152
|
+
source += re.escape(character)
|
|
153
|
+
index += 1
|
|
154
|
+
return re.compile("^" + source + "$")
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def media_type_for(relative_path):
|
|
158
|
+
_, extension = os.path.splitext(relative_path)
|
|
159
|
+
return MEDIA_TYPES.get(extension.lower(), "application/octet-stream")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def is_text_media_type(media_type):
|
|
163
|
+
return media_type.startswith("text/") or media_type in TEXT_MEDIA_TYPES
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def decode_text(data):
|
|
167
|
+
sample = data[:TEXT_SNIFF_BYTES]
|
|
168
|
+
if b"\x00" in sample:
|
|
169
|
+
return None
|
|
170
|
+
try:
|
|
171
|
+
return data.decode("utf-8")
|
|
172
|
+
except UnicodeDecodeError:
|
|
173
|
+
return None
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
class Mount:
|
|
177
|
+
def __init__(self, directory, writable):
|
|
178
|
+
self.root = os.path.realpath(directory)
|
|
179
|
+
self.writable = writable
|
|
180
|
+
if not os.path.isdir(self.root):
|
|
181
|
+
raise usage_error("Mount directory does not exist: %s" % directory)
|
|
182
|
+
|
|
183
|
+
def absolute(self, relative_path):
|
|
184
|
+
assert_safe_path(relative_path)
|
|
185
|
+
current = self.root
|
|
186
|
+
for segment in relative_path.split("/"):
|
|
187
|
+
current = os.path.join(current, segment)
|
|
188
|
+
try:
|
|
189
|
+
stats = os.lstat(current)
|
|
190
|
+
except FileNotFoundError:
|
|
191
|
+
continue
|
|
192
|
+
if os.path.islink(current) or (stats.st_mode & 0o170000) == 0o120000:
|
|
193
|
+
raise path_error("Path crosses a symbolic link: %s" % relative_path)
|
|
194
|
+
real = os.path.realpath(current)
|
|
195
|
+
if real != self.root and not real.startswith(self.root + os.sep):
|
|
196
|
+
raise path_error("Path escapes the mount: %s" % relative_path)
|
|
197
|
+
return current
|
|
198
|
+
|
|
199
|
+
def stat_file(self, relative_path):
|
|
200
|
+
absolute = self.absolute(relative_path)
|
|
201
|
+
try:
|
|
202
|
+
stats = os.lstat(absolute)
|
|
203
|
+
except FileNotFoundError:
|
|
204
|
+
raise path_error("File is not available: %s" % relative_path)
|
|
205
|
+
if not os.path.isfile(absolute) or os.path.islink(absolute):
|
|
206
|
+
raise path_error("File is not available: %s" % relative_path)
|
|
207
|
+
return absolute, stats
|
|
208
|
+
|
|
209
|
+
def walk(self, prefix, max_scan, ignored=None):
|
|
210
|
+
pending = [prefix]
|
|
211
|
+
visited = 0
|
|
212
|
+
results = []
|
|
213
|
+
while pending:
|
|
214
|
+
directory = pending.pop(0)
|
|
215
|
+
absolute = self.absolute(directory) if directory else self.root
|
|
216
|
+
try:
|
|
217
|
+
names = sorted(os.listdir(absolute))
|
|
218
|
+
except FileNotFoundError:
|
|
219
|
+
if directory == prefix:
|
|
220
|
+
return []
|
|
221
|
+
raise
|
|
222
|
+
except NotADirectoryError:
|
|
223
|
+
if directory == prefix:
|
|
224
|
+
return []
|
|
225
|
+
raise
|
|
226
|
+
for name in names:
|
|
227
|
+
visited += 1
|
|
228
|
+
if visited > max_scan:
|
|
229
|
+
raise limit_error("Listing exceeded %d directory entries." % max_scan)
|
|
230
|
+
relative = directory + "/" + name if directory else name
|
|
231
|
+
child = os.path.join(absolute, name)
|
|
232
|
+
if name.startswith(".agent-runtime"):
|
|
233
|
+
continue
|
|
234
|
+
if not is_safe_path(relative):
|
|
235
|
+
if ignored is not None:
|
|
236
|
+
ignored.append({"path": relative, "reason": "path"})
|
|
237
|
+
continue
|
|
238
|
+
if os.path.islink(child):
|
|
239
|
+
if ignored is not None:
|
|
240
|
+
ignored.append({"path": relative, "reason": "symlink"})
|
|
241
|
+
continue
|
|
242
|
+
if os.path.isdir(child):
|
|
243
|
+
pending.append(relative)
|
|
244
|
+
continue
|
|
245
|
+
if not os.path.isfile(child):
|
|
246
|
+
continue
|
|
247
|
+
stats = os.lstat(child)
|
|
248
|
+
results.append((relative, stats))
|
|
249
|
+
results.sort(key=lambda item: item[0])
|
|
250
|
+
return results
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def iso(timestamp):
|
|
254
|
+
import datetime
|
|
255
|
+
|
|
256
|
+
return (
|
|
257
|
+
datetime.datetime.fromtimestamp(timestamp, datetime.timezone.utc)
|
|
258
|
+
.isoformat()
|
|
259
|
+
.replace("+00:00", "Z")
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def file_info(relative, stats):
|
|
264
|
+
return {
|
|
265
|
+
"path": relative,
|
|
266
|
+
"size": stats.st_size,
|
|
267
|
+
"mediaType": media_type_for(relative),
|
|
268
|
+
"modifiedAt": iso(stats.st_mtime),
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def op_list(mount, args):
|
|
273
|
+
prefix = ""
|
|
274
|
+
if args.path:
|
|
275
|
+
prefix = assert_safe_path(args.path.rstrip("/"))
|
|
276
|
+
pattern = compile_glob(args.glob) if args.glob else None
|
|
277
|
+
limit = min(args.limit or 1000, args.max_files)
|
|
278
|
+
files = []
|
|
279
|
+
truncated = False
|
|
280
|
+
for relative, stats in mount.walk(prefix, args.max_scan):
|
|
281
|
+
if pattern and not pattern.match(relative):
|
|
282
|
+
continue
|
|
283
|
+
if len(files) >= limit:
|
|
284
|
+
truncated = True
|
|
285
|
+
break
|
|
286
|
+
files.append(file_info(relative, stats))
|
|
287
|
+
return {"files": files, "truncated": truncated}
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def op_read(mount, args):
|
|
291
|
+
relative = assert_safe_path(args.path)
|
|
292
|
+
absolute, stats = mount.stat_file(relative)
|
|
293
|
+
if stats.st_size > args.max_bytes:
|
|
294
|
+
raise limit_error(
|
|
295
|
+
"File %s is %d bytes, exceeding the %d-byte limit." % (relative, stats.st_size, args.max_bytes)
|
|
296
|
+
)
|
|
297
|
+
with open(absolute, "rb") as handle:
|
|
298
|
+
data = handle.read(args.max_bytes + 1)
|
|
299
|
+
if len(data) > args.max_bytes:
|
|
300
|
+
raise limit_error("File %s exceeds the %d-byte limit." % (relative, args.max_bytes))
|
|
301
|
+
media_type = media_type_for(relative)
|
|
302
|
+
text = decode_text(data) if is_text_media_type(media_type) else None
|
|
303
|
+
if text is None:
|
|
304
|
+
result = {
|
|
305
|
+
"path": relative,
|
|
306
|
+
"size": len(data),
|
|
307
|
+
"mediaType": media_type,
|
|
308
|
+
"encoding": "binary",
|
|
309
|
+
}
|
|
310
|
+
if args.artifact_dir:
|
|
311
|
+
os.makedirs(args.artifact_dir, exist_ok=True)
|
|
312
|
+
target = os.path.join(args.artifact_dir, os.path.basename(relative))
|
|
313
|
+
with open(target, "wb") as handle:
|
|
314
|
+
handle.write(data)
|
|
315
|
+
result["artifactFile"] = os.path.basename(relative)
|
|
316
|
+
return result
|
|
317
|
+
lines = text.split("\n")
|
|
318
|
+
if len(lines) > 1 and lines[-1] == "":
|
|
319
|
+
lines.pop()
|
|
320
|
+
lines = [line[:-1] if line.endswith("\r") else line for line in lines]
|
|
321
|
+
start_line = args.start_line or 1
|
|
322
|
+
line_count = min(args.line_count or DEFAULT_LINE_COUNT, MAX_LINE_COUNT)
|
|
323
|
+
window = lines[start_line - 1 : start_line - 1 + line_count]
|
|
324
|
+
return {
|
|
325
|
+
"path": relative,
|
|
326
|
+
"size": len(data),
|
|
327
|
+
"mediaType": media_type,
|
|
328
|
+
"encoding": "utf-8",
|
|
329
|
+
"content": "\n".join(window),
|
|
330
|
+
"startLine": start_line,
|
|
331
|
+
"lineCount": len(window),
|
|
332
|
+
"totalLines": len(lines),
|
|
333
|
+
"truncated": start_line - 1 + len(window) < len(lines),
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def op_search(mount, args):
|
|
338
|
+
query = args.query
|
|
339
|
+
if not query:
|
|
340
|
+
raise usage_error("Search query cannot be empty.")
|
|
341
|
+
if len(query) > 512:
|
|
342
|
+
raise limit_error("Search query exceeds 512 characters.")
|
|
343
|
+
pattern = compile_glob(args.glob) if args.glob else None
|
|
344
|
+
limit = min(args.limit or 200, args.max_results)
|
|
345
|
+
needle = query if args.case_sensitive else query.lower()
|
|
346
|
+
matches = []
|
|
347
|
+
truncated = False
|
|
348
|
+
scanned = 0
|
|
349
|
+
files_seen = 0
|
|
350
|
+
for relative, stats in mount.walk("", args.max_scan):
|
|
351
|
+
if pattern and not pattern.match(relative):
|
|
352
|
+
continue
|
|
353
|
+
files_seen += 1
|
|
354
|
+
if files_seen > args.max_files:
|
|
355
|
+
truncated = True
|
|
356
|
+
break
|
|
357
|
+
if stats.st_size > args.max_bytes:
|
|
358
|
+
continue
|
|
359
|
+
if not is_text_media_type(media_type_for(relative)):
|
|
360
|
+
continue
|
|
361
|
+
if scanned + stats.st_size > args.max_scan_bytes:
|
|
362
|
+
truncated = True
|
|
363
|
+
break
|
|
364
|
+
scanned += stats.st_size
|
|
365
|
+
with open(os.path.join(mount.root, *relative.split("/")), "rb") as handle:
|
|
366
|
+
data = handle.read(args.max_bytes + 1)
|
|
367
|
+
text = decode_text(data)
|
|
368
|
+
if text is None:
|
|
369
|
+
continue
|
|
370
|
+
for index, line in enumerate(text.split("\n")):
|
|
371
|
+
haystack = line if args.case_sensitive else line.lower()
|
|
372
|
+
if needle not in haystack:
|
|
373
|
+
continue
|
|
374
|
+
if len(matches) >= limit:
|
|
375
|
+
truncated = True
|
|
376
|
+
return {"matches": matches, "truncated": truncated}
|
|
377
|
+
matches.append({"path": relative, "line": index + 1, "text": line.rstrip("\r")})
|
|
378
|
+
return {"matches": matches, "truncated": truncated}
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def write_atomically(absolute, data):
|
|
382
|
+
directory = os.path.dirname(absolute)
|
|
383
|
+
os.makedirs(directory, exist_ok=True)
|
|
384
|
+
handle, temporary = tempfile.mkstemp(prefix=".agent-fs.", dir=directory)
|
|
385
|
+
try:
|
|
386
|
+
with os.fdopen(handle, "wb") as stream:
|
|
387
|
+
stream.write(data)
|
|
388
|
+
stream.flush()
|
|
389
|
+
os.fsync(stream.fileno())
|
|
390
|
+
os.chmod(temporary, 0o600)
|
|
391
|
+
os.replace(temporary, absolute)
|
|
392
|
+
except Exception:
|
|
393
|
+
try:
|
|
394
|
+
os.unlink(temporary)
|
|
395
|
+
except OSError:
|
|
396
|
+
pass
|
|
397
|
+
raise
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def op_write(mount, args):
|
|
401
|
+
if not mount.writable:
|
|
402
|
+
raise read_only_error()
|
|
403
|
+
relative = assert_safe_path(args.path)
|
|
404
|
+
with open(args.source, "rb") as handle:
|
|
405
|
+
data = handle.read(args.max_bytes + 1)
|
|
406
|
+
if args.encoding == "base64":
|
|
407
|
+
try:
|
|
408
|
+
data = base64.b64decode(data, validate=True)
|
|
409
|
+
except Exception:
|
|
410
|
+
raise usage_error("Content is not valid base64.")
|
|
411
|
+
if len(data) > args.max_bytes:
|
|
412
|
+
raise limit_error("Write to %s exceeds the %d-byte limit." % (relative, args.max_bytes))
|
|
413
|
+
absolute = mount.absolute(relative)
|
|
414
|
+
if os.path.lexists(absolute) and (os.path.islink(absolute) or not os.path.isfile(absolute)):
|
|
415
|
+
raise path_error("Path is not a regular file: %s" % relative)
|
|
416
|
+
write_atomically(absolute, data)
|
|
417
|
+
stats = os.lstat(absolute)
|
|
418
|
+
return file_info(relative, stats)
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def op_delete(mount, args):
|
|
422
|
+
if not mount.writable:
|
|
423
|
+
raise read_only_error()
|
|
424
|
+
relative = assert_safe_path(args.path)
|
|
425
|
+
absolute, _ = mount.stat_file(relative)
|
|
426
|
+
os.unlink(absolute)
|
|
427
|
+
return {"path": relative, "deleted": True}
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def op_snapshot(mount, args):
|
|
431
|
+
files = []
|
|
432
|
+
ignored = []
|
|
433
|
+
total = 0
|
|
434
|
+
truncated = False
|
|
435
|
+
for relative, stats in mount.walk("", args.max_scan, ignored):
|
|
436
|
+
if len(files) >= args.max_files:
|
|
437
|
+
truncated = True
|
|
438
|
+
break
|
|
439
|
+
entry = {"path": relative, "size": stats.st_size}
|
|
440
|
+
if stats.st_size <= args.max_bytes:
|
|
441
|
+
digest = hashlib.sha256()
|
|
442
|
+
with open(os.path.join(mount.root, *relative.split("/")), "rb") as handle:
|
|
443
|
+
while True:
|
|
444
|
+
chunk = handle.read(1 << 16)
|
|
445
|
+
if not chunk:
|
|
446
|
+
break
|
|
447
|
+
digest.update(chunk)
|
|
448
|
+
entry["sha256"] = digest.hexdigest()
|
|
449
|
+
total += stats.st_size
|
|
450
|
+
files.append(entry)
|
|
451
|
+
return {"files": files, "ignored": ignored, "truncated": truncated, "totalBytes": total}
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def build_parser():
|
|
455
|
+
parser = argparse.ArgumentParser(prog="agent-fs", add_help=False)
|
|
456
|
+
sub = parser.add_subparsers(dest="operation")
|
|
457
|
+
|
|
458
|
+
def common(target, writable=False):
|
|
459
|
+
target.add_argument("--mount", required=True)
|
|
460
|
+
target.add_argument("--writable", action="store_true")
|
|
461
|
+
target.add_argument("--max-scan", type=int, default=200000)
|
|
462
|
+
target.add_argument("--max-files", type=int, default=5000)
|
|
463
|
+
target.add_argument("--max-bytes", type=int, default=1048576)
|
|
464
|
+
|
|
465
|
+
sub.add_parser("version")
|
|
466
|
+
listing = sub.add_parser("list")
|
|
467
|
+
common(listing)
|
|
468
|
+
listing.add_argument("--path")
|
|
469
|
+
listing.add_argument("--glob")
|
|
470
|
+
listing.add_argument("--limit", type=int)
|
|
471
|
+
|
|
472
|
+
read = sub.add_parser("read")
|
|
473
|
+
common(read)
|
|
474
|
+
read.add_argument("--path", required=True)
|
|
475
|
+
read.add_argument("--start-line", type=int)
|
|
476
|
+
read.add_argument("--line-count", type=int)
|
|
477
|
+
read.add_argument("--artifact-dir")
|
|
478
|
+
|
|
479
|
+
search = sub.add_parser("search")
|
|
480
|
+
common(search)
|
|
481
|
+
search.add_argument("--query", required=True)
|
|
482
|
+
search.add_argument("--glob")
|
|
483
|
+
search.add_argument("--case-sensitive", action="store_true")
|
|
484
|
+
search.add_argument("--limit", type=int)
|
|
485
|
+
search.add_argument("--max-results", type=int, default=200)
|
|
486
|
+
search.add_argument("--max-scan-bytes", type=int, default=52428800)
|
|
487
|
+
|
|
488
|
+
write = sub.add_parser("write")
|
|
489
|
+
common(write)
|
|
490
|
+
write.add_argument("--path", required=True)
|
|
491
|
+
write.add_argument("--source", required=True)
|
|
492
|
+
write.add_argument("--encoding", default="utf-8", choices=["utf-8", "base64"])
|
|
493
|
+
|
|
494
|
+
delete = sub.add_parser("delete")
|
|
495
|
+
common(delete)
|
|
496
|
+
delete.add_argument("--path", required=True)
|
|
497
|
+
|
|
498
|
+
snapshot = sub.add_parser("snapshot")
|
|
499
|
+
common(snapshot)
|
|
500
|
+
return parser
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
OPERATIONS = {
|
|
504
|
+
"list": op_list,
|
|
505
|
+
"read": op_read,
|
|
506
|
+
"search": op_search,
|
|
507
|
+
"write": op_write,
|
|
508
|
+
"delete": op_delete,
|
|
509
|
+
"snapshot": op_snapshot,
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def main(argv):
|
|
514
|
+
parser = build_parser()
|
|
515
|
+
try:
|
|
516
|
+
args = parser.parse_args(argv)
|
|
517
|
+
except SystemExit:
|
|
518
|
+
emit({"protocolVersion": PROTOCOL_VERSION, "error": {"code": "usage", "message": "Invalid arguments."}})
|
|
519
|
+
return 2
|
|
520
|
+
if args.operation == "version":
|
|
521
|
+
emit({"protocolVersion": PROTOCOL_VERSION, "version": HELPER_VERSION})
|
|
522
|
+
return 0
|
|
523
|
+
operation = OPERATIONS.get(args.operation)
|
|
524
|
+
if operation is None:
|
|
525
|
+
emit({"protocolVersion": PROTOCOL_VERSION, "error": {"code": "usage", "message": "Unknown operation."}})
|
|
526
|
+
return 2
|
|
527
|
+
for name in ("max_scan", "max_files", "max_bytes"):
|
|
528
|
+
value = getattr(args, name, None)
|
|
529
|
+
if value is not None and value <= 0:
|
|
530
|
+
emit({"protocolVersion": PROTOCOL_VERSION, "error": {"code": "usage", "message": "Limits must be positive."}})
|
|
531
|
+
return 2
|
|
532
|
+
for name in ("limit", "start_line", "line_count", "max_results", "max_scan_bytes"):
|
|
533
|
+
value = getattr(args, name, None)
|
|
534
|
+
if value is not None and value <= 0:
|
|
535
|
+
emit({"protocolVersion": PROTOCOL_VERSION, "error": {"code": "usage", "message": "%s must be positive." % name}})
|
|
536
|
+
return 2
|
|
537
|
+
try:
|
|
538
|
+
mount = Mount(args.mount, args.writable)
|
|
539
|
+
result = operation(mount, args)
|
|
540
|
+
result["protocolVersion"] = PROTOCOL_VERSION
|
|
541
|
+
emit(result)
|
|
542
|
+
return 0
|
|
543
|
+
except HelperError as error:
|
|
544
|
+
emit({"protocolVersion": PROTOCOL_VERSION, "error": {"code": error.code, "message": str(error)}})
|
|
545
|
+
return error.exit_code
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def emit(document):
|
|
549
|
+
sys.stdout.write(json.dumps(document, separators=(",", ":")))
|
|
550
|
+
sys.stdout.write("\n")
|
|
551
|
+
sys.stdout.flush()
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
if __name__ == "__main__":
|
|
555
|
+
sys.exit(main(sys.argv[1:]))
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { type SandboxCommand, type SandboxFileInfo, type SandboxHandle, type SandboxInputFile, type SandboxProcessEvent, type SandboxProvider, type SandboxProviderCapabilities, type SandboxSpec } from "./contracts.js";
|
|
2
|
+
export interface BubblewrapSandboxProviderOptions {
|
|
3
|
+
/** bubblewrap binary. Defaults to "bwrap" on PATH. */
|
|
4
|
+
binary?: string;
|
|
5
|
+
/** util-linux prlimit binary used for resource limits. Defaults to "prlimit". */
|
|
6
|
+
prlimitBinary?: string;
|
|
7
|
+
/**
|
|
8
|
+
* Host directories bound read-only into every sandbox. Defaults to the
|
|
9
|
+
* system directories needed to run installed software: /usr, /bin, /sbin,
|
|
10
|
+
* /lib*, and the dynamic-loader configuration under /etc.
|
|
11
|
+
*/
|
|
12
|
+
binds?: string[];
|
|
13
|
+
/** Host directory that holds each sandbox's working directory. Defaults to the OS temporary directory. */
|
|
14
|
+
stateDirectory?: string;
|
|
15
|
+
/** Environment variables set inside every sandbox in addition to command environment. */
|
|
16
|
+
environment?: Record<string, string>;
|
|
17
|
+
now?: () => Date;
|
|
18
|
+
}
|
|
19
|
+
export declare const DEFAULT_BUBBLEWRAP_BINDS: string[];
|
|
20
|
+
/**
|
|
21
|
+
* A local sandbox provider built on bubblewrap (bwrap): separate user, PID,
|
|
22
|
+
* IPC, UTS, cgroup, and network namespaces, read-only binds of host system
|
|
23
|
+
* directories, a private /workspace backed by a host directory the provider
|
|
24
|
+
* owns, and prlimit-enforced memory, CPU, process, and file-size limits.
|
|
25
|
+
* Requires Linux with unprivileged user namespaces. It runs without a
|
|
26
|
+
* container daemon and is the reference provider for local development and
|
|
27
|
+
* continuous integration.
|
|
28
|
+
*/
|
|
29
|
+
export declare class BubblewrapSandboxProvider implements SandboxProvider {
|
|
30
|
+
#private;
|
|
31
|
+
readonly name = "bubblewrap";
|
|
32
|
+
readonly capabilities: SandboxProviderCapabilities;
|
|
33
|
+
constructor(options?: BubblewrapSandboxProviderOptions);
|
|
34
|
+
/** Confirm bubblewrap can create an isolated sandbox on this host. */
|
|
35
|
+
probe(options?: {
|
|
36
|
+
signal?: AbortSignal;
|
|
37
|
+
}): Promise<void>;
|
|
38
|
+
/** True when prlimit is available and resource limits are enforced. */
|
|
39
|
+
get limitsEnforced(): boolean | undefined;
|
|
40
|
+
validate(spec: SandboxSpec, options?: {
|
|
41
|
+
signal?: AbortSignal;
|
|
42
|
+
}): Promise<void>;
|
|
43
|
+
create(spec: SandboxSpec, options?: {
|
|
44
|
+
signal?: AbortSignal;
|
|
45
|
+
}): Promise<SandboxHandle>;
|
|
46
|
+
putFiles(handle: SandboxHandle, files: SandboxInputFile[], options?: {
|
|
47
|
+
signal?: AbortSignal;
|
|
48
|
+
}): Promise<void>;
|
|
49
|
+
execute(handle: SandboxHandle, command: SandboxCommand, options?: {
|
|
50
|
+
signal?: AbortSignal;
|
|
51
|
+
}): AsyncIterable<SandboxProcessEvent>;
|
|
52
|
+
listFiles(handle: SandboxHandle, directory: string, options?: {
|
|
53
|
+
signal?: AbortSignal;
|
|
54
|
+
}): Promise<SandboxFileInfo[]>;
|
|
55
|
+
readFile(handle: SandboxHandle, filePath: string, options?: {
|
|
56
|
+
signal?: AbortSignal;
|
|
57
|
+
}): Promise<Uint8Array>;
|
|
58
|
+
terminate(handle: SandboxHandle): Promise<void>;
|
|
59
|
+
}
|