@capybara-hq/plugin-sdk 0.1.0-rc.4 → 0.1.0-rc.41

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