@capybara-hq/plugin-sdk 0.1.0-rc.23 → 0.1.0-rc.25

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.
@@ -1,27 +1,47 @@
1
1
  /**
2
- * Device protocol v1: the WebSocket frames between the kernel and a `capybara-device` program
2
+ * Device protocol v2: the WebSocket frames between the kernel and a `capybara-device` program
3
3
  * (a connected machine that serves as a device). Pure types and hand-written guards.
4
4
  */
5
5
  import { type ExecResult, type SandboxActor, type SandboxLimits, type SandboxRoots } from "./sandbox.js";
6
6
  /** The protocol version carried in `X-Capybara-Device-Protocol` and the hello frame. */
7
- export declare const DEVICE_PROTOCOL_VERSION = 1;
7
+ export declare const DEVICE_PROTOCOL_VERSION = 2;
8
8
  /** The operations the kernel asks a device to run. */
9
- export type DeviceOp = "create" | "exec" | "readFile" | "writeFile" | "stat" | "killTagged" | "killAll" | "stop" | "policy" | "policyStatus";
9
+ export type DeviceOp = "create" | "exec" | "readFile" | "writeFile" | "stat" | "killTagged" | "killAll" | "stop" | "policy" | "policyStatus" | "list" | "scan";
10
10
  /**
11
11
  * Optional capabilities a device announces in its hello. `policyOp`: the device takes the `policy`
12
12
  * op; `policyOpId`: it also logs each `policy` op's outcome by its `opId`, answers `policyStatus`
13
13
  * and reports recent outcomes in its hello (`recentOps`); `networkReport` means exec results may
14
14
  * carry `network`; `mode` means the device applies `limits.mode` / `limits.network` (without it
15
- * the device behaves as an allowlisted sandbox).
15
+ * the device behaves as an allowlisted sandbox); `projects` means the device serves `list` and
16
+ * `scan` (the kernel keeps a device's projects itself and asks the device only what it can read).
17
+ * The kernel gates each op on its feature, as it gates `policy` on `policyOp` / `policyOpId`: it
18
+ * never sends `list` or `scan` to a device that did not announce `projects`.
16
19
  */
17
- export type DeviceFeature = "networkReport" | "policyOp" | "policyOpId" | "mode";
18
- /** What the kernel knows of a device's local policy (from the hello or a `policy` op). */
20
+ export type DeviceFeature = "networkReport" | "policyOp" | "policyOpId" | "mode" | "projects";
21
+ /** The most entries a `list` op may ask for and its result may carry. */
22
+ export declare const MAX_DEVICE_LIST_ENTRIES = 1000;
23
+ /** What a device knows of its local policy and reports (in the hello or a `policy` op). */
19
24
  export interface DeviceLocalPolicySummary {
20
25
  /** `auto` = no OS sandbox (the owner's machine); `sandbox` = the OS sandbox. */
21
26
  mode: "auto" | "sandbox";
22
27
  /** The device's sandbox-mode allowlist; meaningful in sandbox mode only. */
23
28
  allowedDomains: string[];
24
29
  }
30
+ /**
31
+ * A directory a `scan` found that looks like a project (it holds `.git` or `AGENTS.md`): a
32
+ * suggestion, not a project. `path` is absolute ({@link validateSandboxPathShape});
33
+ * `suggestedName` is a guess from its basename ({@link isDeviceProjectName}) the owner may change.
34
+ */
35
+ export interface DeviceProjectCandidate {
36
+ path: string;
37
+ suggestedName: string;
38
+ }
39
+ /**
40
+ * The kernel's current ceiling on a request that reads the device's file system outside a command
41
+ * (`readFile`, `stat`, `list`, `scan`): the device answers in the mode it would run this request in, the owner's
42
+ * choice cut to `mode`, never by a ceiling it saw on an earlier command.
43
+ */
44
+ export type DeviceRequestCeiling = Pick<SandboxLimits, "mode">;
25
45
  /**
26
46
  * The first line of the kernel's background task launch command (`Bash` `run_in_background`), a
27
47
  * shell comment. A device kills what a foreground exec leaves running once the exec ends; an exec
@@ -66,6 +86,11 @@ export interface DeviceHello {
66
86
  * the parser).
67
87
  */
68
88
  recentOps?: DevicePolicyOpReport[];
89
+ /**
90
+ * The owner's home directory, an absolute path (a local device; the base of an auto-mode
91
+ * project's relative path). A malformed value is dropped by the parser.
92
+ */
93
+ home?: string;
69
94
  }
70
95
  /** Error kinds a device reports for a failed request. */
71
96
  export type DeviceErrorKind = "gone" | "fs_gone" | "policy" | "error";
@@ -136,6 +161,7 @@ export interface DeviceExecGrants {
136
161
  export type DeviceExecResult = ExecResult;
137
162
  export interface DeviceReadFileArgs {
138
163
  path: string;
164
+ limits: DeviceRequestCeiling;
139
165
  maxBytes: number;
140
166
  }
141
167
  export type DeviceReadFileResult = {
@@ -149,6 +175,7 @@ export interface DeviceWriteFileArgs {
149
175
  export type DeviceWriteFileResult = null;
150
176
  export interface DeviceStatArgs {
151
177
  path: string;
178
+ limits: DeviceRequestCeiling;
152
179
  }
153
180
  export type DeviceStatResult = {
154
181
  size: number;
@@ -211,7 +238,52 @@ export interface DevicePolicyStatus {
211
238
  policy?: DeviceLocalPolicySummary;
212
239
  message?: string;
213
240
  }
214
- /** A frame that is not valid protocol v1 (or came from the wrong side). */
241
+ /**
242
+ * Lists one directory (absolute `path`, {@link validateSandboxPathShape}): at most `limit` entries
243
+ * (at most {@link MAX_DEVICE_LIST_ENTRIES}), read in the mode `limits` gives. See
244
+ * `SandboxProvider.list` for the semantics.
245
+ */
246
+ export interface DeviceListArgs {
247
+ path: string;
248
+ limit: number;
249
+ limits: DeviceRequestCeiling;
250
+ }
251
+ /**
252
+ * One entry of a listed directory: `name` is never empty, `.` or `..` and holds no `/`. `isDir`
253
+ * follows symbolic links (stat semantics): a link to a directory is `true`, a dangling link `false`,
254
+ * and so is a link whose target the request's mode cannot reach.
255
+ */
256
+ export interface DeviceListEntry {
257
+ name: string;
258
+ isDir: boolean;
259
+ }
260
+ /**
261
+ * The directory's entries sorted by code unit, `truncated` when more than `limit` exist; null only
262
+ * when the path does not exist and the request's mode could reach it (like `stat` / `readFile`).
263
+ * A file, an unreadable directory, or a path the request's mode cannot reach is an error (the
264
+ * latter a `policy` refusal), never null.
265
+ */
266
+ export type DeviceListResult = {
267
+ entries: DeviceListEntry[];
268
+ truncated: boolean;
269
+ } | null;
270
+ /**
271
+ * Looks for project-like directories under `base` (absolute, {@link validateSandboxPathShape}),
272
+ * read in the mode `limits` gives. A `base` that does not exist answers `[]`; a `base` that is a
273
+ * file, unreadable, or outside the request's mode is an error. See `SandboxProvider.scan` for the
274
+ * traversal.
275
+ */
276
+ export interface DeviceScanArgs {
277
+ base: string;
278
+ limits: DeviceRequestCeiling;
279
+ }
280
+ /**
281
+ * `base` itself and the directories at most {@link MAX_DEVICE_SCAN_DEPTH} levels below it that
282
+ * hold a `.git` entry or an `AGENTS.md` file, sorted by `path` in code-unit order and cut to the
283
+ * first {@link MAX_DEVICE_SCAN_RESULTS}. Never file contents. See `SandboxProvider.scan`.
284
+ */
285
+ export type DeviceScanResult = DeviceProjectCandidate[];
286
+ /** A frame that is not valid device protocol (or came from the wrong side). */
215
287
  export declare class DeviceProtocolError extends Error {
216
288
  constructor(message: string);
217
289
  }
@@ -232,6 +304,8 @@ export interface DeviceOpResults {
232
304
  stop: null;
233
305
  policy: DevicePolicyResult;
234
306
  policyStatus: DevicePolicyStatus;
307
+ list: DeviceListResult;
308
+ scan: DeviceScanResult;
235
309
  }
236
310
  /** Validates the `result` of a successful `res` for `op`; throws {@link DeviceProtocolError}. */
237
311
  export declare function parseOpResult<Op extends DeviceOp>(op: Op, result: unknown): DeviceOpResults[Op];
@@ -1,10 +1,10 @@
1
1
  /**
2
- * Device protocol v1: the WebSocket frames between the kernel and a `capybara-device` program
2
+ * Device protocol v2: the WebSocket frames between the kernel and a `capybara-device` program
3
3
  * (a connected machine that serves as a device). Pure types and hand-written guards.
4
4
  */
5
- import { validateAllowHost, validateSandboxPathShape, } from "./sandbox.js";
5
+ import { isDeviceProjectName, MAX_DEVICE_PROJECT_NAME_LENGTH, MAX_DEVICE_SCAN_DEPTH, MAX_DEVICE_SCAN_RESULTS, validateAllowHost, validateSandboxPathShape, } from "./sandbox.js";
6
6
  /** The protocol version carried in `X-Capybara-Device-Protocol` and the hello frame. */
7
- export const DEVICE_PROTOCOL_VERSION = 1;
7
+ export const DEVICE_PROTOCOL_VERSION = 2;
8
8
  const DEVICE_OPS = [
9
9
  "create",
10
10
  "exec",
@@ -16,13 +16,18 @@ const DEVICE_OPS = [
16
16
  "stop",
17
17
  "policy",
18
18
  "policyStatus",
19
+ "list",
20
+ "scan",
19
21
  ];
20
22
  const DEVICE_FEATURES = [
21
23
  "networkReport",
22
24
  "policyOp",
23
25
  "policyOpId",
24
26
  "mode",
27
+ "projects",
25
28
  ];
29
+ /** The most entries a `list` op may ask for and its result may carry. */
30
+ export const MAX_DEVICE_LIST_ENTRIES = 1000;
26
31
  /**
27
32
  * The first line of the kernel's background task launch command (`Bash` `run_in_background`), a
28
33
  * shell comment. A device kills what a foreground exec leaves running once the exec ends; an exec
@@ -41,7 +46,7 @@ const MAX_POLICY_HOSTS = 100;
41
46
  export const MAX_POLICY_OP_ID_LENGTH = 128;
42
47
  /** The most entries a hello's `recentOps` carries; the parser keeps the newest. */
43
48
  export const MAX_RECENT_POLICY_OPS = 100;
44
- /** A frame that is not valid protocol v1 (or came from the wrong side). */
49
+ /** A frame that is not valid device protocol (or came from the wrong side). */
45
50
  export class DeviceProtocolError extends Error {
46
51
  constructor(message) {
47
52
  super(message);
@@ -149,6 +154,70 @@ function hostArray(o, k) {
149
154
  }
150
155
  return v;
151
156
  }
157
+ /** A bounded array field of a result or summary, refused when it is longer than `max`. */
158
+ function boundedArray(v, label, max, what) {
159
+ if (!Array.isArray(v)) {
160
+ throw new DeviceProtocolError(`field "${label}" must be an array of ${what}`);
161
+ }
162
+ if (v.length > max) {
163
+ throw new DeviceProtocolError(`field "${label}" must have at most ${max} entries`);
164
+ }
165
+ return v;
166
+ }
167
+ /** A project name field (see {@link isDeviceProjectName}), named by `what` in the message. */
168
+ function projectName(v, what) {
169
+ if (!isDeviceProjectName(v)) {
170
+ throw new DeviceProtocolError(`${what} must be a non-empty name of at most ${MAX_DEVICE_PROJECT_NAME_LENGTH} UTF-16 code units, not "." or "..", without "/", control characters or leading or trailing whitespace`);
171
+ }
172
+ return v;
173
+ }
174
+ /** An absolute path field ({@link validateSandboxPathShape}), named by `what` in the message. */
175
+ function absolutePath(v, what) {
176
+ if (typeof v !== "string")
177
+ throw new DeviceProtocolError(`${what} must be a string`);
178
+ const problems = validateSandboxPathShape(v);
179
+ if (problems.length > 0)
180
+ throw new DeviceProtocolError(`${what}: ${problems.join("; ")}`);
181
+ return v;
182
+ }
183
+ /** A request's ceiling (`limits` of `list` / `scan`): only its mode. */
184
+ function parseCeiling(v) {
185
+ return { mode: oneOf(obj(v, 'field "limits"'), "mode", ["auto", "sandbox"]) };
186
+ }
187
+ /** A `list` result: null, or at most {@link MAX_DEVICE_LIST_ENTRIES} named entries. */
188
+ function parseListResult(result) {
189
+ if (result === null)
190
+ return null;
191
+ const r = obj(result, "list result");
192
+ const entries = boundedArray(r.entries, "entries", MAX_DEVICE_LIST_ENTRIES, "entries").map((e, i) => {
193
+ const what = `field "entries[${i}]"`;
194
+ if (!isRecord(e))
195
+ throw new DeviceProtocolError(`${what} must be an object`);
196
+ const name = e.name;
197
+ if (typeof name !== "string" ||
198
+ name === "" ||
199
+ name === "." ||
200
+ name === ".." ||
201
+ name.includes("/")) {
202
+ throw new DeviceProtocolError(`${what}.name must be a non-empty string without "/", other than "." and ".."`);
203
+ }
204
+ return { name, isDir: bool(e, "isDir") };
205
+ });
206
+ return { entries, truncated: bool(r, "truncated") };
207
+ }
208
+ /** A `scan` result: at most {@link MAX_DEVICE_SCAN_RESULTS} candidates. */
209
+ function parseScanResult(v) {
210
+ const label = "scan result";
211
+ return boundedArray(v, label, MAX_DEVICE_SCAN_RESULTS, "candidates").map((e, i) => {
212
+ const what = `field "${label}[${i}]"`;
213
+ if (!isRecord(e))
214
+ throw new DeviceProtocolError(`${what} must be an object`);
215
+ return {
216
+ path: absolutePath(e.path, `${what}.path`),
217
+ suggestedName: projectName(e.suggestedName, `${what}.suggestedName`),
218
+ };
219
+ });
220
+ }
152
221
  function parsePolicySummary(v) {
153
222
  const o = obj(v, 'field "policy"');
154
223
  return {
@@ -196,6 +265,9 @@ function optionalHelloFields(o) {
196
265
  }
197
266
  if (Array.isArray(o.recentOps))
198
267
  out.recentOps = parseRecentOps(o.recentOps);
268
+ if (typeof o.home === "string" && validateSandboxPathShape(o.home).length === 0) {
269
+ out.home = o.home;
270
+ }
199
271
  return { ...out, ...optionalPolicy(o.policy) };
200
272
  }
201
273
  /** A summary field that is dropped when absent or unreadable. */
@@ -325,6 +397,7 @@ function validateArgs(op, a) {
325
397
  }
326
398
  case "readFile": {
327
399
  str(a, "path");
400
+ parseCeiling(a.limits);
328
401
  const m = a.maxBytes;
329
402
  if (typeof m !== "number" || !Number.isInteger(m) || m < 0) {
330
403
  throw new DeviceProtocolError('field "maxBytes" must be a non-negative integer');
@@ -337,6 +410,7 @@ function validateArgs(op, a) {
337
410
  return;
338
411
  case "stat":
339
412
  str(a, "path");
413
+ parseCeiling(a.limits);
340
414
  return;
341
415
  case "killTagged":
342
416
  strArray(a, "tags");
@@ -375,6 +449,19 @@ function validateArgs(op, a) {
375
449
  case "policyStatus":
376
450
  opId(a);
377
451
  return;
452
+ case "list": {
453
+ absolutePath(a.path, 'field "path"');
454
+ const limit = posInt(a, "limit");
455
+ if (limit > MAX_DEVICE_LIST_ENTRIES) {
456
+ throw new DeviceProtocolError(`field "limit" must be at most ${MAX_DEVICE_LIST_ENTRIES}`);
457
+ }
458
+ parseCeiling(a.limits);
459
+ return;
460
+ }
461
+ case "scan":
462
+ absolutePath(a.base, 'field "base"');
463
+ parseCeiling(a.limits);
464
+ return;
378
465
  }
379
466
  }
380
467
  export function parseOpResult(op, result) {
@@ -425,6 +512,10 @@ export function parseOpResult(op, result) {
425
512
  }
426
513
  case "create":
427
514
  return { roots: parseRoots(obj(result, "create result").roots) };
515
+ case "list":
516
+ return parseListResult(result);
517
+ case "scan":
518
+ return parseScanResult(result);
428
519
  default:
429
520
  if (result !== null)
430
521
  throw new DeviceProtocolError(`${op} result must be null`);
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const SDK_VERSION = "0.1.0-rc.23";
1
+ export declare const SDK_VERSION = "0.1.0-rc.25";
2
2
  export * from "./agent-template.js";
3
3
  export * from "./bootstrap.js";
4
4
  export * from "./cards.js";
@@ -27,6 +27,8 @@ export * from "./permissions.js";
27
27
  export * from "./plugin-manifest.js";
28
28
  export * from "./plugin-package.js";
29
29
  export * from "./sandbox.js";
30
+ export * from "./sandbox-operation.js";
31
+ export { SANDBOX_RUNTIME_SOURCE } from "./sandbox-runtime-source.js";
30
32
  export * from "./secret.js";
31
33
  export * from "./setup-check.js";
32
34
  export * from "./setup-guide.js";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export const SDK_VERSION = "0.1.0-rc.23";
1
+ export const SDK_VERSION = "0.1.0-rc.25";
2
2
  export * from "./agent-template.js";
3
3
  export * from "./bootstrap.js";
4
4
  export * from "./cards.js";
@@ -27,6 +27,8 @@ export * from "./permissions.js";
27
27
  export * from "./plugin-manifest.js";
28
28
  export * from "./plugin-package.js";
29
29
  export * from "./sandbox.js";
30
+ export * from "./sandbox-operation.js";
31
+ export { SANDBOX_RUNTIME_SOURCE } from "./sandbox-runtime-source.js";
30
32
  export * from "./secret.js";
31
33
  export * from "./setup-check.js";
32
34
  export * from "./setup-guide.js";
@@ -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,307 @@
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
+ /**
3
+ * Private Python 3 transport: one JSON request on stdin, one result/error on stdout.
4
+ * The trusted caller supplies already-authorized canonical root paths and inherited directory
5
+ * descriptors in roots.read/roots.write ({path, fd}); this helper never selects a profile.
6
+ * Binary data uses dataB64. Callers own launch, signal handling, admission and error translation.
7
+ * Descriptor-relative native access alone does not establish an OS execution boundary.
8
+ */
9
+ export const NATIVE_FILES_SOURCE = String.raw `import base64
10
+ import errno
11
+ import json
12
+ import os
13
+ import re
14
+ import stat
15
+ import sys
16
+ import urllib.parse
17
+
18
+ MAX_DEPTH = ${MAX_DEVICE_SCAN_DEPTH}
19
+ MAX_VISITS = ${MAX_DEVICE_SCAN_DIRS}
20
+ MAX_RESULTS = ${MAX_DEVICE_SCAN_RESULTS}
21
+ MAX_NAME = ${MAX_DEVICE_PROJECT_NAME_LENGTH}
22
+ SKIP_ANY = ${JSON.stringify(DEVICE_SCAN_SKIPPED_DIRS)}
23
+ SKIP_BASE = ${JSON.stringify(DEVICE_SCAN_SKIPPED_BASE_DIRS)}
24
+ # ECMAScript whitespace (Python's str.strip also removes several extra control characters).
25
+ 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"
26
+
27
+ class ScopeDenied(Exception):
28
+ pass
29
+
30
+ def units(value):
31
+ return value.encode("utf-16-be", "surrogatepass")
32
+
33
+ def valid_path(path):
34
+ if not isinstance(path, str) or not path.startswith("/") or len(units(path)) > 8192:
35
+ return False
36
+ if "\\" in path or "//" in path or re.search(r"[\x00-\x1f\x7f]", path):
37
+ return False
38
+ for part in path.split("/"):
39
+ try:
40
+ # decodeURIComponent rejects the entire segment on malformed escapes or UTF-8.
41
+ if re.search(r"%(?![0-9a-fA-F]{2})", part):
42
+ raise ValueError("Malformed percent escape")
43
+ decoded = urllib.parse.unquote(part, errors="strict")
44
+ except (UnicodeError, ValueError):
45
+ decoded = part
46
+ if decoded == ".." or "/" in decoded or "\\" in decoded:
47
+ return False
48
+ return True
49
+
50
+ def within(root, path):
51
+ return root == "/" or path == root or path.startswith(root + "/")
52
+
53
+ def valid_name(name):
54
+ return (name not in ("", ".", "..") and len(units(name)) <= MAX_NAME * 2
55
+ and not re.search(r"[\x00-\x1f\x7f/]", name)
56
+ and name[0] not in SPACE and name[-1] not in SPACE)
57
+
58
+ class NativeFiles:
59
+ def __init__(self, roots):
60
+ self.roots = roots
61
+ # Descriptors are supplied by the trusted consumer, never reopened by root pathname.
62
+ for root in roots["read"] + roots["write"]:
63
+ if not valid_path(root["path"]) or os.path.normpath(root["path"]) != root["path"]:
64
+ raise ValueError("Supply canonical absolute root paths")
65
+ if not stat.S_ISDIR(os.fstat(root["fd"]).st_mode):
66
+ raise ValueError("Supply pinned directory descriptors")
67
+
68
+ def parent(self, path, write=False, create=False):
69
+ fd, name, _, _ = self.resolve(path, write, create, 0, False)
70
+ return fd, name
71
+
72
+ def resolve(self, path, write, create, links, must_exist):
73
+ if not valid_path(path):
74
+ raise ValueError("Supply a valid absolute native path")
75
+ path = os.path.normpath(path)
76
+ roots = self.roots["write"] if write else self.roots["read"] + self.roots["write"]
77
+ matches = [root for root in roots if within(root["path"], path)]
78
+ if not matches:
79
+ raise ScopeDenied("Native path is outside the supplied roots")
80
+ root = max(matches, key=lambda entry: len(entry["path"]))
81
+ fd = os.dup(root["fd"])
82
+ current = root["path"]
83
+ parts = os.path.relpath(path, current).split("/")
84
+ return self.walk(fd, current, parts, write, create, links, must_exist)
85
+
86
+ def walk(self, fd, current, parts, write, create, links, must_exist):
87
+ try:
88
+ for index, name in enumerate(parts):
89
+ final = index == len(parts) - 1
90
+ try:
91
+ info = os.stat(name, dir_fd=fd, follow_symlinks=False)
92
+ except FileNotFoundError:
93
+ if not final and create:
94
+ try:
95
+ os.mkdir(name, 0o755, dir_fd=fd)
96
+ except FileExistsError:
97
+ pass
98
+ info = os.stat(name, dir_fd=fd, follow_symlinks=False)
99
+ elif final and not must_exist:
100
+ return fd, name, os.path.normpath(os.path.join(current, name)), links
101
+ else:
102
+ raise
103
+ if stat.S_ISLNK(info.st_mode):
104
+ if links >= 40:
105
+ raise OSError(errno.ELOOP, "Too many symbolic links")
106
+ target = os.readlink(name, dir_fd=fd)
107
+ after = os.stat(name, dir_fd=fd, follow_symlinks=False)
108
+ if (info.st_dev, info.st_ino) != (after.st_dev, after.st_ino):
109
+ raise ScopeDenied("Native path changed during resolution")
110
+ target = os.path.normpath(os.path.join(current, target))
111
+ os.close(fd)
112
+ fd = None
113
+ # Resolve the target once. Writes require an existing target; the returned
114
+ # descriptor/name is reused, including when a directory has a suffix to walk.
115
+ fd, linked_name, resolved, links = self.resolve(
116
+ target, write, False, links + 1, must_exist or write)
117
+ if final:
118
+ return fd, linked_name, resolved, links
119
+ try:
120
+ child = os.open(linked_name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW,
121
+ dir_fd=fd)
122
+ except NotADirectoryError:
123
+ if not write:
124
+ raise FileNotFoundError(errno.ENOENT, "Native target does not exist")
125
+ raise
126
+ os.close(fd)
127
+ fd = None
128
+ return self.walk(child, resolved, parts[index + 1:], write, create,
129
+ links, must_exist)
130
+ if final:
131
+ return fd, name, os.path.normpath(os.path.join(current, name)), links
132
+ if not write and not stat.S_ISDIR(info.st_mode):
133
+ # Existing readers treat ENOTDIR in an ancestor as a missing target.
134
+ raise FileNotFoundError(errno.ENOENT, "Native target does not exist")
135
+ child = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd)
136
+ os.close(fd)
137
+ fd = child
138
+ current = os.path.join(current, name)
139
+ except BaseException:
140
+ if fd is not None:
141
+ os.close(fd)
142
+ raise
143
+
144
+ def open(self, path, write=False, directory=False):
145
+ parent, name = self.parent(path, write, write)
146
+ try:
147
+ flags = os.O_NOFOLLOW | os.O_NONBLOCK
148
+ flags |= os.O_WRONLY | os.O_CREAT if write else os.O_RDONLY
149
+ if directory:
150
+ flags |= os.O_DIRECTORY
151
+ return os.open(name, flags, 0o600, dir_fd=parent)
152
+ finally:
153
+ os.close(parent)
154
+
155
+ def metadata(self, path):
156
+ parent, name = self.parent(path)
157
+ try:
158
+ value = os.stat(name, dir_fd=parent, follow_symlinks=False)
159
+ if stat.S_ISLNK(value.st_mode):
160
+ raise ScopeDenied("Native path changed during resolution")
161
+ return value
162
+ finally:
163
+ os.close(parent)
164
+
165
+ def entries(self, fd):
166
+ # Dirent type data works even when child metadata cannot be searched. If the
167
+ # filesystem needs a metadata fallback, propagate its errors instead of dropping names.
168
+ with os.scandir(fd) as entries:
169
+ result = [(entry.name, entry.is_dir(follow_symlinks=False), entry.is_symlink())
170
+ for entry in entries]
171
+ return sorted(result, key=lambda entry: units(entry[0]))
172
+
173
+ def listing(self, path, limit):
174
+ fd = self.open(path, directory=True)
175
+ try:
176
+ entries = self.entries(fd)
177
+ result = []
178
+ for name, is_dir, is_link in entries[:limit]:
179
+ if is_link:
180
+ try:
181
+ is_dir = stat.S_ISDIR(self.metadata(os.path.join(path, name)).st_mode)
182
+ except (OSError, ScopeDenied, ValueError):
183
+ is_dir = False
184
+ result.append({"name": name, "isDir": is_dir})
185
+ return {"entries": result, "truncated": len(entries) > limit}
186
+ finally:
187
+ os.close(fd)
188
+
189
+ def scan(self, base):
190
+ # Exactly the SDK traversal: sorted breadth-first levels, count all attempted reads,
191
+ # descend past hits/invalid candidate names, then sort/filter/truncate the final answer.
192
+ base = os.path.normpath(base)
193
+ level = [base]
194
+ found = []
195
+ visits = 0
196
+ depth = 0
197
+ while level and visits < MAX_VISITS:
198
+ next_level = []
199
+ for path in sorted(level, key=units):
200
+ if visits >= MAX_VISITS:
201
+ break
202
+ visits += 1
203
+ try:
204
+ fd = self.open(path, directory=True)
205
+ try:
206
+ entries = self.entries(fd)
207
+ finally:
208
+ os.close(fd)
209
+ except FileNotFoundError:
210
+ if depth == 0:
211
+ return []
212
+ continue
213
+ except (OSError, ScopeDenied, ValueError):
214
+ if depth == 0:
215
+ raise
216
+ continue
217
+ if any(name == ".git" or (name == "AGENTS.md" and not is_dir)
218
+ for name, is_dir, _ in entries):
219
+ found.append(path)
220
+ if depth < MAX_DEPTH:
221
+ for name, is_dir, is_link in entries:
222
+ if (is_dir and not is_link and not name.startswith(".")
223
+ and name not in SKIP_ANY and not (depth == 0 and name in SKIP_BASE)):
224
+ next_level.append(os.path.join(path, name))
225
+ level = next_level
226
+ depth += 1
227
+ return [{"path": path, "suggestedName": os.path.basename(path)}
228
+ for path in sorted(set(found), key=units)
229
+ if valid_name(os.path.basename(path)) and valid_path(path)][:MAX_RESULTS]
230
+
231
+ def run(self, request):
232
+ method = request["method"]
233
+ path = request["path"]
234
+ if not valid_path(path):
235
+ raise ValueError("Supply a valid absolute native path")
236
+ if method in ("readFile", "list"):
237
+ bound = request["maxBytes" if method == "readFile" else "limit"]
238
+ if type(bound) is not int or bound < 0 or bound > 9007199254740991:
239
+ raise ValueError("Supply a nonnegative integer byte or entry limit")
240
+ if method == "scan":
241
+ return self.scan(path)
242
+ try:
243
+ if method == "stat":
244
+ info = self.metadata(path)
245
+ return {"size": info.st_size, "isDir": stat.S_ISDIR(info.st_mode)}
246
+ if method == "list":
247
+ return self.listing(path, bound)
248
+ if method == "readFile":
249
+ fd = self.open(path)
250
+ try:
251
+ info = os.fstat(fd)
252
+ if stat.S_ISDIR(info.st_mode):
253
+ return None
254
+ if not stat.S_ISREG(info.st_mode):
255
+ raise ValueError("Native reads require a regular file")
256
+ want = min(info.st_size, bound)
257
+ data = bytearray()
258
+ while len(data) < want:
259
+ chunk = os.read(fd, want - len(data))
260
+ if not chunk:
261
+ break
262
+ data.extend(chunk)
263
+ finally:
264
+ os.close(fd)
265
+ return {"dataB64": base64.b64encode(data).decode("ascii"),
266
+ "truncated": info.st_size > bound}
267
+ if method == "writeFile":
268
+ data = base64.b64decode(request["dataB64"], validate=True)
269
+ fd = self.open(path, write=True)
270
+ try:
271
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
272
+ raise ValueError("Native writes require a regular file")
273
+ os.ftruncate(fd, 0)
274
+ remaining = memoryview(data)
275
+ while remaining:
276
+ written = os.write(fd, remaining)
277
+ if written == 0:
278
+ raise OSError(errno.EIO, "Native write made no progress")
279
+ remaining = remaining[written:]
280
+ finally:
281
+ os.close(fd)
282
+ return None
283
+ raise ValueError("Unknown native method")
284
+ except FileNotFoundError:
285
+ if method != "writeFile":
286
+ return None
287
+ raise
288
+ except IsADirectoryError:
289
+ if method == "readFile":
290
+ return None
291
+ raise
292
+
293
+ def main():
294
+ try:
295
+ request = json.load(sys.stdin)
296
+ result = NativeFiles(request["roots"]).run(request)
297
+ response = {"result": result}
298
+ except Exception as error:
299
+ code = ("SCOPE_DENIED" if isinstance(error, ScopeDenied)
300
+ else errno.errorcode.get(getattr(error, "errno", None), "INVALID_NATIVE_REQUEST"))
301
+ # Do not expose symlink targets or other resolved paths in transport errors.
302
+ response = {"error": {"code": code, "message": "Native operation failed; check the path, scope and filesystem access"}}
303
+ print(json.dumps(response), flush=True)
304
+
305
+ if __name__ == "__main__":
306
+ main()
307
+ `;