@capybara-hq/plugin-sdk 0.1.0-rc.79 → 0.1.0-rc.80

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/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const SDK_VERSION = "0.1.0-rc.79";
1
+ export declare const SDK_VERSION = "0.1.0-rc.80";
2
2
  export * from "./agent-template.js";
3
3
  export * from "./avatar-presets.js";
4
4
  export * from "./bootstrap.js";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export const SDK_VERSION = "0.1.0-rc.79";
1
+ export const SDK_VERSION = "0.1.0-rc.80";
2
2
  export * from "./agent-template.js";
3
3
  export * from "./avatar-presets.js";
4
4
  export * from "./bootstrap.js";
@@ -37,8 +37,7 @@ export interface SandboxRuntimeFile {
37
37
  *
38
38
  * A runtime change therefore lands in three steps (tools/checks/README.md, "Changing the SDK
39
39
  * runtime sources"): `current` first, then the provider restages, then core promotes `current` to
40
- * `files` with the pin. Between changes `current` is `files`; now `native-files.py` is ahead
41
- * (core#907: `NOT_REGULAR_FILE`).
40
+ * `files` with the pin. Between changes, as now, `current` is `files`.
42
41
  */
43
42
  export declare const SANDBOX_RUNTIME_SOURCE: {
44
43
  readonly version: number;
@@ -1,13 +1,5 @@
1
1
  import { LINUX_SANDBOX_SOURCE } from "./sandbox-linux-runtime-source.js";
2
2
  import { NATIVE_FILES_SOURCE } from "./sandbox-native-runtime-source.js";
3
- import { NATIVE_FILES_STAGED_SOURCE } from "./sandbox-native-staged-runtime-source.js";
4
- /** The staged helper: answers a non-regular file with the generic `INVALID_NATIVE_REQUEST`. */
5
- const NATIVE_FILES_STAGED = Object.freeze({
6
- name: "native-files.py",
7
- source: NATIVE_FILES_STAGED_SOURCE,
8
- sha256: "c1712198af4ffedc0b48f789c28ed4233dc9008521b897300731c4f903168950",
9
- });
10
- /** The current helper: answers a non-regular file with `NOT_REGULAR_FILE` (core#907). */
11
3
  const NATIVE_FILES = Object.freeze({
12
4
  name: "native-files.py",
13
5
  source: NATIVE_FILES_SOURCE,
@@ -19,17 +11,17 @@ const LINUX_SANDBOX = Object.freeze({
19
11
  sha256: "ceb5bb0971437978a7695091792bfafcf3dbf2e7c74e8425d8aceb76e442f848",
20
12
  features: Object.freeze(["fileReadRoots"]),
21
13
  });
22
- const STAGED = Object.freeze([NATIVE_FILES_STAGED, LINUX_SANDBOX]);
23
- const CURRENT = Object.freeze([NATIVE_FILES, LINUX_SANDBOX]);
14
+ const STAGED = Object.freeze([NATIVE_FILES, LINUX_SANDBOX]);
15
+ const CURRENT = STAGED;
24
16
  /**
25
17
  * Digests of earlier revisions a staged copy may still have (one previous revision at most):
26
18
  * device containers made from an earlier image keep their staged runtime until recreated. The
27
- * launcher before exact file read roots (core#742); the next runtime change drops it.
19
+ * native helper before `NOT_REGULAR_FILE` (core#907); the next runtime change drops it.
28
20
  */
29
21
  const PREVIOUS = Object.freeze([
30
22
  Object.freeze({
31
- name: "linux-sandbox.py",
32
- sha256: "4e046df902dc644532ada9f2a3bef30a983daf7d1f238bd46dcd16524d96c66c",
23
+ name: "native-files.py",
24
+ sha256: "c1712198af4ffedc0b48f789c28ed4233dc9008521b897300731c4f903168950",
33
25
  }),
34
26
  ]);
35
27
  function acceptedDigests(...sets) {
@@ -71,8 +63,7 @@ function acceptedDigests(...sets) {
71
63
  *
72
64
  * A runtime change therefore lands in three steps (tools/checks/README.md, "Changing the SDK
73
65
  * runtime sources"): `current` first, then the provider restages, then core promotes `current` to
74
- * `files` with the pin. Between changes `current` is `files`; now `native-files.py` is ahead
75
- * (core#907: `NOT_REGULAR_FILE`).
66
+ * `files` with the pin. Between changes, as now, `current` is `files`.
76
67
  */
77
68
  export const SANDBOX_RUNTIME_SOURCE = Object.freeze({
78
69
  version: 2,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/plugin-sdk",
3
- "version": "0.1.0-rc.79",
3
+ "version": "0.1.0-rc.80",
4
4
  "description": "Capybara plugin SDK: the types and pure functions plugins are written against",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -1,11 +0,0 @@
1
- /**
2
- * The `native-files.py` that released image providers stage (device-docker's image) and that
3
- * providers uploading the staged set at runtime (device-e2b) run, kept byte for byte while the
4
- * SDK's current helper (`sandbox-native-runtime-source.ts`) is ahead of them:
5
- * `SANDBOX_RUNTIME_SOURCE.files` lists these bytes, so a provider that checks its staged copy
6
- * against the host SDK keeps working until it restages and core moves its pin (see
7
- * `SANDBOX_RUNTIME_SOURCE` and tools/checks/README.md, "Changing the SDK runtime sources"). The
8
- * text is inlined, not composed, so nothing else in the SDK can change these bytes. Never edit it;
9
- * the promotion that makes the current helper the staged one deletes this file.
10
- */
11
- export declare const NATIVE_FILES_STAGED_SOURCE: string;
@@ -1,592 +0,0 @@
1
- /**
2
- * The `native-files.py` that released image providers stage (device-docker's image) and that
3
- * providers uploading the staged set at runtime (device-e2b) run, kept byte for byte while the
4
- * SDK's current helper (`sandbox-native-runtime-source.ts`) is ahead of them:
5
- * `SANDBOX_RUNTIME_SOURCE.files` lists these bytes, so a provider that checks its staged copy
6
- * against the host SDK keeps working until it restages and core moves its pin (see
7
- * `SANDBOX_RUNTIME_SOURCE` and tools/checks/README.md, "Changing the SDK runtime sources"). The
8
- * text is inlined, not composed, so nothing else in the SDK can change these bytes. Never edit it;
9
- * the promotion that makes the current helper the staged one deletes this file.
10
- */
11
- export const NATIVE_FILES_STAGED_SOURCE = String.raw `import base64
12
- import contextlib
13
- import errno
14
- import fcntl
15
- import json
16
- import os
17
- import re
18
- import stat
19
- import sys
20
- import time
21
- import urllib.parse
22
-
23
- MAX_DEPTH = 2
24
- MAX_VISITS = 500
25
- MAX_RESULTS = 50
26
- MAX_NAME = 64
27
- SKIP_ANY = ["node_modules"]
28
- SKIP_BASE = ["Library"]
29
- # How long a write waits for a guarded move of the device (which holds the device's files lock
30
- # exclusively for a few renames) before it fails with EBUSY: only a lock held from outside every
31
- # sandbox (Full work of the owner) can take that long.
32
- SHARED_WAIT_S = 30
33
- # A test seam (pause_mkdir): a write creating that directory pauses PAUSE_S between its check and
34
- # its mkdir, announced by PAUSE_MARKER in the parent. Never set in production.
35
- PAUSE_S = 2
36
- PAUSE_MARKER = ".capybara-test-paused"
37
- # ECMAScript whitespace (Python's str.strip also removes several extra control characters).
38
- SPACE = "\u0009\u000a\u000b\u000c\u000d\u0020\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff"
39
-
40
- # Restricted roots ({"denyWrites": true}) follow the shared write policy (sandbox-write-denies.ts).
41
-
42
- import unicodedata as _unicodedata
43
- WRITE_DENIES = [[_unicodedata.normalize("NFKC", n).casefold() for n in e] for e in [[".gitconfig"],[".gitmodules"],[".bashrc"],[".bash_profile"],[".zshrc"],[".zprofile"],[".profile"],[".ripgreprc"],[".mcp.json"],[".envrc"],[".npmrc"],[".vscode"],[".idea"],[".claude","commands"],[".claude","agents"],[".husky"],[".huskyrc"],[".huskyrc.json"],[".huskyrc.js"],["husky.config.js"],[".pre-commit-config.yaml"],[".pre-commit-config.yml"],["lefthook.yml"],["lefthook.yaml"],["lefthook.json"],["lefthook.toml"],[".lefthook.yml"],[".lefthook.yaml"],[".lefthook.json"],[".lefthook.toml"],["lefthook-local.yml"],["lefthook-local.yaml"],["lefthook-local.json"],["lefthook-local.toml"],[".lefthook-local.yml"],[".lefthook-local.yaml"],[".lefthook-local.json"],[".lefthook-local.toml"],[".lefthook"],[".lefthook-local"],[".config","lefthook.yml"],[".config","lefthook.yaml"],[".config","lefthook.json"],[".config","lefthook.toml"],[".overcommit.yml"],[".simple-git-hooks.json"],[".simple-git-hooks.js"],[".simple-git-hooks.cjs"],["simple-git-hooks.json"],["simple-git-hooks.js"],["simple-git-hooks.cjs"],[".githooks"],[".zshenv"],[".zlogin"],[".zlogout"],[".bash_login"],[".bash_logout"],[".logout"],[".tcshrc"],[".cshrc"],[".kshrc"],[".config","git","config"],[".config","fish","config.fish"],[".config","fish","conf.d"],["library","launchagents"],["library","launchdaemons"],[".config","systemd"],[".local","share","systemd"],[".config","environment.d"],[".config","autostart"],[".config","autostart-scripts"],[".config","plasma-workspace","env"],[".xprofile"],[".xsessionrc"],[".local","bin"],[".cargo","bin"]]]
44
- SYSTEM_WRITE_DENIES = [[_unicodedata.normalize("NFKC", n).casefold() for n in p.split("/") if n] for p in ["/var/spool/cron","/var/spool/at","/private/var/at/tabs","/private/var/at/jobs","/var/at"]]
45
- PREFIX_GUARDED = [(e, False) for e in WRITE_DENIES if len(e) > 1] + [(e, True) for e in SYSTEM_WRITE_DENIES]
46
- GIT_ALLOWED_DIRECTORIES = set(["objects","refs","logs","rebase-merge","rebase-apply","sequencer"])
47
- GIT_ALLOWED_FILES = set(["index","head","orig_head","fetch_head","merge_head","merge_msg","merge_mode","merge_rr","auto_merge","cherry_pick_head","revert_head","rebase_head","bisect_log","bisect_start","bisect_expected_rev","bisect_ancestors_ok","bisect_names","bisect_terms","packed-refs","packed-refs.new","merge_autostash","commit_editmsg","tag_editmsg","squash_msg","shallow","description","gc.pid","gc.log","info","modules","worktrees"])
48
- GIT_DANGER = set(["config","config.worktree","commondir","gitdir","hooks","info"])
49
- PROTECTED_PATH_NAMES = set([".git",".gitconfig",".gitmodules",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",".ripgreprc",".mcp.json",".envrc",".npmrc",".vscode",".idea",".husky",".huskyrc",".huskyrc.json",".huskyrc.js","husky.config.js",".pre-commit-config.yaml",".pre-commit-config.yml","lefthook.yml","lefthook.yaml","lefthook.json","lefthook.toml",".lefthook.yml",".lefthook.yaml",".lefthook.json",".lefthook.toml","lefthook-local.yml","lefthook-local.yaml","lefthook-local.json","lefthook-local.toml",".lefthook-local.yml",".lefthook-local.yaml",".lefthook-local.json",".lefthook-local.toml",".lefthook",".lefthook-local",".overcommit.yml",".simple-git-hooks.json",".simple-git-hooks.js",".simple-git-hooks.cjs","simple-git-hooks.json","simple-git-hooks.js","simple-git-hooks.cjs",".githooks",".zshenv",".zlogin",".zlogout",".bash_login",".bash_logout",".logout",".tcshrc",".cshrc",".kshrc",".xprofile",".xsessionrc"])
50
- RESERVED_NAME_PREFIX = ".capybara-staging-"
51
-
52
-
53
- def _fold_parts(path):
54
- return [_unicodedata.normalize("NFKC", p).casefold() for p in path.split("/") if p]
55
-
56
-
57
- def _holds_head(head, prefix):
58
- if head == "logs":
59
- return not prefix or (len(prefix) == 3 and prefix[0] == "refs" and prefix[1] == "remotes")
60
- if head == "refs":
61
- return len(prefix) == 2 and prefix[0] == "remotes"
62
- return head == "sequencer" and not prefix
63
-
64
-
65
- def _subtree_allowed(head, rest):
66
- for k, name in enumerate(rest):
67
- if name == ".git":
68
- return False
69
- if name == "head" and not (k == len(rest) - 1 and _holds_head(head, rest[:k])):
70
- return False
71
- if name in ("objects", "commondir", "gitdir") and _holds_head(head, rest[:k]):
72
- return False
73
- return True
74
-
75
-
76
- def _git_internal_allowed(rel):
77
- if not rel:
78
- return True
79
- head = rel[0]
80
- if head in GIT_ALLOWED_DIRECTORIES:
81
- return _subtree_allowed(head, rel[1:])
82
- if head in ("modules", "worktrees") and len(rel) > 1:
83
- rest = rel[1:]
84
- if head == "worktrees":
85
- return _git_internal_allowed(rest[1:])
86
- readings = [rest[k + 1:] for k in range(len(rest))]
87
- if any(r and r[0] in GIT_DANGER and not _git_internal_allowed(r) for r in readings):
88
- return False
89
- return any(r and _git_internal_allowed(r) for r in readings)
90
- if len(rel) == 1:
91
- base = head[:-5] if head.endswith(".lock") else head
92
- stash = base.startswith("index.stash.") and base[12:].isascii() and base[12:].isdigit()
93
- return base in GIT_ALLOWED_FILES or stash
94
- return head == "info" and len(rel) == 2 and rel[1] in ("exclude", "exclude.lock")
95
-
96
-
97
- def write_denied(path):
98
- names = _fold_parts(path)
99
- if any(n.startswith(RESERVED_NAME_PREFIX) for n in names):
100
- return True
101
- for system in SYSTEM_WRITE_DENIES:
102
- if names[:len(system)] == system:
103
- return True
104
- for entry in WRITE_DENIES:
105
- for i in range(len(names) - len(entry) + 1):
106
- if names[i:i + len(entry)] == entry:
107
- return True
108
- if ".git" in names:
109
- return not _git_internal_allowed(names[names.index(".git") + 1:])
110
- return bool(names) and names[-1] == "head"
111
-
112
-
113
- def _prefix_next(dst):
114
- nxt = []
115
- for names, anchored in PREFIX_GUARDED:
116
- for k in range(1, len(names)):
117
- if (anchored and len(dst) != k) or len(dst) < k:
118
- continue
119
- if dst[len(dst) - k:] == names[:k]:
120
- nxt.append(names[k])
121
- return nxt
122
-
123
-
124
- def move_denied(source, destination, is_dir, entries=None):
125
- if write_denied(source) or write_denied(destination):
126
- return True
127
- src, dst = _fold_parts(source), _fold_parts(destination)
128
- # an anchored deny's ancestor never moves away: a link resolved into it would dangle
129
- for names, anchored in PREFIX_GUARDED:
130
- if anchored and len(src) < len(names) and names[:len(src)] == src:
131
- return True
132
- nxt = _prefix_next(dst)
133
- if nxt:
134
- if not is_dir:
135
- return True
136
- if entries is None:
137
- # no entries given: list the source path itself, refusing what cannot be listed
138
- try:
139
- import os as _os
140
- entries = _os.listdir(source)
141
- except OSError:
142
- return True
143
- if any(_unicodedata.normalize("NFKC", n).casefold() in nxt for n in entries):
144
- return True
145
-
146
- def protected_at(names):
147
- return next((k for k, n in enumerate(names) if n in PROTECTED_PATH_NAMES), -1)
148
-
149
- def same_prefix(n):
150
- return n >= 0 and len(dst) > n + 1 and dst[:n + 1] == src[:n + 1]
151
- i = protected_at(src)
152
- if i >= 0 and not same_prefix(i):
153
- return True
154
- j = protected_at(dst)
155
- if is_dir and j >= 0 and not (i == j and same_prefix(j)):
156
- return True
157
- return (not is_dir) and bool(dst) and dst[-1] == ".git"
158
-
159
-
160
- class ScopeDenied(Exception):
161
- pass
162
-
163
- def units(value):
164
- return value.encode("utf-16-be", "surrogatepass")
165
-
166
- def valid_path(path):
167
- if not isinstance(path, str) or not path.startswith("/") or len(units(path)) > 8192:
168
- return False
169
- if "\\" in path or "//" in path or re.search(r"[\x00-\x1f\x7f]", path):
170
- return False
171
- for part in path.split("/"):
172
- try:
173
- # decodeURIComponent rejects the entire segment on malformed escapes or UTF-8.
174
- if re.search(r"%(?![0-9a-fA-F]{2})", part):
175
- raise ValueError("Malformed percent escape")
176
- decoded = urllib.parse.unquote(part, errors="strict")
177
- except (UnicodeError, ValueError):
178
- decoded = part
179
- if decoded == ".." or "/" in decoded or "\\" in decoded:
180
- return False
181
- return True
182
-
183
- def within(root, path):
184
- return root == "/" or path == root or path.startswith(root + "/")
185
-
186
- def valid_name(name):
187
- return (name not in ("", ".", "..") and len(units(name)) <= MAX_NAME * 2
188
- and not re.search(r"[\x00-\x1f\x7f/]", name)
189
- and name[0] not in SPACE and name[-1] not in SPACE)
190
-
191
- class DeviceFilesLock:
192
- """The device's files lock, shared by every operation of the device: an flock on a file outside
193
- every sandbox, inherited as a descriptor ("filesLockFd") that the restricted command never
194
- holds. Every acquisition reopens it through /proc/self/fd (this process is non-dumpable, so no
195
- other process can), because flock belongs to an open file description: each holder needs its
196
- own. The launcher's broker and the device agent's native writes take it. Shared and exclusive acquisitions both poll without blocking up to their bound, so a
197
- waiting exclusive holder never holds back new shared ones (as in the launcher's in-process SharedLock)."""
198
-
199
- def __init__(self, fd):
200
- self.fd = fd
201
-
202
- def acquire(self, mode, timeout, message):
203
- fd = os.open("/proc/self/fd/%d" % self.fd, os.O_RDONLY | os.O_CLOEXEC)
204
- deadline = time.monotonic() + timeout
205
- delay = 0.0005
206
- while True:
207
- try:
208
- fcntl.flock(fd, mode | fcntl.LOCK_NB)
209
- return fd
210
- except OSError as error:
211
- if error.errno not in (errno.EWOULDBLOCK, errno.EAGAIN, errno.EINTR):
212
- os.close(fd)
213
- raise
214
- if time.monotonic() >= deadline:
215
- os.close(fd)
216
- raise OSError(errno.EBUSY, message)
217
- time.sleep(delay)
218
- delay = min(delay * 2, 0.005)
219
-
220
- @contextlib.contextmanager
221
- def shared(self):
222
- fd = self.acquire(fcntl.LOCK_SH, SHARED_WAIT_S, "A guarded move of the device did not end")
223
- try:
224
- yield
225
- finally:
226
- os.close(fd) # closing the last descriptor of the description releases the lock
227
-
228
- @contextlib.contextmanager
229
- def exclusive(self, timeout):
230
- """Raises EBUSY when the shared holders do not leave within timeout seconds."""
231
- fd = self.acquire(fcntl.LOCK_EX, timeout, "The device's other writes did not finish")
232
- try:
233
- yield
234
- finally:
235
- os.close(fd)
236
-
237
-
238
- class NativeFiles:
239
- def __init__(self, roots):
240
- self.roots = roots
241
- self.deny_writes = roots.get("denyWrites") is True
242
- self.pause_mkdir = None
243
- # The device's files lock (DeviceFilesLock), held shared by a write from its check to its
244
- # effect; set by a consumer serving one device's operations, never by the transport.
245
- self.files_lock = None
246
- # Descriptors are supplied by the trusted consumer, never reopened by root pathname.
247
- for root in roots["read"] + roots["write"]:
248
- if not valid_path(root["path"]) or os.path.normpath(root["path"]) != root["path"]:
249
- raise ValueError("Supply canonical absolute root paths")
250
- if root.get("file") is True and (root in roots["write"] or root["path"] == "/"):
251
- raise ValueError("Only a read root may be a single file")
252
- if not stat.S_ISDIR(os.fstat(root["fd"]).st_mode):
253
- raise ValueError("Supply pinned directory descriptors")
254
-
255
- def parent(self, path, write=False, create=False):
256
- fd, name, _, _ = self.resolve(path, write, create, 0, False)
257
- return fd, name
258
-
259
- def resolve(self, path, write, create, links, must_exist):
260
- if not valid_path(path):
261
- raise ValueError("Supply a valid absolute native path")
262
- path = os.path.normpath(path)
263
- if write and self.deny_writes and write_denied(path):
264
- raise ScopeDenied("Native path is a protected write target")
265
- roots = self.roots["write"] if write else self.roots["read"] + self.roots["write"]
266
- matches = [root for root in roots if within(root["path"], path)]
267
- if not matches:
268
- raise ScopeDenied("Native path is outside the supplied roots")
269
- root = max(matches, key=lambda entry: len(entry["path"]))
270
- fd = os.dup(root["fd"])
271
- current = root["path"]
272
- parts = os.path.relpath(path, current).split("/")
273
- if root.get("file") is True:
274
- # a single-file root: walked from its parent directory, so the file's own name is
275
- # the first component (anything below it is no directory, so missing for a reader)
276
- current = os.path.dirname(root["path"])
277
- parts = [os.path.basename(root["path"])] + ([] if path == root["path"] else parts)
278
- result = self.walk(fd, current, parts, write, create, links, must_exist)
279
- if write and self.deny_writes and write_denied(result[2]):
280
- os.close(result[0])
281
- raise ScopeDenied("Native path is a protected write target")
282
- return result
283
-
284
- def walk(self, fd, current, parts, write, create, links, must_exist):
285
- try:
286
- for index, name in enumerate(parts):
287
- final = index == len(parts) - 1
288
- try:
289
- info = os.stat(name, dir_fd=fd, follow_symlinks=False)
290
- except FileNotFoundError:
291
- if not final and create:
292
- if self.deny_writes and write_denied(os.path.join(current, name)):
293
- raise ScopeDenied("Native path is a protected write target")
294
- if self.pause_mkdir is not None and name == self.pause_mkdir:
295
- os.close(os.open(PAUSE_MARKER, os.O_WRONLY | os.O_CREAT | os.O_EXCL,
296
- 0o644, dir_fd=fd))
297
- time.sleep(PAUSE_S)
298
- try:
299
- os.mkdir(name, 0o755, dir_fd=fd)
300
- made = True
301
- except FileExistsError:
302
- made = False
303
- info = os.stat(name, dir_fd=fd, follow_symlinks=False)
304
- if made:
305
- self.settle(fd, name, (info.st_dev, info.st_ino), True)
306
- elif final and not must_exist:
307
- return fd, name, os.path.normpath(os.path.join(current, name)), links
308
- else:
309
- raise
310
- if stat.S_ISLNK(info.st_mode):
311
- if links >= 40:
312
- raise OSError(errno.ELOOP, "Too many symbolic links")
313
- target = os.readlink(name, dir_fd=fd)
314
- after = os.stat(name, dir_fd=fd, follow_symlinks=False)
315
- if (info.st_dev, info.st_ino) != (after.st_dev, after.st_ino):
316
- raise ScopeDenied("Native path changed during resolution")
317
- target = os.path.normpath(os.path.join(current, target))
318
- os.close(fd)
319
- fd = None
320
- # Resolve the target once. Writes require an existing target; the returned
321
- # descriptor/name is reused, including when a directory has a suffix to walk.
322
- fd, linked_name, resolved, links = self.resolve(
323
- target, write, False, links + 1, must_exist or write)
324
- if final:
325
- return fd, linked_name, resolved, links
326
- try:
327
- child = os.open(linked_name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW,
328
- dir_fd=fd)
329
- except NotADirectoryError:
330
- if not write:
331
- raise FileNotFoundError(errno.ENOENT, "Native target does not exist")
332
- raise
333
- os.close(fd)
334
- fd = None
335
- return self.walk(child, resolved, parts[index + 1:], write, create,
336
- links, must_exist)
337
- if final:
338
- return fd, name, os.path.normpath(os.path.join(current, name)), links
339
- if not write and not stat.S_ISDIR(info.st_mode):
340
- # Existing readers treat ENOTDIR in an ancestor as a missing target.
341
- raise FileNotFoundError(errno.ENOENT, "Native target does not exist")
342
- child = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd)
343
- os.close(fd)
344
- fd = child
345
- current = os.path.join(current, name)
346
- except BaseException:
347
- if fd is not None:
348
- os.close(fd)
349
- raise
350
-
351
- # ---- post-effect verification (restricted roots) -----------------------------------------
352
- # A write is checked on the path its parent had, then applied through the parent descriptor.
353
- # The device's files lock keeps sandboxed guarded moves out of that window; a process outside
354
- # the sandbox can still move the parent meanwhile. So each entry this helper creates is checked
355
- # again at its parent's current place (Linux /proc; elsewhere there is no such check) and
356
- # undone when it landed at a protected path.
357
-
358
- def placed(self, fd, name):
359
- """name below fd at fd's current path, mapped onto the roots' recorded paths; None where
360
- that cannot be told (no /proc) or the directory is gone."""
361
- try:
362
- where = os.readlink("/proc/self/fd/%d" % fd)
363
- except OSError:
364
- return None
365
- if not where.startswith("/") or where.endswith(" (deleted)"):
366
- return None
367
- best = None
368
- for root in self.roots["read"] + self.roots["write"]:
369
- if root.get("file") is True:
370
- continue # its descriptor is the parent directory, not the root's path
371
- try:
372
- now = os.readlink("/proc/self/fd/%d" % root["fd"]).rstrip("/")
373
- except OSError:
374
- continue
375
- if where == now or where.startswith(now + "/"):
376
- if best is None or len(now) > best[0]:
377
- best = (len(now), root["path"].rstrip("/") + where[len(now):])
378
- where = best[1] if best else where
379
- return where.rstrip("/") + "/" + name
380
-
381
- def landed_denied(self, fd, name, is_dir):
382
- now = self.placed(fd, name) if self.deny_writes else None
383
- return now is not None and (write_denied(now) or (
384
- not is_dir and _fold_parts(name) == [".git"]))
385
-
386
- def settle(self, fd, name, made, is_dir):
387
- """Undoes the entry this helper made below fd (made: its (st_dev, st_ino)) when it now
388
- sits at a protected path, and refuses."""
389
- if not self.landed_denied(fd, name, is_dir):
390
- return
391
- try:
392
- info = os.stat(name, dir_fd=fd, follow_symlinks=False)
393
- if (info.st_dev, info.st_ino) != made:
394
- raise OSError(errno.ESTALE, "The created entry was replaced")
395
- if is_dir:
396
- os.rmdir(name, dir_fd=fd)
397
- else:
398
- os.unlink(name, dir_fd=fd)
399
- except OSError:
400
- raise ScopeDenied("A native write landed at a protected path and could not be undone")
401
- raise ScopeDenied("Native path became a protected write target")
402
-
403
- def open(self, path, write=False, directory=False):
404
- parent, name = self.parent(path, write, write)
405
- try:
406
- if write and self.deny_writes and _fold_parts(name) == [".git"]:
407
- os.close(parent)
408
- parent = None
409
- raise ScopeDenied("A file named .git would point git elsewhere")
410
- flags = os.O_NOFOLLOW | os.O_NONBLOCK
411
- flags |= os.O_WRONLY | os.O_CREAT if write else os.O_RDONLY
412
- if directory:
413
- flags |= os.O_DIRECTORY
414
- if not write:
415
- return os.open(name, flags, 0o600, dir_fd=parent)
416
- try:
417
- os.stat(name, dir_fd=parent, follow_symlinks=False)
418
- existed = True
419
- except FileNotFoundError:
420
- existed = False
421
- fd = os.open(name, flags, 0o600, dir_fd=parent)
422
- try:
423
- if existed:
424
- # nothing was made: refused before any byte changes (the caller truncates)
425
- if self.landed_denied(parent, name, False):
426
- raise ScopeDenied("Native path became a protected write target")
427
- else:
428
- info = os.fstat(fd)
429
- self.settle(parent, name, (info.st_dev, info.st_ino), False)
430
- except BaseException:
431
- os.close(fd)
432
- raise
433
- return fd
434
- finally:
435
- if parent is not None:
436
- os.close(parent)
437
-
438
- def metadata(self, path):
439
- parent, name = self.parent(path)
440
- try:
441
- value = os.stat(name, dir_fd=parent, follow_symlinks=False)
442
- if stat.S_ISLNK(value.st_mode):
443
- raise ScopeDenied("Native path changed during resolution")
444
- return value
445
- finally:
446
- os.close(parent)
447
-
448
- def entries(self, fd):
449
- # Dirent type data works even when child metadata cannot be searched. If the
450
- # filesystem needs a metadata fallback, propagate its errors instead of dropping names.
451
- with os.scandir(fd) as entries:
452
- result = [(entry.name, entry.is_dir(follow_symlinks=False), entry.is_symlink())
453
- for entry in entries]
454
- return sorted(result, key=lambda entry: units(entry[0]))
455
-
456
- def listing(self, path, limit):
457
- fd = self.open(path, directory=True)
458
- try:
459
- entries = self.entries(fd)
460
- result = []
461
- for name, is_dir, is_link in entries[:limit]:
462
- if is_link:
463
- try:
464
- is_dir = stat.S_ISDIR(self.metadata(os.path.join(path, name)).st_mode)
465
- except (OSError, ScopeDenied, ValueError):
466
- is_dir = False
467
- result.append({"name": name, "isDir": is_dir})
468
- return {"entries": result, "truncated": len(entries) > limit}
469
- finally:
470
- os.close(fd)
471
-
472
- def scan(self, base):
473
- # Exactly the SDK traversal: sorted breadth-first levels, count all attempted reads,
474
- # descend past hits/invalid candidate names, then sort/filter/truncate the final answer.
475
- base = os.path.normpath(base)
476
- level = [base]
477
- found = []
478
- visits = 0
479
- depth = 0
480
- while level and visits < MAX_VISITS:
481
- next_level = []
482
- for path in sorted(level, key=units):
483
- if visits >= MAX_VISITS:
484
- break
485
- visits += 1
486
- try:
487
- fd = self.open(path, directory=True)
488
- try:
489
- entries = self.entries(fd)
490
- finally:
491
- os.close(fd)
492
- except FileNotFoundError:
493
- if depth == 0:
494
- return []
495
- continue
496
- except (OSError, ScopeDenied, ValueError):
497
- if depth == 0:
498
- raise
499
- continue
500
- if any(name == ".git" or (name == "AGENTS.md" and not is_dir)
501
- for name, is_dir, _ in entries):
502
- found.append(path)
503
- if depth < MAX_DEPTH:
504
- for name, is_dir, is_link in entries:
505
- if (is_dir and not is_link and not name.startswith(".")
506
- and name not in SKIP_ANY and not (depth == 0 and name in SKIP_BASE)):
507
- next_level.append(os.path.join(path, name))
508
- level = next_level
509
- depth += 1
510
- return [{"path": path, "suggestedName": os.path.basename(path)}
511
- for path in sorted(set(found), key=units)
512
- if valid_name(os.path.basename(path)) and valid_path(path)][:MAX_RESULTS]
513
-
514
- def run(self, request):
515
- method = request["method"]
516
- path = request["path"]
517
- if not valid_path(path):
518
- raise ValueError("Supply a valid absolute native path")
519
- if method in ("readFile", "list"):
520
- bound = request["maxBytes" if method == "readFile" else "limit"]
521
- if type(bound) is not int or bound < 0 or bound > 9007199254740991:
522
- raise ValueError("Supply a nonnegative integer byte or entry limit")
523
- if method == "scan":
524
- return self.scan(path)
525
- try:
526
- if method == "stat":
527
- info = self.metadata(path)
528
- return {"size": info.st_size, "isDir": stat.S_ISDIR(info.st_mode)}
529
- if method == "list":
530
- return self.listing(path, bound)
531
- if method == "readFile":
532
- fd = self.open(path)
533
- try:
534
- info = os.fstat(fd)
535
- if stat.S_ISDIR(info.st_mode):
536
- return None
537
- if not stat.S_ISREG(info.st_mode):
538
- raise ValueError("Native reads require a regular file")
539
- want = min(info.st_size, bound)
540
- data = bytearray()
541
- while len(data) < want:
542
- chunk = os.read(fd, want - len(data))
543
- if not chunk:
544
- break
545
- data.extend(chunk)
546
- finally:
547
- os.close(fd)
548
- return {"dataB64": base64.b64encode(data).decode("ascii"),
549
- "truncated": info.st_size > bound}
550
- if method == "writeFile":
551
- data = base64.b64decode(request["dataB64"], validate=True)
552
- with (self.files_lock.shared() if self.files_lock is not None
553
- else contextlib.nullcontext()):
554
- fd = self.open(path, write=True)
555
- try:
556
- if not stat.S_ISREG(os.fstat(fd).st_mode):
557
- raise ValueError("Native writes require a regular file")
558
- os.ftruncate(fd, 0)
559
- remaining = memoryview(data)
560
- while remaining:
561
- written = os.write(fd, remaining)
562
- if written == 0:
563
- raise OSError(errno.EIO, "Native write made no progress")
564
- remaining = remaining[written:]
565
- finally:
566
- os.close(fd)
567
- return None
568
- raise ValueError("Unknown native method")
569
- except FileNotFoundError:
570
- if method != "writeFile":
571
- return None
572
- raise
573
- except IsADirectoryError:
574
- if method == "readFile":
575
- return None
576
- raise
577
-
578
- def main():
579
- try:
580
- request = json.load(sys.stdin)
581
- result = NativeFiles(request["roots"]).run(request)
582
- response = {"result": result}
583
- except Exception as error:
584
- code = ("SCOPE_DENIED" if isinstance(error, ScopeDenied)
585
- else errno.errorcode.get(getattr(error, "errno", None), "INVALID_NATIVE_REQUEST"))
586
- # Do not expose symlink targets or other resolved paths in transport errors.
587
- response = {"error": {"code": code, "message": "Native operation failed; check the path, scope and filesystem access"}}
588
- print(json.dumps(response), flush=True)
589
-
590
- if __name__ == "__main__":
591
- main()
592
- `;