An open-source, faster Devin alternative
TypeScript
add a command driver to mounts, run a user-provided FUSE daemon, not just rclone
Brian Reardond8d9e122ee8a
diff --git a/cmd/oc/internal/commands/mounts.go b/cmd/oc/internal/commands/mounts.goindex be7a564d..b4458628 100644--- a/cmd/oc/internal/commands/mounts.go+++ b/cmd/oc/internal/commands/mounts.go@@ -13,11 +13,14 @@ import (// MountInfo mirrors internal/mounts.MountRecord — copied here to avoid an// internal-package import from the CLI binary.type MountInfo struct {- Path string `json:"path"`- Remote string `json:"remote"`- Backend string `json:"backend,omitempty"`- ReadOnly bool `json:"readOnly"`- RcloneVersion string `json:"rcloneVersion,omitempty"`+ Path string `json:"path"`+ Driver string `json:"driver"`+ ReadOnly bool `json:"readOnly"`+ Remote string `json:"remote,omitempty"`+ Backend string `json:"backend,omitempty"`+ RcloneVersion string `json:"rcloneVersion,omitempty"`+ Command []string `json:"command,omitempty"`+ Env map[string]string `json:"env,omitempty"`}var mountsCmd = &cobra.Command{@@ -44,36 +47,59 @@ var mountsAddCmd = &cobra.Command{configFile, _ := cmd.Flags().GetString("config-file")readWrite, _ := cmd.Flags().GetBool("read-write")extraOpts, _ := cmd.Flags().GetStringArray("opt")-- creds := map[string]string{}- for _, kv := range credsFlag {- i := strings.Index(kv, "=")- if i <= 0 {- return fmt.Errorf("--cred must be key=value (got %q)", kv)- }- creds[kv[:i]] = kv[i+1:]- }+ command, _ := cmd.Flags().GetStringArray("command")+ envFlag, _ := cmd.Flags().GetStringArray("env")+ secretFlag, _ := cmd.Flags().GetStringArray("secret")body := map[string]any{"path": path,- "remote": remote,"readOnly": !readWrite,}- if backend != "" {- body["backend"] = backend- }- if len(creds) > 0 {- body["creds"] = creds- }- if configFile != "" {- raw, err := os.ReadFile(configFile)++ if len(command) > 0 {+ // command driver — bring your own FUSE daemon / mount command.+ body["driver"] = "command"+ body["command"] = command+ env, err := parseKV(envFlag, "--env")if err != nil {- return fmt.Errorf("read --config-file: %w", err)+ return err+ }+ if len(env) > 0 {+ body["env"] = env+ }+ secrets, err := parseKV(secretFlag, "--secret")+ if err != nil {+ return err+ }+ if len(secrets) > 0 {+ body["secrets"] = secrets+ }+ } else {+ // rclone driver (default).+ if remote == "" {+ return fmt.Errorf("--remote is required (or pass --command to run your own FUSE daemon)")+ }+ body["remote"] = remote+ creds, err := parseKV(credsFlag, "--cred")+ if err != nil {+ return err+ }+ if backend != "" {+ body["backend"] = backend+ }+ if len(creds) > 0 {+ body["creds"] = creds+ }+ if configFile != "" {+ raw, err := os.ReadFile(configFile)+ if err != nil {+ return fmt.Errorf("read --config-file: %w", err)+ }+ body["rcloneConfig"] = string(raw)+ }+ if len(extraOpts) > 0 {+ body["mountOptions"] = extraOpts}- body["rcloneConfig"] = string(raw)- }- if len(extraOpts) > 0 {- body["mountOptions"] = extraOpts}var info MountInfo@@ -86,7 +112,11 @@ var mountsAddCmd = &cobra.Command{if info.ReadOnly {ro = "ro"}- fmt.Printf("Mounted %s → %s (%s)\n", info.Remote, info.Path, ro)+ src := info.Remote+ if info.Driver == "command" {+ src = strings.Join(info.Command, " ")+ }+ fmt.Printf("Mounted %s → %s (%s)\n", src, info.Path, ro)})return nil},@@ -109,14 +139,22 @@ var mountsListCmd = &cobra.Command{fmt.Println("No mounts.")return}- headers := []string{"PATH", "REMOTE", "BACKEND", "MODE", "RCLONE"}+ headers := []string{"PATH", "DRIVER", "SOURCE", "MODE"}var rows [][]stringfor _, m := range mounts {mode := "rw"if m.ReadOnly {mode = "ro"}- rows = append(rows, []string{m.Path, m.Remote, m.Backend, mode, m.RcloneVersion})+ driver := m.Driver+ if driver == "" {+ driver = "rclone"+ }+ source := m.Remote+ if m.Driver == "command" {+ source = strings.Join(m.Command, " ")+ }+ rows = append(rows, []string{m.Path, driver, source, mode})}printer.Table(headers, rows)})@@ -141,16 +179,33 @@ var mountsRemoveCmd = &cobra.Command{},}+// parseKV turns repeated "key=value" flag values into a map.+func parseKV(pairs []string, flag string) (map[string]string, error) {+ out := map[string]string{}+ for _, kv := range pairs {+ i := strings.Index(kv, "=")+ if i <= 0 {+ return nil, fmt.Errorf("%s must be key=value (got %q)", flag, kv)+ }+ out[kv[:i]] = kv[i+1:]+ }+ return out, nil+}+func init() {mountsAddCmd.Flags().String("path", "", "Absolute path inside the sandbox to mount at (required)")- mountsAddCmd.Flags().String("remote", "", "rclone remote spec, e.g. s3:my-bucket (required)")+ // rclone driver (default)+ mountsAddCmd.Flags().String("remote", "", "rclone remote spec, e.g. s3:my-bucket (rclone driver)")mountsAddCmd.Flags().String("backend", "", "Backend type: s3, gcs, azureblob, sftp, webdav, dropbox")mountsAddCmd.Flags().StringArray("cred", nil, "Backend credential as key=value (repeatable; e.g. --cred access_key_id=AKIA...)")mountsAddCmd.Flags().String("config-file", "", "Path to a raw rclone config file (overrides --backend/--cred)")- mountsAddCmd.Flags().Bool("read-write", false, "Mount read-write (default is read-only)")mountsAddCmd.Flags().StringArray("opt", nil, "Extra args appended to `rclone mount` (repeatable)")+ // command driver (bring your own FUSE)+ mountsAddCmd.Flags().StringArray("command", nil, "FUSE daemon/mount argv (repeatable; switches to the command driver). {mountpoint} is replaced with --path")+ mountsAddCmd.Flags().StringArray("env", nil, "Env var for the command as key=value (repeatable)")+ mountsAddCmd.Flags().StringArray("secret", nil, "Secret env var as key=value (repeatable; injected into the daemon env, never recorded)")+ mountsAddCmd.Flags().Bool("read-write", false, "Mount read-write (default is read-only)")_ = mountsAddCmd.MarkFlagRequired("path")- _ = mountsAddCmd.MarkFlagRequired("remote")mountsCmd.AddCommand(mountsAddCmd)mountsCmd.AddCommand(mountsListCmd)diff --git a/docs/sandboxes/mounts.mdx b/docs/sandboxes/mounts.mdxindex 807680bd..0c2b62b6 100644--- a/docs/sandboxes/mounts.mdx+++ b/docs/sandboxes/mounts.mdx@@ -1,20 +1,36 @@---title: "Mounts"-description: "Mount S3, GCS, Azure Blob, SFTP, WebDAV, and Dropbox into a sandbox via FUSE"+description: "Mount remote filesystems into a sandbox via FUSE — rclone's ~40 backends, or your own FUSE daemon"tag: "Preview"---<Note>**Preview:** the mounts API is new. Endpoints, request shape, and SDK- method names may change before GA. Backend coverage is rclone's — works- for the listed providers today; expect rough edges on less-tested- backends.+ method names may change before GA.</Note>-Mount remote filesystems directly into your sandbox so your code reads and-writes them like local files — no SDK calls, no chunked downloads, no-boilerplate. Perfect for pulling in datasets, model weights, or a customer's-bucket without staging anything to disk first.+Mount filesystems directly into your sandbox so your code reads and writes them+like local files — no SDK calls, no chunked downloads, no boilerplate. Perfect+for pulling in datasets, model weights, or a customer's bucket without staging+anything to disk first.++## Two drivers++A FUSE mount is a userspace daemon that serves a filesystem under a mountpoint.+The platform manages the mountpoint, secret injection, and teardown — the+*driver* decides which daemon establishes the mount:++| Driver | When to use | What you pass |+| --- | --- | --- |+| **`rclone`** (default) | You want S3 / GCS / Azure Blob / SFTP / WebDAV / Dropbox and ~35 more, behind a simple creds shape. | `remote` + `backend` + `creds` |+| **`command`** | You already have a FUSE-ready filesystem (your own VFS, gcsfuse, s3fs, …) and don't want rclone as a middle layer. | a `command` (the daemon's argv) + `env`/`secrets` |++Both share the same lifecycle (`list`, `remove`, hibernate survival) and the+same secret guarantee — credentials never persist on the worker.++## rclone driver++Wrap any of rclone's backends behind `remote` + `backend` + `creds`:```typescriptimport { Sandbox } from "@opencomputer/sdk";@@ -37,11 +53,12 @@ await sandbox.exec.run("ls /mnt/data");await sandbox.exec.run("head /mnt/data/train.csv");```-## How It Works+## How the rclone driver works-Mounts use [`rclone mount`](https://rclone.org/commands/rclone_mount/) under-the hood — a single binary that speaks ~40 backends (S3, GCS, Azure Blob,-SFTP, WebDAV, Dropbox, and more). When you call `mounts.add()`:+The rclone driver uses [`rclone mount`](https://rclone.org/commands/rclone_mount/)+under the hood — a single binary that speaks ~40 backends (S3, GCS, Azure Blob,+SFTP, WebDAV, Dropbox, and more). When you call `mounts.add()` without a+`driver` (or `driver: "rclone"`):1. The control plane templates an rclone config from your `backend` + `creds`.2. The config is written to a tmpfs file inside the VM (mode `0600` — the@@ -211,21 +228,148 @@ await sandbox.mounts.add({artifacts.</Warning>+## command driver — bring your own FUSE++If you already have a FUSE-ready filesystem, skip rclone entirely. Pass+`driver: "command"` with the daemon's argv; the platform runs it as the sandbox+user, injects your env/secrets, waits for the mount to come live, and tears it+down on `remove` — the same lifecycle as an rclone mount.++<CodeGroup>++```typescript TypeScript+await sandbox.mounts.add({+ path: "/mnt/data",+ driver: "command",+ command: ["my-vfs-fuse", "--bucket", "gs://my-bucket", "{mountpoint}"],+ secrets: { MY_VFS_TOKEN: process.env.MY_VFS_TOKEN! },+});+```++```python Python+await sandbox.mounts.add_command(+ path="/mnt/data",+ command=["my-vfs-fuse", "--bucket", "gs://my-bucket", "{mountpoint}"],+ secrets={"MY_VFS_TOKEN": os.environ["MY_VFS_TOKEN"]},+)+```++</CodeGroup>++### The `{mountpoint}` token++`{mountpoint}` (or `{path}`) in your argv is replaced with `path` before the+command runs, so you don't repeat the path twice. The call above runs:++```+my-vfs-fuse --bucket gs://my-bucket /mnt/data+```++You can also hardcode the path — the token is just a convenience.++### env and secrets++- **`env`** — plain environment variables for the daemon. Recorded and returned+ by `list()`.+- **`secrets`** — credentials. Injected into the daemon's **process+ environment** (never the command line, so they don't leak via `ps`), never+ written to disk on the worker, and never returned by `list()`.++Both end up in the daemon's environment; the only difference is that `secrets`+are kept out of every record and response. For daemons that need a credentials+*file* (e.g. a service-account JSON), write it first with the+[filesystem API](/sandboxes/filesystem) and point the command at it.++### Read-only++`readOnly` is **advisory** for this driver — your command must honor it (we+also export `OC_MOUNT_READONLY=1` so the daemon can read the intent). Unlike+rclone, the platform can't enforce read-only on an arbitrary daemon.++### Requirements++Your daemon must:++- be present in the sandbox — bake it into your image, or install/download it at+ runtime before mounting;+- mount at the mountpoint and keep running (a foreground daemon is fine — we+ background it; a self-daemonizing one works too);+- exit when its mount is unmounted (standard libfuse behavior) so `remove`+ cleans up.++The platform handles the rest: `/dev/fuse` access, creating the mountpoint, and+`-o allow_other` support (`user_allow_other` is set in `/etc/fuse.conf`).++If the mount doesn't come up within the timeout, the call fails with the+**daemon's own log tail** so you can see why (a bad flag, missing binary, auth+error, etc.).++### Example: gcsfuse (GCS, no rclone)++[gcsfuse](https://cloud.google.com/storage/docs/gcsfuse-install) is Google's own+GCS-to-FUSE adapter. Run it directly via the command driver — no rclone in the+middle. Install it in your image (or at runtime), write your service-account key+with the [filesystem API](/sandboxes/filesystem), and mount:++```typescript+// 1. write the service-account JSON into the sandbox (tmpfs)+await sandbox.files.write("/run/gcp-sa.json", process.env.GCP_SA_JSON!);++// 2. run gcsfuse via the command driver+await sandbox.mounts.add({+ path: "/mnt/bucket",+ driver: "command",+ command: [+ "gcsfuse", "--foreground", "--implicit-dirs",+ "-o", "allow_other",+ "--key-file", "/run/gcp-sa.json",+ "my-bucket", "{mountpoint}",+ ],+});++await sandbox.exec.run("ls /mnt/bucket"); // GCS objects, read like local files+```++For a **public** bucket, skip the key and pass `--anonymous-access`:++```typescript+command: ["gcsfuse", "--foreground", "--anonymous-access", "-o", "allow_other",+ "gcp-public-data-landsat", "{mountpoint}"],+```++### Example: bindfs++A minimal local FUSE — mirror one directory onto another path:++```typescript+await sandbox.exec.run("apt-get update && apt-get install -y bindfs");+await sandbox.mounts.add({+ path: "/mnt/mirror",+ driver: "command",+ command: ["bindfs", "-f", "-o", "allow_other", "/home/sandbox/data", "{mountpoint}"],+ readOnly: false,+});+// reads/writes under /mnt/mirror now pass through to /home/sandbox/data+```+## Listing and removing+`list()` returns both driver shapes:+```typescriptconst mounts = await sandbox.mounts.list();-// [{ path: "/mnt/data", remote: "s3:my-bucket", backend: "s3", readOnly: true }]+// rclone: { path: "/mnt/data", driver: "rclone", remote: "s3:my-bucket", backend: "s3", readOnly: true }+// command: { path: "/mnt/mirror", driver: "command", command: ["bindfs", "-f", ...], readOnly: false }-await sandbox.mounts.remove("/mnt/data");+await sandbox.mounts.remove("/mnt/data"); // fusermount3 -u, same for both drivers```## Hibernate behavior-Mounts survive hibernate/wake transparently. The VM snapshot captures the live-FUSE mount and the rclone daemon process; when the sandbox wakes, both are-restored as-is. No re-mount call needed — the mount is exactly where you left-it, with the same credentials, serving the same path.+Mounts survive hibernate/wake transparently, **for both drivers**. The VM+snapshot captures the live FUSE mount and the daemon process — rclone or your+own — and `wake` restores both as-is. No re-mount call needed; the mount is+exactly where you left it, serving the same path.```typescriptawait sandbox.mounts.add({ path: "/mnt/data", remote: "s3:my-bucket", backend: "s3", creds });@@ -255,6 +399,8 @@ credentials.## CLI+rclone driver:+```bashoc mounts add sb-abc123 \--path /mnt/data \@@ -274,17 +420,34 @@ For raw rclone configs, point `--config-file` at a local file:oc mounts add sb-abc123 --path /mnt/box --remote box:Reports --config-file ./rclone.conf```+Command driver — pass `--command` (repeat per argv element) to run your own+FUSE daemon; `--env`/`--secret` take `key=value`:++```bash+oc mounts add sb-abc123 \+ --path /mnt/mirror \+ --command bindfs --command -f --command -o --command allow_other \+ --command /home/sandbox/data --command '{mountpoint}' \+ --secret MY_VFS_TOKEN=...+```+## Troubleshooting**`sandbox image is missing rclone and/or fusermount3`** — the sandbox is-running on an older base image. Recreate the sandbox from the latest default-template or build a new image off the current `Dockerfile.default`.--**Mount succeeds but `ls` returns empty** — usually a creds / permission issue-on the remote side rather than a mount issue. SSH in (`oc shell`) and run+running on an older base image. The rclone driver needs both `rclone` and+`fusermount3`; the command driver needs only `fusermount3`. Recreate the sandbox+from the latest default template, or build an image off the current+`Dockerfile.default`.++**`mount command did not produce a live mount … within timeout`** (command+driver) — the error includes your daemon's **log tail**. Common causes: the+binary isn't installed in the sandbox, a bad flag, or an auth failure. Reproduce+by hand with `oc shell` and run the same command.++**Mount succeeds but `ls` returns empty** (rclone driver) — usually a creds /+permission issue on the remote side. SSH in (`oc shell`) and run`rclone ls <remote>: --config /run/oc-agent/mounts/<id>.conf` to see the real-error. Or just `ls -la` the mount point — FUSE errors surface as filesystem-errors there.+error. Or `ls -la` the mount point — FUSE errors surface as filesystem errors.**`fuse: bad mount point ... permission denied`** — make sure the target pathisn't already a non-empty directory you don't own. The mount call creates thediff --git a/internal/mounts/service.go b/internal/mounts/service.goindex b39d80c1..c36b170f 100644--- a/internal/mounts/service.go+++ b/internal/mounts/service.go@@ -18,37 +18,69 @@ import ("sort""strings""sync"+ "time""github.com/opensandbox/opensandbox/internal/sandbox""github.com/opensandbox/opensandbox/pkg/types")-// MountRecord describes one rclone-backed FUSE mount inside a sandbox.-// Process-local — tracks what was added via this worker. Credentials are-// not stored anywhere outside the in-VM tmpfs config file.+// Mount drivers. "rclone" wraps any of rclone's ~40 backends behind a simple+// remote+creds shape (the easy path). "command" runs a user-provided FUSE+// daemon / mount command directly — for callers who already have a FUSE-ready+// filesystem (their own VFS, gcsfuse, s3fs, …) and don't want rclone as a+// middle layer. Both share the same lifecycle: managed mountpoint, secret+// injection, listing, and teardown.+const (+ DriverRclone = "rclone"+ DriverCommand = "command"+)++// MountRecord describes one FUSE mount inside a sandbox. Process-local — tracks+// what was added via this worker. Credentials are never stored: rclone creds+// live only in the in-VM tmpfs config file; command-driver secrets are injected+// as process env (in-guest only) and deliberately omitted from this record.//-// RcloneVersion is captured at mount-add time. rclone gets installed in the-// rootfs at image-build time, so different sandboxes can be on different-// versions depending on which rootfs they cold-booted from. Surfacing this-// lets ops triage "my S3 mount is broken" reports quickly — "you're on+// RcloneVersion is captured at mount-add time for the rclone driver. rclone gets+// installed in the rootfs at image-build time, so different sandboxes can be on+// different versions depending on which rootfs they cold-booted from. Surfacing+// this lets ops triage "my S3 mount is broken" reports quickly — "you're on// v1.62, the fix is in v1.65, recreate the sandbox".type MountRecord struct {- Path string `json:"path"`- Remote string `json:"remote"`+ Path string `json:"path"`+ Driver string `json:"driver"` // "rclone" | "command"+ ReadOnly bool `json:"readOnly"`++ // rclone driver+ Remote string `json:"remote,omitempty"`Backend string `json:"backend,omitempty"`- ReadOnly bool `json:"readOnly"`RcloneVersion string `json:"rcloneVersion,omitempty"`++ // command driver — the resolved argv and non-secret env (secrets omitted).+ Command []string `json:"command,omitempty"`+ Env map[string]string `json:"env,omitempty"`}// AddRequest is the wire shape the HTTP layer parses and hands to Service.Add.type AddRequest struct {- Path string `json:"path"` // absolute path inside the VM- Remote string `json:"remote"` // rclone remote spec, e.g. "s3:my-bucket/sub"- Backend string `json:"backend"` // s3, gcs, azureblob, sftp, webdav, dropbox- Creds map[string]string `json:"creds"` // backend-specific config keys- RcloneConfig string `json:"rcloneConfig"` // raw config; overrides backend+creds- ReadOnly *bool `json:"readOnly"` // default true- MountOptions []string `json:"mountOptions"` // extra args appended to `rclone mount`+ Path string `json:"path"` // absolute mountpoint inside the VM+ Driver string `json:"driver,omitempty"` // "rclone" (default) | "command"+ ReadOnly *bool `json:"readOnly"` // default true++ // rclone driver (default).+ Remote string `json:"remote,omitempty"` // rclone remote spec, e.g. "s3:my-bucket/sub"+ Backend string `json:"backend,omitempty"` // s3, gcs, azureblob, sftp, webdav, dropbox+ Creds map[string]string `json:"creds,omitempty"` // backend-specific config keys+ RcloneConfig string `json:"rcloneConfig,omitempty"` // raw config; overrides backend+creds+ MountOptions []string `json:"mountOptions,omitempty"` // extra args appended to `rclone mount`++ // command driver — run a user-provided FUSE daemon / mount command. The+ // platform manages the mountpoint, env/secret injection, and teardown; the+ // command itself establishes the FUSE mount. "{mountpoint}" tokens in the+ // argv are replaced with the resolved mount path. readOnly is advisory for+ // this driver (the daemon must honor it; we also pass OC_MOUNT_READONLY).+ Command []string `json:"command,omitempty"` // argv; required for the command driver+ Env map[string]string `json:"env,omitempty"` // env vars (recorded, returned by list)+ Secrets map[string]string `json:"secrets,omitempty"` // secret env vars; injected, never recorded/returned}// Service is the rclone-mount orchestrator. Process-local Registry tracks@@ -78,35 +110,66 @@ func (s *Service) List(sandboxID string) []MountRecord {}// Add validates the request, performs the live mount in the sandbox, and-// records the in-memory entry.+// records the in-memory entry. Dispatches on driver — "rclone" (default) or+// "command".func (s *Service) Add(ctx context.Context, sandboxID string, req AddRequest) (MountRecord, error) {- if req.Path == "" || req.Remote == "" {- return MountRecord{}, fmt.Errorf("path and remote are required")+ if req.Path == "" {+ return MountRecord{}, fmt.Errorf("path is required")}if !strings.HasPrefix(req.Path, "/") {return MountRecord{}, fmt.Errorf("path must be absolute")}-- rcloneConf, err := renderRcloneConfig(req)- if err != nil {- return MountRecord{}, err+ driver := req.Driver+ if driver == "" {+ driver = DriverRclone}readOnly := trueif req.ReadOnly != nil {readOnly = *req.ReadOnly}- if err := s.doMount(ctx, sandboxID, req.Path, req.Remote, rcloneConf, readOnly, req.MountOptions); err != nil {- return MountRecord{}, err- }+ var rec MountRecord+ switch driver {+ case DriverRclone:+ if req.Remote == "" {+ return MountRecord{}, fmt.Errorf("remote is required for the rclone driver")+ }+ rcloneConf, err := renderRcloneConfig(req)+ if err != nil {+ return MountRecord{}, err+ }+ if err := s.doMountRclone(ctx, sandboxID, req.Path, req.Remote, rcloneConf, readOnly, req.MountOptions); err != nil {+ return MountRecord{}, err+ }+ rec = MountRecord{+ Path: req.Path,+ Driver: DriverRclone,+ ReadOnly: readOnly,+ Remote: req.Remote,+ Backend: req.Backend,+ RcloneVersion: s.probeRcloneVersion(ctx, sandboxID),+ }++ case DriverCommand:+ if len(req.Command) == 0 {+ return MountRecord{}, fmt.Errorf("command is required for the command driver")+ }+ argv := substituteMountpoint(req.Command, req.Path)+ if err := s.doMountCommand(ctx, sandboxID, req.Path, argv, req.Env, req.Secrets, readOnly); err != nil {+ return MountRecord{}, err+ }+ rec = MountRecord{+ Path: req.Path,+ Driver: DriverCommand,+ ReadOnly: readOnly,+ Command: argv,+ Env: req.Env,+ }- rec := MountRecord{- Path: req.Path,- Remote: req.Remote,- Backend: req.Backend,- ReadOnly: readOnly,- RcloneVersion: s.probeRcloneVersion(ctx, sandboxID),+ default:+ return MountRecord{}, fmt.Errorf("unsupported driver %q (supported: %q, %q)", driver, DriverRclone, DriverCommand)}+s.registry.put(sandboxID, rec)return rec, nil}@@ -139,35 +202,71 @@ func (s *Service) Remove(ctx context.Context, sandboxID, path string) error {return nil}-// doMount is the shared orchestration: probe rclone is present, write the-// config to tmpfs, mkdir the target, exec `rclone mount --daemon`.-//-// `remote` is the full rclone remote spec passed to `rclone mount` (e.g.-// "s3:my-bucket/prefix"). It is NOT derived from the config section header-// because rclone needs the `<name>:<path>` form — bare `<name>` makes rclone-// fall back to its local-filesystem backend at `~/<name>` with no error,-// which surfaces as a silently-empty mount target.-func (s *Service) doMount(ctx context.Context, sandboxID, target, remote, rcloneConf string, readOnly bool, mountOptions []string) error {- confPath := mountConfPath(target)-- probe, perr := s.manager.Exec(ctx, sandboxID, types.ProcessConfig{+// probeFUSE checks the sandbox image has the FUSE userspace bits. rclone is+// only required for the rclone driver; fusermount3 is required for both.+func (s *Service) probeFUSE(ctx context.Context, sandboxID string, needRclone bool) error {+ test := "command -v fusermount3 >/dev/null 2>&1"+ missing := "`fusermount3`"+ if needRclone {+ test = "command -v rclone >/dev/null 2>&1 && " + test+ missing = "`rclone` and/or `fusermount3`"+ }+ probe, err := s.manager.Exec(ctx, sandboxID, types.ProcessConfig{Command: "sh",- Args: []string{"-c", "command -v rclone >/dev/null 2>&1 && command -v fusermount3 >/dev/null 2>&1"},+ Args: []string{"-c", test},Timeout: 10,})- if perr != nil {- return fmt.Errorf("probe sandbox: %w", perr)+ if err != nil {+ return fmt.Errorf("probe sandbox: %w", err)}if probe == nil || probe.ExitCode != 0 {- return fmt.Errorf("sandbox image is missing `rclone` and/or `fusermount3` — rebuild from the latest default rootfs to use mounts")+ return fmt.Errorf("sandbox image is missing %s — rebuild from the latest default rootfs to use mounts", missing)}+ return nil+}+// ensureMountsDir creates the root-owned 0700 tmpfs dir that holds rclone+// config files (which carry creds) and per-mount logs.+func (s *Service) ensureMountsDir(ctx context.Context, sandboxID string) error {if _, err := s.manager.Exec(ctx, sandboxID, types.ProcessConfig{Command: "sudo",Args: []string{"sh", "-c", "mkdir -p /run/oc-agent/mounts && chmod 700 /run/oc-agent/mounts"},Timeout: 10,}); err != nil {- return fmt.Errorf("prepare config dir: %w", err)+ return fmt.Errorf("prepare mounts dir: %w", err)+ }+ return nil+}++// ensureTarget creates the mountpoint and hands it to the sandbox user so a+// non-root FUSE daemon can mount there.+func (s *Service) ensureTarget(ctx context.Context, sandboxID, target string) error {+ if _, err := s.manager.Exec(ctx, sandboxID, types.ProcessConfig{+ Command: "sudo",+ Args: []string{"sh", "-c", fmt.Sprintf("mkdir -p %q && chown sandbox:sandbox %q", target, target)},+ Timeout: 10,+ }); err != nil {+ return fmt.Errorf("prepare mount target: %w", err)+ }+ return nil+}++// doMountRclone is the rclone-driver orchestration: write the config to tmpfs,+// mkdir the target, exec `rclone mount --daemon`.+//+// `remote` is the full rclone remote spec passed to `rclone mount` (e.g.+// "s3:my-bucket/prefix"). It is NOT derived from the config section header+// because rclone needs the `<name>:<path>` form — bare `<name>` makes rclone+// fall back to its local-filesystem backend at `~/<name>` with no error,+// which surfaces as a silently-empty mount target.+func (s *Service) doMountRclone(ctx context.Context, sandboxID, target, remote, rcloneConf string, readOnly bool, mountOptions []string) error {+ confPath := mountConfPath(target)++ if err := s.probeFUSE(ctx, sandboxID, true); err != nil {+ return err+ }+ if err := s.ensureMountsDir(ctx, sandboxID); err != nil {+ return err}if err := s.manager.WriteFile(ctx, sandboxID, confPath, rcloneConf); err != nil {@@ -181,16 +280,12 @@ func (s *Service) doMount(ctx context.Context, sandboxID, target, remote, rclonereturn fmt.Errorf("chmod config: %w", err)}- if _, err := s.manager.Exec(ctx, sandboxID, types.ProcessConfig{- Command: "sudo",- Args: []string{"sh", "-c", fmt.Sprintf("mkdir -p %q && chown sandbox:sandbox %q", target, target)},- Timeout: 10,- }); err != nil {- return fmt.Errorf("prepare mount target: %w", err)+ if err := s.ensureTarget(ctx, sandboxID, target); err != nil {+ return err}if remote == "" {- return fmt.Errorf("internal: empty remote passed to doMount")+ return fmt.Errorf("internal: empty remote passed to doMountRclone")}mountArgs := []string{@@ -237,11 +332,128 @@ func (s *Service) doMount(ctx context.Context, sandboxID, target, remote, rclonereturn nil}+// doMountCommand runs a user-provided FUSE daemon / mount command. We manage+// the mountpoint, inject env + secrets (via the in-guest process env — never+// the command line, so they don't leak via `ps`), launch the daemon as the+// sandbox user (FUSE works non-root via user_allow_other), and poll until the+// mount is live. The daemon stays running in the background; Remove unmounts it+// (a libfuse daemon exits on its own when its mount goes away).+func (s *Service) doMountCommand(ctx context.Context, sandboxID, target string, argv []string, env, secrets map[string]string, readOnly bool) error {+ if err := s.probeFUSE(ctx, sandboxID, false); err != nil {+ return err+ }+ // The daemon runs as the sandbox user, so /dev/fuse must be openable by it.+ // Some base images ship /dev/fuse as 0600 root (rclone gets away with it by+ // running as root); a user daemon can't. Make it user-accessible — the VM+ // is single-tenant, matching a normal desktop's crw-rw-rw-.+ if _, err := s.manager.Exec(ctx, sandboxID, types.ProcessConfig{+ Command: "sudo",+ Args: []string{"sh", "-c", "[ -e /dev/fuse ] && chmod 0666 /dev/fuse || true"},+ Timeout: 5,+ }); err != nil {+ return fmt.Errorf("prepare /dev/fuse: %w", err)+ }+ if err := s.ensureMountsDir(ctx, sandboxID); err != nil {+ return err+ }+ logPath := mountLogPath(target)+ // The daemon runs as the sandbox user, so its log must live in a dir the+ // sandbox user can write — NOT the root-owned 0700 rclone-config dir (the+ // sandbox can't even traverse into it, so a redirect there fails silently+ // before the daemon starts).+ if _, err := s.manager.Exec(ctx, sandboxID, types.ProcessConfig{+ Command: "sudo",+ Args: []string{"sh", "-c", "mkdir -p /run/oc-agent/mount-logs && chown sandbox:sandbox /run/oc-agent/mount-logs && chmod 700 /run/oc-agent/mount-logs"},+ Timeout: 10,+ }); err != nil {+ return fmt.Errorf("prepare mount log dir: %w", err)+ }+ if err := s.ensureTarget(ctx, sandboxID, target); err != nil {+ return err+ }++ // Merge env + secrets into the process environment. Both go through the+ // agent's process env (not argv), so secret values never appear in `ps`.+ procEnv := make(map[string]string, len(env)+len(secrets)+1)+ for k, v := range env {+ procEnv[k] = v+ }+ for k, v := range secrets {+ procEnv[k] = v+ }+ if readOnly {+ procEnv["OC_MOUNT_READONLY"] = "1"+ }++ // Background the daemon; shQuote each arg so arbitrary user argv is safe.+ quoted := make([]string, len(argv))+ for i, a := range argv {+ quoted[i] = shQuote(a)+ }+ launch := fmt.Sprintf("nohup %s >%s 2>&1 & echo $!", strings.Join(quoted, " "), shQuote(logPath))+ resp, err := s.manager.Exec(ctx, sandboxID, types.ProcessConfig{+ Command: "sh",+ Args: []string{"-c", launch},+ Env: procEnv,+ Timeout: 30,+ })+ if err != nil {+ return fmt.Errorf("launch mount command: %w", err)+ }+ if resp.ExitCode != 0 {+ return fmt.Errorf("launch mount command failed (exit %d): %s", resp.ExitCode, mountErrText(resp))+ }+ pid := strings.TrimSpace(resp.Stdout)++ // Poll until the mount is live. FUSE daemons usually mount in <5s; give a+ // cold first-connect generous headroom. Bail early if the daemon dies+ // before mounting so a bad command fails fast instead of waiting it out.+ for i := 0; i < 30; i++ {+ if chk, _ := s.manager.Exec(ctx, sandboxID, types.ProcessConfig{+ Command: "sh",+ Args: []string{"-c", fmt.Sprintf("mountpoint -q %q && echo MOUNTED", target)},+ Timeout: 5,+ }); chk != nil && strings.Contains(chk.Stdout, "MOUNTED") {+ return nil+ }+ alive, _ := s.manager.Exec(ctx, sandboxID, types.ProcessConfig{+ Command: "sh",+ Args: []string{"-c", fmt.Sprintf("kill -0 %s 2>/dev/null && echo ALIVE", pid)},+ Timeout: 5,+ })+ if alive == nil || !strings.Contains(alive.Stdout, "ALIVE") {+ break // daemon exited without mounting+ }+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-time.After(time.Second):+ }+ }++ // Not mounted: capture the daemon log, tear down, and report.+ logTail := "(no output)"+ if t, _ := s.manager.Exec(ctx, sandboxID, types.ProcessConfig{+ Command: "sh",+ Args: []string{"-c", fmt.Sprintf("tail -n 20 %q 2>/dev/null", logPath)},+ Timeout: 5,+ }); t != nil && strings.TrimSpace(t.Stdout) != "" {+ logTail = strings.TrimSpace(t.Stdout)+ }+ _, _ = s.manager.Exec(ctx, sandboxID, types.ProcessConfig{+ Command: "sh",+ Args: []string{"-c", fmt.Sprintf("kill %s 2>/dev/null; sudo fusermount3 -u %q 2>/dev/null; sudo rm -f %q; true", pid, target, logPath)},+ Timeout: 10,+ })+ return fmt.Errorf("mount command did not produce a live mount at %s within timeout; daemon log:\n%s", target, logTail)+}+func (s *Service) unmountInVM(ctx context.Context, sandboxID, path string) error {confPath := mountConfPath(path)+ logPath := mountLogPath(path)_, err := s.manager.Exec(ctx, sandboxID, types.ProcessConfig{Command: "sudo",- Args: []string{"sh", "-c", fmt.Sprintf("fusermount3 -u %q 2>/dev/null; rm -f %q 2>/dev/null; true", path, confPath)},+ Args: []string{"sh", "-c", fmt.Sprintf("fusermount3 -u %q 2>/dev/null; rm -f %q %q 2>/dev/null; true", path, confPath, logPath)},Timeout: 15,})return err@@ -313,6 +525,43 @@ func mountConfPath(path string) string {return "/run/oc-agent/mounts/" + hex.EncodeToString(sum[:])[:16] + ".conf"}+// mountLogPath is the deterministic tmpfs path for a command-driver daemon's+// stdout/stderr. Lives in a sandbox-owned dir (the daemon runs as the sandbox+// user) — distinct from the root-owned rclone-config dir. Same hashing scheme+// as mountConfPath so add→remove is self-consistent.+func mountLogPath(path string) string {+ sum := sha1.Sum([]byte(path))+ return "/run/oc-agent/mount-logs/" + hex.EncodeToString(sum[:])[:16] + ".log"+}++// shQuote single-quotes a string for safe interpolation into an `sh -c` line,+// so arbitrary user-supplied argv can't break out of the command.+func shQuote(s string) string {+ return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"+}++// substituteMountpoint replaces "{mountpoint}" / "{path}" tokens in the argv+// with the resolved mount path, so command-driver callers can template where+// the mount lands without hardcoding it twice.+func substituteMountpoint(argv []string, target string) []string {+ out := make([]string, len(argv))+ for i, a := range argv {+ a = strings.ReplaceAll(a, "{mountpoint}", target)+ a = strings.ReplaceAll(a, "{path}", target)+ out[i] = a+ }+ return out+}++// mountErrText picks the most useful stderr/stdout text from a process result.+func mountErrText(r *types.ProcessResult) string {+ msg := strings.TrimSpace(r.Stderr)+ if msg == "" {+ msg = strings.TrimSpace(r.Stdout)+ }+ return msg+}+// RenderRcloneConfig builds a single-section rclone config from the typed// backend+creds shape, or returns the raw user-supplied config if present.func RenderRcloneConfig(req AddRequest) (string, error) { return renderRcloneConfig(req) }diff --git a/internal/mounts/service_test.go b/internal/mounts/service_test.gonew file mode 100644index 00000000..2614226b--- /dev/null+++ b/internal/mounts/service_test.go@@ -0,0 +1,144 @@+package mounts++import (+ "context"+ "strings"+ "testing"++ "github.com/opensandbox/opensandbox/internal/sandbox"+ "github.com/opensandbox/opensandbox/pkg/types"+)++// fakeManager implements just the two sandbox.Manager methods the mounts+// service uses (Exec, WriteFile). Embedding the interface means any other+// method would panic if called — a guard that the service only touches these.+type fakeManager struct {+ sandbox.Manager+ calls []types.ProcessConfig+ execFn func(cfg types.ProcessConfig) (*types.ProcessResult, error)+ written map[string]string+}++func (f *fakeManager) Exec(_ context.Context, _ string, cfg types.ProcessConfig) (*types.ProcessResult, error) {+ f.calls = append(f.calls, cfg)+ if f.execFn != nil {+ return f.execFn(cfg)+ }+ return &types.ProcessResult{ExitCode: 0}, nil+}++func (f *fakeManager) WriteFile(_ context.Context, _ string, path, content string) error {+ if f.written == nil {+ f.written = map[string]string{}+ }+ f.written[path] = content+ return nil+}++func argsContain(args []string, sub string) bool {+ for _, a := range args {+ if strings.Contains(a, sub) {+ return true+ }+ }+ return false+}++func TestAdd_CommandDriver_HappyPath_SecretsViaEnvNotArgv(t *testing.T) {+ fm := &fakeManager{}+ var launch types.ProcessConfig+ fm.execFn = func(cfg types.ProcessConfig) (*types.ProcessResult, error) {+ switch {+ case argsContain(cfg.Args, "mountpoint -q"):+ return &types.ProcessResult{ExitCode: 0, Stdout: "MOUNTED"}, nil+ case argsContain(cfg.Args, "nohup"):+ launch = cfg+ return &types.ProcessResult{ExitCode: 0, Stdout: "4242"}, nil+ default:+ return &types.ProcessResult{ExitCode: 0}, nil+ }+ }+ svc := NewService(fm)++ rec, err := svc.Add(context.Background(), "sb-1", AddRequest{+ Path: "/mnt/data",+ Driver: DriverCommand,+ Command: []string{"my-vfs-fuse", "--target", "{mountpoint}"},+ Env: map[string]string{"REGION": "us-east-1"},+ Secrets: map[string]string{"TOKEN": "super-secret-value"},+ })+ if err != nil {+ t.Fatalf("Add: %v", err)+ }++ // Record reflects the command driver and omits secrets entirely.+ if rec.Driver != DriverCommand {+ t.Errorf("driver = %q, want %q", rec.Driver, DriverCommand)+ }+ if got := strings.Join(rec.Command, " "); got != "my-vfs-fuse --target /mnt/data" {+ t.Errorf("{mountpoint} not substituted in record: %q", got)+ }+ if _, ok := rec.Env["TOKEN"]; ok {+ t.Error("secret leaked into the mount record env")+ }+ if rec.Env["REGION"] != "us-east-1" {+ t.Errorf("non-secret env missing from record: %v", rec.Env)+ }++ // The secret must be injected via process env, never the command line.+ if launch.Env["TOKEN"] != "super-secret-value" {+ t.Errorf("secret not passed via process env: %v", launch.Env)+ }+ if argsContain(launch.Args, "super-secret-value") {+ t.Error("secret value leaked into the command line (visible via ps)")+ }+}++func TestAdd_CommandDriver_RequiresCommand(t *testing.T) {+ svc := NewService(&fakeManager{})+ if _, err := svc.Add(context.Background(), "sb-1", AddRequest{+ Path: "/mnt/x",+ Driver: DriverCommand,+ }); err == nil {+ t.Fatal("expected error when command driver has no command")+ }+}++func TestAdd_RcloneDriver_RequiresRemote(t *testing.T) {+ svc := NewService(&fakeManager{})+ if _, err := svc.Add(context.Background(), "sb-1", AddRequest{Path: "/mnt/x"}); err == nil {+ t.Fatal("expected error when rclone driver has no remote")+ }+}++func TestAdd_UnsupportedDriver(t *testing.T) {+ svc := NewService(&fakeManager{})+ if _, err := svc.Add(context.Background(), "sb-1", AddRequest{+ Path: "/mnt/x",+ Driver: "nfs",+ }); err == nil {+ t.Fatal("expected error for unsupported driver")+ }+}++func TestSubstituteMountpoint(t *testing.T) {+ got := substituteMountpoint([]string{"gcsfuse", "bkt", "{mountpoint}", "--path={path}"}, "/mnt/d")+ want := []string{"gcsfuse", "bkt", "/mnt/d", "--path=/mnt/d"}+ if strings.Join(got, " ") != strings.Join(want, " ") {+ t.Errorf("substituteMountpoint = %v, want %v", got, want)+ }+}++func TestShQuote(t *testing.T) {+ cases := map[string]string{+ "plain": "'plain'",+ "a b": "'a b'",+ "it's": `'it'\''s'`,+ "$(rm -rf)": "'$(rm -rf)'",+ }+ for in, want := range cases {+ if got := shQuote(in); got != want {+ t.Errorf("shQuote(%q) = %q, want %q", in, got, want)+ }+ }+}diff --git a/sdks/python/opencomputer/mounts.py b/sdks/python/opencomputer/mounts.pyindex 5d3b9067..ffb99cbd 100644--- a/sdks/python/opencomputer/mounts.py+++ b/sdks/python/opencomputer/mounts.py@@ -1,15 +1,20 @@-"""FUSE-backed remote filesystem mounts inside a sandbox.--Mounts use ``rclone mount`` under the hood — one driver covering ~40 backends-(S3, GCS, Azure Blob, SFTP, WebDAV, Dropbox, etc.). Credentials are passed-inline, written to a tmpfs file inside the VM (mode 0600), and never persisted-on the worker. v1 does NOT auto-restore mounts on hibernate/wake — callers-re-issue ``add(...)`` after a wake if they need the mount back.+"""FUSE-backed filesystem mounts inside a sandbox.++Two drivers:++- ``rclone`` (default, via :meth:`Mounts.add`): wrap any of rclone's ~40+ backends (S3, GCS, Azure Blob, SFTP, WebDAV, Dropbox, …) behind a simple+ remote+creds shape. Creds are written to a tmpfs file (mode 0600), never+ persisted on the worker.+- ``command`` (via :meth:`Mounts.add_command`): run your own FUSE daemon /+ mount command. Use this when you already have a FUSE-ready filesystem and+ don't want rclone as a middle layer. Secrets are injected into the daemon's+ process env (never the command line) and never persisted."""from __future__ import annotations-from dataclasses import dataclass+from dataclasses import dataclass, fieldfrom typing import Literalimport httpx@@ -21,17 +26,22 @@ MountBackend = Literal["s3", "gcs", "azureblob", "sftp", "webdav", "dropbox"]class MountInfo:"""An active mount as tracked by the worker.- ``rclone_version`` is the rclone version inside the sandbox captured at- mount-add time (e.g. ``"v1.65.2"``). rclone is baked into the rootfs, so- different sandboxes may carry different versions; this lets ops triage- backend-specific bug reports quickly.+ ``rclone_version`` (rclone driver) is the rclone version inside the sandbox+ captured at mount-add time (e.g. ``"v1.65.2"``). rclone is baked into the+ rootfs, so different sandboxes may carry different versions; this lets ops+ triage backend-specific bug reports quickly."""path: str- remote: strread_only: bool+ driver: str = "rclone"+ # rclone driver+ remote: str = ""backend: str = ""rclone_version: str = ""+ # command driver+ command: list[str] = field(default_factory=list)+ env: dict[str, str] = field(default_factory=dict)@dataclass@@ -90,6 +100,57 @@ class Mounts:data = resp.json()return _mount_from_dict(data)+ async def add_command(+ self,+ path: str,+ command: list[str],+ env: dict[str, str] | None = None,+ secrets: dict[str, str] | None = None,+ read_only: bool = True,+ ) -> MountInfo:+ """Mount a filesystem by running your own FUSE daemon / mount command.++ Use this when you already have a FUSE-ready filesystem (your own VFS,+ gcsfuse, s3fs, …) and don't want rclone as a middle layer. The platform+ manages the mountpoint, env/secret injection, and teardown; ``command``+ establishes the mount.++ Args:+ path: Absolute mountpoint inside the VM.+ command: argv for the FUSE daemon. Any ``"{mountpoint}"`` token is+ replaced with ``path``.+ env: Env vars for the command (returned by :meth:`list`).+ secrets: Secret env vars — injected into the daemon's process env+ (never the command line, so they don't leak via ``ps``), and+ never recorded or returned by :meth:`list`.+ read_only: Advisory for this driver — your command must honor it.+ Also exported to the daemon as ``OC_MOUNT_READONLY=1``. Default+ ``True``.++ Example:+ >>> await sandbox.mounts.add_command(+ ... path="/mnt/data",+ ... command=["gcsfuse", "my-bucket", "{mountpoint}"],+ ... secrets={"GOOGLE_APPLICATION_CREDENTIALS_JSON": sa_json},+ ... )+ """+ body: dict[str, object] = {+ "path": path,+ "driver": "command",+ "command": command,+ "readOnly": read_only,+ }+ if env is not None:+ body["env"] = env+ if secrets is not None:+ body["secrets"] = secrets++ resp = await self._client.post(+ f"/sandboxes/{self._sandbox_id}/mounts", json=body+ )+ resp.raise_for_status()+ return _mount_from_dict(resp.json())+async def list(self) -> list[MountInfo]:"""List the mounts this worker is tracking for the sandbox.@@ -117,8 +178,11 @@ class Mounts:def _mount_from_dict(data: dict) -> MountInfo:return MountInfo(path=data["path"],- remote=data["remote"],- backend=data.get("backend", ""),+ driver=data.get("driver", "rclone"),read_only=data.get("readOnly", True),+ remote=data.get("remote", ""),+ backend=data.get("backend", ""),rclone_version=data.get("rcloneVersion", ""),+ command=data.get("command", []) or [],+ env=data.get("env", {}) or {},)diff --git a/sdks/typescript/src/mounts.ts b/sdks/typescript/src/mounts.tsindex c8afa5e8..bdf66fa9 100644--- a/sdks/typescript/src/mounts.ts+++ b/sdks/typescript/src/mounts.ts@@ -11,9 +11,15 @@ export type MountBackend =| "webdav"| "dropbox";-export interface AddMountOpts {+/**+ * rclone-driver mount — the easy path. Wraps any of rclone's ~40 backends+ * behind a simple remote+creds shape.+ */+export interface RcloneMountOpts {/** Absolute path inside the sandbox where the remote will be mounted. */path: string;+ /** Driver. Defaults to `"rclone"`. */+ driver?: "rclone";/** rclone remote spec — `<name>:<path>` (e.g. `"s3:my-bucket/prefix"`). */remote: string;/**@@ -26,8 +32,7 @@ export interface AddMountOpts {* e.g. for S3: `access_key_id`, `secret_access_key`, `region`).** Creds are written to a tmpfs file inside the VM (mode 0600) and never- * persisted on the worker. v1 does not auto-restore mounts on hibernate —- * re-call `mounts.add` after wake if you need the mount back.+ * persisted on the worker.*/creds?: Record<string, string>;/**@@ -41,17 +46,58 @@ export interface AddMountOpts {mountOptions?: string[];}+/**+ * Command-driver mount — run your own FUSE daemon / mount command. Use this+ * when you already have a FUSE-ready filesystem (your own VFS, gcsfuse, s3fs,+ * …) and don't want rclone as a middle layer. The platform manages the+ * mountpoint, env/secret injection, and teardown; your command establishes the+ * mount.+ */+export interface CommandMountOpts {+ /** Absolute path inside the sandbox where the filesystem will be mounted. */+ path: string;+ driver: "command";+ /**+ * argv for the FUSE daemon / mount command. Any `"{mountpoint}"` token is+ * replaced with `path` (so you can template where the mount lands).+ * @example ["gcsfuse", "my-bucket", "{mountpoint}"]+ */+ command: string[];+ /** Env vars for the command. Returned by `list()`. */+ env?: Record<string, string>;+ /**+ * Secret env vars — injected into the daemon's process environment (never+ * the command line, so they don't leak via `ps`), and never recorded or+ * returned by `list()`.+ */+ secrets?: Record<string, string>;+ /**+ * Advisory for this driver — your command must honor it. Also exported to+ * the daemon as `OC_MOUNT_READONLY=1`. Default `true`.+ */+ readOnly?: boolean;+}++export type AddMountOpts = RcloneMountOpts | CommandMountOpts;+export interface MountInfo {path: string;- remote: string;- backend?: string;+ driver: "rclone" | "command";readOnly: boolean;+ /** rclone driver: the remote spec. */+ remote?: string;+ /** rclone driver: the backend type. */+ backend?: string;/**- * rclone version inside the sandbox at the moment this mount was added- * (e.g. `"v1.65.2"`). Captured for ops triage — rclone is baked into the- * rootfs, so different sandboxes may carry different versions.+ * rclone driver: rclone version inside the sandbox at add time (e.g.+ * `"v1.65.2"`). Captured for ops triage — rclone is baked into the rootfs,+ * so different sandboxes may carry different versions.*/rcloneVersion?: string;+ /** command driver: the resolved argv. */+ command?: string[];+ /** command driver: non-secret env vars (secrets are omitted). */+ env?: Record<string, string>;}export class Mounts {@@ -68,9 +114,12 @@ export class Mounts {}/**- * Mount a remote filesystem via rclone+FUSE inside the sandbox.+ * Mount a filesystem inside the sandbox. Two drivers:+ *+ * - `rclone` (default): wrap any rclone backend behind remote+creds.+ * - `command`: run your own FUSE daemon / mount command.*- * @example+ * @example rclone driver* ```ts* await sandbox.mounts.add({* path: "/mnt/data",@@ -79,6 +128,16 @@ export class Mounts {* creds: { access_key_id: "...", secret_access_key: "...", region: "us-east-1" },* });* ```+ *+ * @example command driver (bring your own FUSE)+ * ```ts+ * await sandbox.mounts.add({+ * path: "/mnt/data",+ * driver: "command",+ * command: ["my-vfs-fuse", "--bucket", "gs://my-bucket", "{mountpoint}"],+ * secrets: { GOOGLE_APPLICATION_CREDENTIALS_JSON: saJson },+ * });+ * ```*/async add(opts: AddMountOpts): Promise<MountInfo> {const resp = await fetch(