@capybara-hq/plugin-sdk 0.1.0-rc.6 → 0.1.0-rc.61

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.
Files changed (136) hide show
  1. package/README.md +1 -1
  2. package/agent-docs/agent-templates.md +14 -2
  3. package/agent-docs/concepts.md +14 -5
  4. package/agent-docs/connector-templates.md +7 -1
  5. package/agent-docs/extension-points/channel.md +1 -1
  6. package/agent-docs/extension-points/context.md +15 -0
  7. package/agent-docs/extension-points/device-provider.md +15 -0
  8. package/agent-docs/extension-points/file-preview.md +2 -0
  9. package/agent-docs/extension-points/model-provider.md +3 -1
  10. package/agent-docs/extension-points/object-store.md +2 -0
  11. package/agent-docs/extension-points/push-provider.md +17 -0
  12. package/agent-docs/extensions.md +29 -3
  13. package/agent-docs/plugin-format.md +52 -2
  14. package/agent-docs/setup.md +54 -0
  15. package/dist/agent-template.d.ts +15 -6
  16. package/dist/agent-template.js +32 -13
  17. package/dist/avatar-presets.d.ts +8 -0
  18. package/dist/avatar-presets.js +17 -0
  19. package/dist/bootstrap.d.ts +109 -1
  20. package/dist/bootstrap.js +185 -2
  21. package/dist/cards.d.ts +67 -13
  22. package/dist/cards.js +91 -21
  23. package/dist/channel.d.ts +148 -48
  24. package/dist/channel.js +10 -5
  25. package/dist/client-css.d.ts +36 -0
  26. package/dist/client-css.js +326 -0
  27. package/dist/client-section.d.ts +35 -0
  28. package/dist/client-section.js +133 -0
  29. package/dist/config-ui.d.ts +22 -0
  30. package/dist/config-ui.js +64 -4
  31. package/dist/connector-auth.d.ts +15 -2
  32. package/dist/connector-auth.js +97 -8
  33. package/dist/connector.d.ts +74 -32
  34. package/dist/context.d.ts +40 -0
  35. package/dist/context.js +2 -0
  36. package/dist/ctx.d.ts +132 -29
  37. package/dist/define-extension.d.ts +26 -12
  38. package/dist/define-extension.js +12 -5
  39. package/dist/device-denied-paths.d.ts +18 -0
  40. package/dist/device-denied-paths.js +84 -0
  41. package/dist/device-operation.d.ts +333 -0
  42. package/dist/device-operation.js +312 -0
  43. package/dist/device-protocol.d.ts +285 -50
  44. package/dist/device-protocol.js +755 -90
  45. package/dist/device-provider.d.ts +503 -0
  46. package/dist/device-provider.js +302 -0
  47. package/dist/dial-in.d.ts +176 -0
  48. package/dist/dial-in.js +115 -0
  49. package/dist/extension-point.d.ts +2 -0
  50. package/dist/extension-point.js +6 -2
  51. package/dist/file-preview.d.ts +23 -6
  52. package/dist/git-hosts.d.ts +53 -0
  53. package/dist/git-hosts.js +98 -0
  54. package/dist/hooks.d.ts +125 -20
  55. package/dist/hooks.js +5 -0
  56. package/dist/http-access.d.ts +62 -0
  57. package/dist/http-access.js +12 -0
  58. package/dist/identity.d.ts +38 -9
  59. package/dist/identity.js +21 -1
  60. package/dist/index.d.ts +29 -3
  61. package/dist/index.js +29 -3
  62. package/dist/marketplace.d.ts +26 -0
  63. package/dist/marketplace.js +43 -1
  64. package/dist/model-params.d.ts +41 -22
  65. package/dist/model-params.js +28 -15
  66. package/dist/model.d.ts +206 -71
  67. package/dist/model.js +152 -19
  68. package/dist/net.d.ts +52 -0
  69. package/dist/net.js +34 -0
  70. package/dist/network-classes.d.ts +98 -0
  71. package/dist/network-classes.js +291 -0
  72. package/dist/permissions.d.ts +54 -22
  73. package/dist/permissions.js +119 -43
  74. package/dist/plugin-manifest.d.ts +45 -5
  75. package/dist/plugin-manifest.js +174 -6
  76. package/dist/plugin-package.d.ts +82 -38
  77. package/dist/plugin-package.js +61 -29
  78. package/dist/push.d.ts +75 -0
  79. package/dist/push.js +87 -0
  80. package/dist/sandbox-linux-runtime-source.d.ts +1 -0
  81. package/dist/sandbox-linux-runtime-source.js +2318 -0
  82. package/dist/sandbox-native-runtime-source.d.ts +10 -0
  83. package/dist/sandbox-native-runtime-source.js +476 -0
  84. package/dist/sandbox-runtime-source.d.ts +19 -0
  85. package/dist/sandbox-runtime-source.js +28 -0
  86. package/dist/sandbox-write-denies.d.ts +139 -0
  87. package/dist/sandbox-write-denies.js +869 -0
  88. package/dist/secret.d.ts +4 -1
  89. package/dist/secret.js +4 -1
  90. package/dist/setup-check.d.ts +128 -0
  91. package/dist/setup-check.js +142 -0
  92. package/dist/setup-guide-parse.d.ts +121 -0
  93. package/dist/setup-guide-parse.js +356 -0
  94. package/dist/setup-guide-render.d.ts +45 -0
  95. package/dist/setup-guide-render.js +351 -0
  96. package/dist/setup-guide.d.ts +108 -0
  97. package/dist/setup-guide.js +367 -0
  98. package/dist/shell-capabilities.d.ts +211 -0
  99. package/dist/shell-capabilities.js +44 -0
  100. package/dist/shell-environment.d.ts +57 -0
  101. package/dist/shell-environment.js +21 -0
  102. package/dist/skill.d.ts +27 -17
  103. package/dist/skill.js +40 -26
  104. package/dist/storage.d.ts +52 -25
  105. package/dist/svg-viewbox.d.ts +10 -0
  106. package/dist/svg-viewbox.js +24 -0
  107. package/dist/theme-assets.d.ts +55 -0
  108. package/dist/theme-assets.js +489 -0
  109. package/dist/theme-readability.d.ts +37 -0
  110. package/dist/theme-readability.js +145 -0
  111. package/dist/theme-tokens.generated.d.ts +299 -0
  112. package/dist/theme-tokens.generated.js +184 -0
  113. package/dist/theme.d.ts +190 -0
  114. package/dist/theme.js +471 -0
  115. package/dist/tool.d.ts +99 -26
  116. package/dist/tool.js +29 -9
  117. package/dist/ui-parts.d.ts +23 -0
  118. package/dist/ui-parts.js +385 -0
  119. package/dist/ui-resolve.d.ts +35 -0
  120. package/dist/ui-resolve.js +42 -0
  121. package/dist/ui-slots.d.ts +65 -0
  122. package/dist/ui-slots.js +261 -0
  123. package/dist/ui.d.ts +212 -76
  124. package/dist/ui.js +101 -27
  125. package/dist/url.d.ts +4 -1
  126. package/dist/url.js +4 -1
  127. package/package.json +13 -1
  128. package/schemas/bootstrap-extra.v1.schema.json +186 -0
  129. package/schemas/bootstrap.v1.schema.json +20 -0
  130. package/schemas/connector-template.v1.schema.json +35 -0
  131. package/schemas/marketplace.v1.schema.json +14 -0
  132. package/schemas/plugin.v1.schema.json +122 -3
  133. package/schemas/theme.v1.schema.json +302 -0
  134. package/agent-docs/extension-points/sandbox.md +0 -15
  135. package/dist/sandbox.d.ts +0 -254
  136. package/dist/sandbox.js +0 -153
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Private Python 3 transport: one JSON request on stdin, one result/error on stdout.
3
+ * The trusted caller supplies already-authorized canonical root paths and inherited directory
4
+ * descriptors in roots.read/roots.write ({path, fd}); this helper never selects a profile. A read
5
+ * root may be a single file ({path, fd, file: true}): fd is then its parent directory, and only
6
+ * that one name below it is reachable through the root.
7
+ * Binary data uses dataB64. Callers own launch, signal handling, admission and error translation.
8
+ * Descriptor-relative native access alone does not establish an OS execution boundary.
9
+ */
10
+ export declare const NATIVE_FILES_SOURCE: string;
@@ -0,0 +1,476 @@
1
+ import { DEVICE_SCAN_SKIPPED_BASE_DIRS, DEVICE_SCAN_SKIPPED_DIRS, MAX_DEVICE_PROJECT_NAME_LENGTH, MAX_DEVICE_SCAN_DEPTH, MAX_DEVICE_SCAN_DIRS, MAX_DEVICE_SCAN_RESULTS, } from "./device-provider.js";
2
+ import { SANDBOX_WRITE_POLICY_PYTHON } from "./sandbox-write-denies.js";
3
+ /**
4
+ * Private Python 3 transport: one JSON request on stdin, one result/error on stdout.
5
+ * The trusted caller supplies already-authorized canonical root paths and inherited directory
6
+ * descriptors in roots.read/roots.write ({path, fd}); this helper never selects a profile. A read
7
+ * root may be a single file ({path, fd, file: true}): fd is then its parent directory, and only
8
+ * that one name below it is reachable through the root.
9
+ * Binary data uses dataB64. Callers own launch, signal handling, admission and error translation.
10
+ * Descriptor-relative native access alone does not establish an OS execution boundary.
11
+ */
12
+ export const NATIVE_FILES_SOURCE = String.raw `import base64
13
+ import contextlib
14
+ import errno
15
+ import fcntl
16
+ import json
17
+ import os
18
+ import re
19
+ import stat
20
+ import sys
21
+ import time
22
+ import urllib.parse
23
+
24
+ MAX_DEPTH = ${MAX_DEVICE_SCAN_DEPTH}
25
+ MAX_VISITS = ${MAX_DEVICE_SCAN_DIRS}
26
+ MAX_RESULTS = ${MAX_DEVICE_SCAN_RESULTS}
27
+ MAX_NAME = ${MAX_DEVICE_PROJECT_NAME_LENGTH}
28
+ SKIP_ANY = ${JSON.stringify(DEVICE_SCAN_SKIPPED_DIRS)}
29
+ SKIP_BASE = ${JSON.stringify(DEVICE_SCAN_SKIPPED_BASE_DIRS)}
30
+ # How long a write waits for a guarded move of the device (which holds the device's files lock
31
+ # exclusively for a few renames) before it fails with EBUSY: only a lock held from outside every
32
+ # sandbox (Full work of the owner) can take that long.
33
+ SHARED_WAIT_S = 30
34
+ # A test seam (pause_mkdir): a write creating that directory pauses PAUSE_S between its check and
35
+ # its mkdir, announced by PAUSE_MARKER in the parent. Never set in production.
36
+ PAUSE_S = 2
37
+ PAUSE_MARKER = ".capybara-test-paused"
38
+ # ECMAScript whitespace (Python's str.strip also removes several extra control characters).
39
+ 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"
40
+
41
+ # Restricted roots ({"denyWrites": true}) follow the shared write policy (sandbox-write-denies.ts).
42
+ ${SANDBOX_WRITE_POLICY_PYTHON}
43
+
44
+ class ScopeDenied(Exception):
45
+ pass
46
+
47
+ def units(value):
48
+ return value.encode("utf-16-be", "surrogatepass")
49
+
50
+ def valid_path(path):
51
+ if not isinstance(path, str) or not path.startswith("/") or len(units(path)) > 8192:
52
+ return False
53
+ if "\\" in path or "//" in path or re.search(r"[\x00-\x1f\x7f]", path):
54
+ return False
55
+ for part in path.split("/"):
56
+ try:
57
+ # decodeURIComponent rejects the entire segment on malformed escapes or UTF-8.
58
+ if re.search(r"%(?![0-9a-fA-F]{2})", part):
59
+ raise ValueError("Malformed percent escape")
60
+ decoded = urllib.parse.unquote(part, errors="strict")
61
+ except (UnicodeError, ValueError):
62
+ decoded = part
63
+ if decoded == ".." or "/" in decoded or "\\" in decoded:
64
+ return False
65
+ return True
66
+
67
+ def within(root, path):
68
+ return root == "/" or path == root or path.startswith(root + "/")
69
+
70
+ def valid_name(name):
71
+ return (name not in ("", ".", "..") and len(units(name)) <= MAX_NAME * 2
72
+ and not re.search(r"[\x00-\x1f\x7f/]", name)
73
+ and name[0] not in SPACE and name[-1] not in SPACE)
74
+
75
+ class DeviceFilesLock:
76
+ """The device's files lock, shared by every operation of the device: an flock on a file outside
77
+ every sandbox, inherited as a descriptor ("filesLockFd") that the restricted command never
78
+ holds. Every acquisition reopens it through /proc/self/fd (this process is non-dumpable, so no
79
+ other process can), because flock belongs to an open file description: each holder needs its
80
+ 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
81
+ waiting exclusive holder never holds back new shared ones (as in the launcher's in-process SharedLock)."""
82
+
83
+ def __init__(self, fd):
84
+ self.fd = fd
85
+
86
+ def acquire(self, mode, timeout, message):
87
+ fd = os.open("/proc/self/fd/%d" % self.fd, os.O_RDONLY | os.O_CLOEXEC)
88
+ deadline = time.monotonic() + timeout
89
+ delay = 0.0005
90
+ while True:
91
+ try:
92
+ fcntl.flock(fd, mode | fcntl.LOCK_NB)
93
+ return fd
94
+ except OSError as error:
95
+ if error.errno not in (errno.EWOULDBLOCK, errno.EAGAIN, errno.EINTR):
96
+ os.close(fd)
97
+ raise
98
+ if time.monotonic() >= deadline:
99
+ os.close(fd)
100
+ raise OSError(errno.EBUSY, message)
101
+ time.sleep(delay)
102
+ delay = min(delay * 2, 0.005)
103
+
104
+ @contextlib.contextmanager
105
+ def shared(self):
106
+ fd = self.acquire(fcntl.LOCK_SH, SHARED_WAIT_S, "A guarded move of the device did not end")
107
+ try:
108
+ yield
109
+ finally:
110
+ os.close(fd) # closing the last descriptor of the description releases the lock
111
+
112
+ @contextlib.contextmanager
113
+ def exclusive(self, timeout):
114
+ """Raises EBUSY when the shared holders do not leave within timeout seconds."""
115
+ fd = self.acquire(fcntl.LOCK_EX, timeout, "The device's other writes did not finish")
116
+ try:
117
+ yield
118
+ finally:
119
+ os.close(fd)
120
+
121
+
122
+ class NativeFiles:
123
+ def __init__(self, roots):
124
+ self.roots = roots
125
+ self.deny_writes = roots.get("denyWrites") is True
126
+ self.pause_mkdir = None
127
+ # The device's files lock (DeviceFilesLock), held shared by a write from its check to its
128
+ # effect; set by a consumer serving one device's operations, never by the transport.
129
+ self.files_lock = None
130
+ # Descriptors are supplied by the trusted consumer, never reopened by root pathname.
131
+ for root in roots["read"] + roots["write"]:
132
+ if not valid_path(root["path"]) or os.path.normpath(root["path"]) != root["path"]:
133
+ raise ValueError("Supply canonical absolute root paths")
134
+ if root.get("file") is True and (root in roots["write"] or root["path"] == "/"):
135
+ raise ValueError("Only a read root may be a single file")
136
+ if not stat.S_ISDIR(os.fstat(root["fd"]).st_mode):
137
+ raise ValueError("Supply pinned directory descriptors")
138
+
139
+ def parent(self, path, write=False, create=False):
140
+ fd, name, _, _ = self.resolve(path, write, create, 0, False)
141
+ return fd, name
142
+
143
+ def resolve(self, path, write, create, links, must_exist):
144
+ if not valid_path(path):
145
+ raise ValueError("Supply a valid absolute native path")
146
+ path = os.path.normpath(path)
147
+ if write and self.deny_writes and write_denied(path):
148
+ raise ScopeDenied("Native path is a protected write target")
149
+ roots = self.roots["write"] if write else self.roots["read"] + self.roots["write"]
150
+ matches = [root for root in roots if within(root["path"], path)]
151
+ if not matches:
152
+ raise ScopeDenied("Native path is outside the supplied roots")
153
+ root = max(matches, key=lambda entry: len(entry["path"]))
154
+ fd = os.dup(root["fd"])
155
+ current = root["path"]
156
+ parts = os.path.relpath(path, current).split("/")
157
+ if root.get("file") is True:
158
+ # a single-file root: walked from its parent directory, so the file's own name is
159
+ # the first component (anything below it is no directory, so missing for a reader)
160
+ current = os.path.dirname(root["path"])
161
+ parts = [os.path.basename(root["path"])] + ([] if path == root["path"] else parts)
162
+ result = self.walk(fd, current, parts, write, create, links, must_exist)
163
+ if write and self.deny_writes and write_denied(result[2]):
164
+ os.close(result[0])
165
+ raise ScopeDenied("Native path is a protected write target")
166
+ return result
167
+
168
+ def walk(self, fd, current, parts, write, create, links, must_exist):
169
+ try:
170
+ for index, name in enumerate(parts):
171
+ final = index == len(parts) - 1
172
+ try:
173
+ info = os.stat(name, dir_fd=fd, follow_symlinks=False)
174
+ except FileNotFoundError:
175
+ if not final and create:
176
+ if self.deny_writes and write_denied(os.path.join(current, name)):
177
+ raise ScopeDenied("Native path is a protected write target")
178
+ if self.pause_mkdir is not None and name == self.pause_mkdir:
179
+ os.close(os.open(PAUSE_MARKER, os.O_WRONLY | os.O_CREAT | os.O_EXCL,
180
+ 0o644, dir_fd=fd))
181
+ time.sleep(PAUSE_S)
182
+ try:
183
+ os.mkdir(name, 0o755, dir_fd=fd)
184
+ made = True
185
+ except FileExistsError:
186
+ made = False
187
+ info = os.stat(name, dir_fd=fd, follow_symlinks=False)
188
+ if made:
189
+ self.settle(fd, name, (info.st_dev, info.st_ino), True)
190
+ elif final and not must_exist:
191
+ return fd, name, os.path.normpath(os.path.join(current, name)), links
192
+ else:
193
+ raise
194
+ if stat.S_ISLNK(info.st_mode):
195
+ if links >= 40:
196
+ raise OSError(errno.ELOOP, "Too many symbolic links")
197
+ target = os.readlink(name, dir_fd=fd)
198
+ after = os.stat(name, dir_fd=fd, follow_symlinks=False)
199
+ if (info.st_dev, info.st_ino) != (after.st_dev, after.st_ino):
200
+ raise ScopeDenied("Native path changed during resolution")
201
+ target = os.path.normpath(os.path.join(current, target))
202
+ os.close(fd)
203
+ fd = None
204
+ # Resolve the target once. Writes require an existing target; the returned
205
+ # descriptor/name is reused, including when a directory has a suffix to walk.
206
+ fd, linked_name, resolved, links = self.resolve(
207
+ target, write, False, links + 1, must_exist or write)
208
+ if final:
209
+ return fd, linked_name, resolved, links
210
+ try:
211
+ child = os.open(linked_name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW,
212
+ dir_fd=fd)
213
+ except NotADirectoryError:
214
+ if not write:
215
+ raise FileNotFoundError(errno.ENOENT, "Native target does not exist")
216
+ raise
217
+ os.close(fd)
218
+ fd = None
219
+ return self.walk(child, resolved, parts[index + 1:], write, create,
220
+ links, must_exist)
221
+ if final:
222
+ return fd, name, os.path.normpath(os.path.join(current, name)), links
223
+ if not write and not stat.S_ISDIR(info.st_mode):
224
+ # Existing readers treat ENOTDIR in an ancestor as a missing target.
225
+ raise FileNotFoundError(errno.ENOENT, "Native target does not exist")
226
+ child = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd)
227
+ os.close(fd)
228
+ fd = child
229
+ current = os.path.join(current, name)
230
+ except BaseException:
231
+ if fd is not None:
232
+ os.close(fd)
233
+ raise
234
+
235
+ # ---- post-effect verification (restricted roots) -----------------------------------------
236
+ # A write is checked on the path its parent had, then applied through the parent descriptor.
237
+ # The device's files lock keeps sandboxed guarded moves out of that window; a process outside
238
+ # the sandbox can still move the parent meanwhile. So each entry this helper creates is checked
239
+ # again at its parent's current place (Linux /proc; elsewhere there is no such check) and
240
+ # undone when it landed at a protected path.
241
+
242
+ def placed(self, fd, name):
243
+ """name below fd at fd's current path, mapped onto the roots' recorded paths; None where
244
+ that cannot be told (no /proc) or the directory is gone."""
245
+ try:
246
+ where = os.readlink("/proc/self/fd/%d" % fd)
247
+ except OSError:
248
+ return None
249
+ if not where.startswith("/") or where.endswith(" (deleted)"):
250
+ return None
251
+ best = None
252
+ for root in self.roots["read"] + self.roots["write"]:
253
+ if root.get("file") is True:
254
+ continue # its descriptor is the parent directory, not the root's path
255
+ try:
256
+ now = os.readlink("/proc/self/fd/%d" % root["fd"]).rstrip("/")
257
+ except OSError:
258
+ continue
259
+ if where == now or where.startswith(now + "/"):
260
+ if best is None or len(now) > best[0]:
261
+ best = (len(now), root["path"].rstrip("/") + where[len(now):])
262
+ where = best[1] if best else where
263
+ return where.rstrip("/") + "/" + name
264
+
265
+ def landed_denied(self, fd, name, is_dir):
266
+ now = self.placed(fd, name) if self.deny_writes else None
267
+ return now is not None and (write_denied(now) or (
268
+ not is_dir and _fold_parts(name) == [".git"]))
269
+
270
+ def settle(self, fd, name, made, is_dir):
271
+ """Undoes the entry this helper made below fd (made: its (st_dev, st_ino)) when it now
272
+ sits at a protected path, and refuses."""
273
+ if not self.landed_denied(fd, name, is_dir):
274
+ return
275
+ try:
276
+ info = os.stat(name, dir_fd=fd, follow_symlinks=False)
277
+ if (info.st_dev, info.st_ino) != made:
278
+ raise OSError(errno.ESTALE, "The created entry was replaced")
279
+ if is_dir:
280
+ os.rmdir(name, dir_fd=fd)
281
+ else:
282
+ os.unlink(name, dir_fd=fd)
283
+ except OSError:
284
+ raise ScopeDenied("A native write landed at a protected path and could not be undone")
285
+ raise ScopeDenied("Native path became a protected write target")
286
+
287
+ def open(self, path, write=False, directory=False):
288
+ parent, name = self.parent(path, write, write)
289
+ try:
290
+ if write and self.deny_writes and _fold_parts(name) == [".git"]:
291
+ os.close(parent)
292
+ parent = None
293
+ raise ScopeDenied("A file named .git would point git elsewhere")
294
+ flags = os.O_NOFOLLOW | os.O_NONBLOCK
295
+ flags |= os.O_WRONLY | os.O_CREAT if write else os.O_RDONLY
296
+ if directory:
297
+ flags |= os.O_DIRECTORY
298
+ if not write:
299
+ return os.open(name, flags, 0o600, dir_fd=parent)
300
+ try:
301
+ os.stat(name, dir_fd=parent, follow_symlinks=False)
302
+ existed = True
303
+ except FileNotFoundError:
304
+ existed = False
305
+ fd = os.open(name, flags, 0o600, dir_fd=parent)
306
+ try:
307
+ if existed:
308
+ # nothing was made: refused before any byte changes (the caller truncates)
309
+ if self.landed_denied(parent, name, False):
310
+ raise ScopeDenied("Native path became a protected write target")
311
+ else:
312
+ info = os.fstat(fd)
313
+ self.settle(parent, name, (info.st_dev, info.st_ino), False)
314
+ except BaseException:
315
+ os.close(fd)
316
+ raise
317
+ return fd
318
+ finally:
319
+ if parent is not None:
320
+ os.close(parent)
321
+
322
+ def metadata(self, path):
323
+ parent, name = self.parent(path)
324
+ try:
325
+ value = os.stat(name, dir_fd=parent, follow_symlinks=False)
326
+ if stat.S_ISLNK(value.st_mode):
327
+ raise ScopeDenied("Native path changed during resolution")
328
+ return value
329
+ finally:
330
+ os.close(parent)
331
+
332
+ def entries(self, fd):
333
+ # Dirent type data works even when child metadata cannot be searched. If the
334
+ # filesystem needs a metadata fallback, propagate its errors instead of dropping names.
335
+ with os.scandir(fd) as entries:
336
+ result = [(entry.name, entry.is_dir(follow_symlinks=False), entry.is_symlink())
337
+ for entry in entries]
338
+ return sorted(result, key=lambda entry: units(entry[0]))
339
+
340
+ def listing(self, path, limit):
341
+ fd = self.open(path, directory=True)
342
+ try:
343
+ entries = self.entries(fd)
344
+ result = []
345
+ for name, is_dir, is_link in entries[:limit]:
346
+ if is_link:
347
+ try:
348
+ is_dir = stat.S_ISDIR(self.metadata(os.path.join(path, name)).st_mode)
349
+ except (OSError, ScopeDenied, ValueError):
350
+ is_dir = False
351
+ result.append({"name": name, "isDir": is_dir})
352
+ return {"entries": result, "truncated": len(entries) > limit}
353
+ finally:
354
+ os.close(fd)
355
+
356
+ def scan(self, base):
357
+ # Exactly the SDK traversal: sorted breadth-first levels, count all attempted reads,
358
+ # descend past hits/invalid candidate names, then sort/filter/truncate the final answer.
359
+ base = os.path.normpath(base)
360
+ level = [base]
361
+ found = []
362
+ visits = 0
363
+ depth = 0
364
+ while level and visits < MAX_VISITS:
365
+ next_level = []
366
+ for path in sorted(level, key=units):
367
+ if visits >= MAX_VISITS:
368
+ break
369
+ visits += 1
370
+ try:
371
+ fd = self.open(path, directory=True)
372
+ try:
373
+ entries = self.entries(fd)
374
+ finally:
375
+ os.close(fd)
376
+ except FileNotFoundError:
377
+ if depth == 0:
378
+ return []
379
+ continue
380
+ except (OSError, ScopeDenied, ValueError):
381
+ if depth == 0:
382
+ raise
383
+ continue
384
+ if any(name == ".git" or (name == "AGENTS.md" and not is_dir)
385
+ for name, is_dir, _ in entries):
386
+ found.append(path)
387
+ if depth < MAX_DEPTH:
388
+ for name, is_dir, is_link in entries:
389
+ if (is_dir and not is_link and not name.startswith(".")
390
+ and name not in SKIP_ANY and not (depth == 0 and name in SKIP_BASE)):
391
+ next_level.append(os.path.join(path, name))
392
+ level = next_level
393
+ depth += 1
394
+ return [{"path": path, "suggestedName": os.path.basename(path)}
395
+ for path in sorted(set(found), key=units)
396
+ if valid_name(os.path.basename(path)) and valid_path(path)][:MAX_RESULTS]
397
+
398
+ def run(self, request):
399
+ method = request["method"]
400
+ path = request["path"]
401
+ if not valid_path(path):
402
+ raise ValueError("Supply a valid absolute native path")
403
+ if method in ("readFile", "list"):
404
+ bound = request["maxBytes" if method == "readFile" else "limit"]
405
+ if type(bound) is not int or bound < 0 or bound > 9007199254740991:
406
+ raise ValueError("Supply a nonnegative integer byte or entry limit")
407
+ if method == "scan":
408
+ return self.scan(path)
409
+ try:
410
+ if method == "stat":
411
+ info = self.metadata(path)
412
+ return {"size": info.st_size, "isDir": stat.S_ISDIR(info.st_mode)}
413
+ if method == "list":
414
+ return self.listing(path, bound)
415
+ if method == "readFile":
416
+ fd = self.open(path)
417
+ try:
418
+ info = os.fstat(fd)
419
+ if stat.S_ISDIR(info.st_mode):
420
+ return None
421
+ if not stat.S_ISREG(info.st_mode):
422
+ raise ValueError("Native reads require a regular file")
423
+ want = min(info.st_size, bound)
424
+ data = bytearray()
425
+ while len(data) < want:
426
+ chunk = os.read(fd, want - len(data))
427
+ if not chunk:
428
+ break
429
+ data.extend(chunk)
430
+ finally:
431
+ os.close(fd)
432
+ return {"dataB64": base64.b64encode(data).decode("ascii"),
433
+ "truncated": info.st_size > bound}
434
+ if method == "writeFile":
435
+ data = base64.b64decode(request["dataB64"], validate=True)
436
+ with (self.files_lock.shared() if self.files_lock is not None
437
+ else contextlib.nullcontext()):
438
+ fd = self.open(path, write=True)
439
+ try:
440
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
441
+ raise ValueError("Native writes require a regular file")
442
+ os.ftruncate(fd, 0)
443
+ remaining = memoryview(data)
444
+ while remaining:
445
+ written = os.write(fd, remaining)
446
+ if written == 0:
447
+ raise OSError(errno.EIO, "Native write made no progress")
448
+ remaining = remaining[written:]
449
+ finally:
450
+ os.close(fd)
451
+ return None
452
+ raise ValueError("Unknown native method")
453
+ except FileNotFoundError:
454
+ if method != "writeFile":
455
+ return None
456
+ raise
457
+ except IsADirectoryError:
458
+ if method == "readFile":
459
+ return None
460
+ raise
461
+
462
+ def main():
463
+ try:
464
+ request = json.load(sys.stdin)
465
+ result = NativeFiles(request["roots"]).run(request)
466
+ response = {"result": result}
467
+ except Exception as error:
468
+ code = ("SCOPE_DENIED" if isinstance(error, ScopeDenied)
469
+ else errno.errorcode.get(getattr(error, "errno", None), "INVALID_NATIVE_REQUEST"))
470
+ # Do not expose symlink targets or other resolved paths in transport errors.
471
+ response = {"error": {"code": code, "message": "Native operation failed; check the path, scope and filesystem access"}}
472
+ print(json.dumps(response), flush=True)
473
+
474
+ if __name__ == "__main__":
475
+ main()
476
+ `;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Immutable runtime bytes for trusted consumer staging (requires Python 3). Consumers verify every
3
+ * hash before use, stage the files together in a directory the operation user cannot write, and
4
+ * supply pinned, already-authorized root descriptors.
5
+ *
6
+ * - `native-files.py`: the portable native helper (descriptor-relative file access).
7
+ * - `linux-sandbox.py`: the restricted Linux launcher and syscall broker (Landlock plus a seccomp
8
+ * notification broker). It decides nothing about authority; its `probe` reports whether the
9
+ * running kernel, architecture and container policy support restricted execution, and every
10
+ * unsupported case reports unavailable. Shipping these bytes is not a provider support claim.
11
+ */
12
+ export declare const SANDBOX_RUNTIME_SOURCE: {
13
+ readonly version: number;
14
+ readonly files: readonly {
15
+ readonly name: string;
16
+ readonly source: string;
17
+ readonly sha256: string;
18
+ }[];
19
+ };
@@ -0,0 +1,28 @@
1
+ import { LINUX_SANDBOX_SOURCE } from "./sandbox-linux-runtime-source.js";
2
+ import { NATIVE_FILES_SOURCE } from "./sandbox-native-runtime-source.js";
3
+ /**
4
+ * Immutable runtime bytes for trusted consumer staging (requires Python 3). Consumers verify every
5
+ * hash before use, stage the files together in a directory the operation user cannot write, and
6
+ * supply pinned, already-authorized root descriptors.
7
+ *
8
+ * - `native-files.py`: the portable native helper (descriptor-relative file access).
9
+ * - `linux-sandbox.py`: the restricted Linux launcher and syscall broker (Landlock plus a seccomp
10
+ * notification broker). It decides nothing about authority; its `probe` reports whether the
11
+ * running kernel, architecture and container policy support restricted execution, and every
12
+ * unsupported case reports unavailable. Shipping these bytes is not a provider support claim.
13
+ */
14
+ export const SANDBOX_RUNTIME_SOURCE = Object.freeze({
15
+ version: 2,
16
+ files: Object.freeze([
17
+ Object.freeze({
18
+ name: "native-files.py",
19
+ source: NATIVE_FILES_SOURCE,
20
+ sha256: "c1712198af4ffedc0b48f789c28ed4233dc9008521b897300731c4f903168950",
21
+ }),
22
+ Object.freeze({
23
+ name: "linux-sandbox.py",
24
+ source: LINUX_SANDBOX_SOURCE,
25
+ sha256: "4e046df902dc644532ada9f2a3bef30a983daf7d1f238bd46dcd16524d96c66c",
26
+ }),
27
+ ]),
28
+ });