> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mirage.strukto.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Google Drive

> Virtualize Google Drive folders and files from Node or the browser.

`GoogleDriveVFS` mounts a Google Drive account: every folder becomes a
directory, every file a file, and Docs, Sheets and Slides read as JSON. My
Drive and every Shared Drive the account can see are included. Set up the credentials as in [Google Workspace setup](https://docs.mirage.strukto.ai/home/setup/google.md).

## Install

```bash theme={null}
npm install @struktoai/mirage-node
```

## Configure

```ts theme={null}
import { GoogleDriveVFS, MountMode, Workspace } from '@struktoai/mirage-node'

const drive = new GoogleDriveVFS({
  clientId: process.env.GOOGLE_CLIENT_ID!,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
  refreshToken: process.env.GOOGLE_REFRESH_TOKEN!,
})
const ws = new Workspace({ '/gdrive': drive }, { mode: MountMode.WRITE })

const result = await ws.shell("ls /gdrive && find /gdrive -maxdepth 2 -name '*.gsheet.json'")
console.log(result.stdoutText)
await ws.close()
```

`folderId` mounts one folder instead of the whole Drive. A mount takes
`MountMode.READ`, `WRITE` or `EXEC`; `EXEC` lets `python3` and `js` run
scripts from the mount.

### Fields

**timeout** `number` (default: DEFAULT\_TIMEOUT)

Seconds a request may wait to connect, or between two reads of its answer, before it fails; a download that keeps flowing is never cut off.

**accessToken** `string | function`

OAuth access token, or a function (sync or async) that returns one. Takes precedence over `clientId` and `refreshToken`.

**clientId** `string`

Google OAuth client ID. Required with `refreshToken` when `accessToken` is unset; mirage then mints and renews access tokens itself.

**clientSecret** `string`

Google OAuth client secret, sent with the refresh-token grant. Omit it for a PKCE client.

**refreshToken** `string`

User's OAuth refresh token. Required with `clientId` when `accessToken` is unset.

**refreshFn** `function`

Function that exchanges the refresh token for `{ accessToken, expiresIn }` instead of Google's token endpoint, so the client secret can stay on a backend. Still needs `clientId` and `refreshToken`.

**apiBase** `string`

One base URL that replaces every Google API host and the OAuth token endpoint, such as a test server. Unset uses Google's hosts.

**folderId** `string`

Drive folder ID the `gdrive` mount uses as its root instead of My Drive; it may be a folder in a Shared Drive. Other Google mounts ignore it.

Fields marked secret are redacted in snapshots.

## Authentication

Credentials come from the first of:

1. `accessToken`, a token or a function, sync or async, that returns one.
2. `clientId` and `refreshToken`, with `clientSecret` unless the client uses
   PKCE. Mirage trades the refresh token for access tokens on its own, or
   hands it to `refreshFn` when set, so the secret can stay on a backend.

The mount needs the Drive API and the `https://www.googleapis.com/auth/drive`
scope, or `drive.readonly` for a read-only mount. Drive grants access per
item, so a write mount can still hold files the account may not change. A
change Drive refuses fails with `Permission denied` on that operand, and the
rest of the mount keeps working.

## Layout

```text theme={null}
/gdrive/
  Projects/
    roadmap.gsheet.json
    spec.pdf
  Notes/
    meeting.gdoc.json
  Engineering/
    ...
```

* The root holds My Drive's folders and files plus one folder per Shared
  Drive. A Shared Drive whose name clashes gets a `[Shared Drive]` suffix and,
  if needed, a number.
* Regular files (PDFs, images, CSVs) keep their names and read as their
  bytes.
* Docs, Sheets and Slides cannot be downloaded as bytes, so they read as the
  JSON of their own API: `.gdoc.json`, `.gsheet.json` and `.gslide.json`.

## Behavior

* **Folder scope:** `folderId: '1AbCdEf...'` makes that folder the mount
  root. It may sit in My Drive, be shared with the account, sit in a Shared
  Drive, or be a Shared Drive's id. A scoped mount shows no other Shared
  Drive.
* **Writes:** on a `write` mount, `tee`, `cp`, `mv`, `rm`, `mkdir`, `rmdir`,
  `touch`, `truncate` and `sed -i` work on regular files and folders.
  `mkdir` over an existing name fails with `File exists`, `mv` onto a
  non-empty directory with `Directory not empty`, and `cp -r` merges. `rm`
  deletes for good, not to the trash.
* **Docs, Sheets and Slides:** read only as bytes; a write to one fails with
  `Permission denied`. Change them with the [`gws`](https://docs.mirage.strukto.ai/typescript/cli/gws) CLI,
  which also acts on any Drive item by id.
* **Shared Drives:** writable on the same terms as My Drive. The account's
  role on that drive decides what it may change, and some organizations
  restrict deleting or moving content out of a drive. `MountMode.READ` makes
  a mount that cannot write at all.

## Browser

The same `GoogleDriveVFS` comes from `@struktoai/mirage-browser`. In a page, an
`accessToken` function fetches a fresh token from a backend, so the client
secret never reaches the browser.

```bash theme={null}
npm install @struktoai/mirage-browser
```

```ts theme={null}
import { GoogleDriveVFS, MountMode, Workspace } from '@struktoai/mirage-browser'

const drive = new GoogleDriveVFS({
  accessToken: async () => (await fetch('/api/google-token')).text(),
})
const ws = new Workspace({ '/gdrive': drive }, { mode: MountMode.READ })
```

* `/api/google-token` stands for a backend endpoint that returns an access
  token.
* A PKCE OAuth client needs no secret: `clientId` and `refreshToken` alone
  mount it. `examples/browser/vfs/gdrive/gdrive_pkce.ts` shows the sign-in
  flow.
* `refreshFn` sends each refresh to a backend instead of Google's token
  endpoint.

## Integration

Drive answers these commands through its own API, so fewer files are read.
See [Integration](https://docs.mirage.strukto.ai/home/integration/overview.md).

* `grep -r` and `rg` with `-w` or `-x`: Drive full-text search names the
  files to read. Every file is read when the search fails or finds nothing.
  Drive searches the text it extracted, not the bytes `grep` reads, and
  indexes a write some time after it lands, so it can leave out a file that
  holds the word: a Docs, Sheets or Slides file (its JSON keys and ids), an
  office file, PDF or archive, the end of a large file, or a word Drive
  splits differently (`foo.bar`). `walkLimit: -1` in the mount's `"@all"`
  [command limit](https://docs.mirage.strukto.ai/home/limits.md#command-output) turns the search off and reads
  every file.
* `md5sum`, `sha1sum` and `sha256sum`: the digest Drive keeps. A Docs, Sheets
  or Slides file is read.
* `find`, `du`, `ls -R` and `tree`: one recursive listing.

## VFS.md

The [VFS.md](https://docs.mirage.strukto.ai/home/setup/vfs-md.md) an agent reads with Google Drive mounted at
`/<path>`. `<mode>` is the mount's mode: `read`, `write` or `exec`. The
commands shown are those of a `write` mount.

> [tab] Rendered
>
> **Virtual Filesystem**
>
> | Path | Description |
> | - | - |
> | `/<path>` | `gdrive`, `<mode>` |
>
> **VFS Layout**
>
> **`/<path>`**
>
> ```text theme={null}
> /<path>
>   <folder>/              # the Drive folder hierarchy, mirrored
>     <name>.gdoc.json     # Google Docs: the gdocs gdoc.json shape
>     <name>.gsheet.json   # Google Sheets: the gsheets gsheet.json shape
>     <name>.gslide.json   # Google Slides: the gslides gslide.json shape
>     <file>               # PDFs, images and the rest: raw bytes
>   <shared-drive>/        # each shared drive you can see
> ```
>
> * The full Drive view, folders mirrored, with files shared into My Drive;
>   there is no `owned/` and `shared/` split.
> * Changes by id (create, export, permissions) go through the `gws drive`
>   CLI.
>
> **Supported Unix Commands for VFS**
>
> Unix commands work on each path as on a local filesystem, as far as the path supports them:
>
> | Path | Supported |
> | - | - |
> | `/<path>` | Almost all Unix commands. `grep -r` and `rg` with `-w` ask `gdrive` which files may match. |
>
> **Limitations of Unix Commands for VFS**
>
> Where a path differs from a local filesystem:
>
> | Path | Limitations |
> | - | - |
> | `/<path>` | Without `-w`, `grep -r` and `rg` read every file. `grep -r`, `find` and `du` stop after 1000 files; a glob matching more, `tar -c`, `cp -r` and `rm -r` are refused. |
>
> Run `man <cmd>` or `<cmd> --help` for one command's usage.

> [tab] Raw
>
> ````markdown theme={null}
> ---
> name: workspace-filesystem
> description: The virtual filesystem layout of this workspace.
> ---
>
> # Virtual Filesystem
>
> | Path | Description |
> | --- | --- |
> | `/<path>` | `gdrive`, `<mode>` |
>
> ## VFS Layout
>
> ### `/<path>`
>
> ```text
> /<path>
>   <folder>/              # the Drive folder hierarchy, mirrored
>     <name>.gdoc.json     # Google Docs: the gdocs gdoc.json shape
>     <name>.gsheet.json   # Google Sheets: the gsheets gsheet.json shape
>     <name>.gslide.json   # Google Slides: the gslides gslide.json shape
>     <file>               # PDFs, images and the rest: raw bytes
>   <shared-drive>/        # each shared drive you can see
> ```
>
> - The full Drive view, folders mirrored, with files shared into My Drive;
>   there is no `owned/` and `shared/` split.
> - Changes by id (create, export, permissions) go through the `gws drive`
>   CLI.
>
> ## Supported Unix Commands for VFS
>
> Unix commands work on each path as on a local filesystem, as far as the path supports them:
>
> | Path | Supported |
> | --- | --- |
> | `/<path>` | Almost all Unix commands. `grep -r` and `rg` with `-w` ask `gdrive` which files may match. |
>
> ## Limitations of Unix Commands for VFS
>
> Where a path differs from a local filesystem:
>
> | Path | Limitations |
> | --- | --- |
> | `/<path>` | Without `-w`, `grep -r` and `rg` read every file. `grep -r`, `find` and `du` stop after 1000 files; a glob matching more, `tar -c`, `cp -r` and `rm -r` are refused. |
>
> Run `man <cmd>` or `<cmd> --help` for one command's usage.
> ````


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.