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