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

# mesa.fs()

> Define a layout, mount it as a Mesa virtual filesystem, or mint its token.

`mesa.fs({ layout, authors, ttl? })` builds a `FilesystemDefinition`: a raw `Layout`, its authors, and its token lifetime, bundled with `layout()`, `mount()`, and `token()`. Calling `.mount()` returns a `MesaFileSystem` backed by Mesa's native filesystem.

```ts theme={null}
import { Buffer } from 'node:buffer';
import { Mesa, repo } from '@mesadev/sdk';

const mesa = new Mesa({ privateKey: process.env.MESA_PRIVATE_KEY });

const fs = await mesa
  .fs({
    layout: {
      '/workspace': repo('app', { mode: 'rw', at: { bookmark: 'main' } }),
    },
    authors: [{ name: 'Mesa Bot', email: 'mesa-bot@example.com' }],
  })
  .mount();

const data = await fs.readFileBuffer('/workspace/README.md');
console.log(Buffer.from(data).toString('utf8'));
```

Map `repos.list()` results into layout declarations when the repository set is dynamic:

```ts theme={null}
const { repos } = await mesa.repos.list({
  tags: {
    $and: [{ environment: 'prod' }, { workload: { $in: ['sync', 'index'] } }],
  },
});

const fs = await mesa
  .fs({
    layout: {
      '/skills': repos.map((r) => repo(r.name, { mode: 'ro' })),
    },
    authors: [{ name: 'Mesa Bot', email: 'mesa-bot@example.com' }],
  })
  .mount();
```

The client signs a short-lived, layout-scoped token locally from its private key. The mount keeps that token for its whole lifetime; nothing refreshes it in the background.

See [Layouts](https://docs.mesa.dev/content/mesafs/layouts.md) for nesting, structural rules, and running a layout mount in a sandbox.

## `mesa.fs(options)`

Synchronous. Builds the definition eagerly so invalid layouts throw at this call.

**layout** `Layout` *required*

Map of absolute mount paths (`/`-prefixed) to one `repo(...)` declaration or an array of them. The mount contains exactly this visible path tree.

**ttl** `number | undefined`

Lifetime, in seconds, of every token the definition mints through `token()` and under the hood in `mount()`. Defaults to `900` and allows up to `14400`.

**authors** `[\{ name: string; email?: string \}, ...]` *required*

Commit authors, in order, with at least one entry. Required for every layout definition.

### Definition members

**layout()** `Layout`

An independent plain-object snapshot of the validated layout. Pass it to `JSON.stringify(...)` to produce the document `mesa mount --layout` reads.

**mount(options?)** `Promise\<MesaFileSystem\>`

Mount the layout as the complete visible path tree. Accepts only runtime options (`cache`, `telemetry`). The mount's token lifetime is the definition's `ttl`.

**token()** `Promise\<AccessToken\>`

Mint the layout-scoped, least-privilege access token. Each repository receives read only access for `mode: 'ro'` or read and write access for `mode: 'rw'`.

`mesa.fs(...)` validates the layout structurally before returning the definition. Repository names resolve only at mount time — a layout naming a nonexistent repository still produces a definition and token, then fails when the mount resolves it.

```ts theme={null}
import { repo } from '@mesadev/sdk';

const definition = mesa.fs({
  layout: { '/workspace': repo('app', { mode: 'rw' }) },
  authors: [{ name: 'Mesa Bot', email: 'mesa-bot@example.com' }],
  ttl: 3600,
});

sandbox.writeFile('layout.json', JSON.stringify(definition.layout(), null, 2));
const { token } = await definition.token();
```

## `repo(selector, options)`

Declare one repository in a layout. Do not construct `Repo` objects by hand.

```ts theme={null}
repo('app', { mode: 'rw', at: { bookmark: 'main' } });
repo({ name: 'app' }, { mode: 'ro', at: { changeId: 'zyxwvutsrqponmlkzyxwvutsrqponmlk' } });
repo('app', {
  mode: 'rw',
  branchedFrom: {
    bookmark: 'main',
    as: { bookmark: 'run-27', describe: 'initiate plan...' },
  },
});
```

**selector** `string | \{ name: string \}` *required*

Repository name within the client's organization.

**options.mode** `'rw' | 'ro'` *required*

Access mode. Always required — there is no default. `'ro'` rejects writes with `EROFS`.

**options.at** `RevisionIdentifier | undefined`

Pin an existing revision: `{ bookmark }` or `{ changeId }`. Mutually exclusive with `branchedFrom`. When neither `at` nor `branchedFrom` is set, the repository's default bookmark is used.

**options.branchedFrom** `BranchedRevision | undefined`

Fork a new empty descendant from a parent tip at cold open and check it out. Requires `mode: 'rw'`. Shape: parent `{ bookmark }` or `{ changeId }`, optional `as: { bookmark?, describe? }`. Omit `as` (or `as.bookmark`) for an anonymous tip. Parent bookmark is not moved. Mutually exclusive with `at`.

**options.alias** `string | undefined`

Directory-name override. Only valid when the declaration is an element of an array value in the layout.

**options.subPaths** `Record\<string, Repo | Repo[]\> | undefined`

Nested repository mounts declared beneath this repository's mount path. Keys are relative paths.

## `FsMountRuntimeOptions`

Non-token options accepted by `definition.mount(options?)`.

**cache.diskCache** `\{ path: string; maxSizeBytes?: number \} | undefined`

Optional on-disk cache. When omitted, the mount uses in-memory caching only.

**telemetry.logLevel** `'error' | 'warn' | 'info' | 'debug' | undefined`

Minimum native log level. Defaults to `warn`.

**telemetry.onLog** `(record: LogRecord) =\> void | undefined`

Per-instance structured log callback from the native filesystem.

### Disk cache

```ts theme={null}
const fs = await mesa
  .fs({
    layout: { '/workspace': repo('app', { mode: 'rw' }) },
    authors: [{ name: 'Mesa Bot' }],
  })
  .mount({
    cache: { diskCache: { path: '/tmp/mesa-cache', maxSizeBytes: 500_000_000 } },
  });
```

**cache.diskCache.path** `string` *required*

Directory for the on-disk cache.

**cache.diskCache.maxSizeBytes** `number | undefined`

Optional cache size cap. When omitted, the native extension auto-sizes the budget against system resources.

## Paths

Mounted paths are whatever the layout declares:

```text theme={null}
/workspace/README.md
/workspace/src/main.ts
/skills/code-review/SKILL.md
```

## Response

`definition.mount()` returns a `Promise<MesaFileSystem>`.

## MesaFileSystem

The returned `fs` object implements the `just-bash` filesystem interface and exposes async file I/O, metadata, traversal, mutation, Bash, and mounted-repo version-control helpers.

```ts theme={null}
await fs.mkdir('/workspace/src', { recursive: true });
await fs.writeFile('/workspace/src/main.ts', 'console.log("hello")\n');
const data = await fs.readFile('/workspace/src/main.ts', 'utf8');
```

### Byte and text I/O

**readFile(path, options?)** `Promise\<string\>`

Read a file as text using a Node-compatible encoding. The `binary` encoding follows the `just-bash` latin1 byte-string convention.

**readFileBuffer(path)** `Promise\<Uint8Array\>`

Read raw file bytes.

**writeFile(path, content, options?)** `Promise\<void\>`

Replace file contents, creating the file if missing. Parent directories must already exist.

**appendFile(path, content, options?)** `Promise\<void\>`

Append text or bytes to a file, creating it if missing.

**exists(path)** `Promise\<boolean\>`

Return whether a path exists. Follows symlinks.

### Metadata and traversal

**stat(path)** `Promise\<FsStat\>`

Return metadata for a path, following symlinks. `mtime` is a JavaScript `Date`.

**lstat(path)** `Promise\<FsStat\>`

Return metadata for a path without following symlinks. `mtime` is a JavaScript `Date`.

**readdir(path)** `Promise\<string[]\>`

Return entry names in a directory. Sort client-side if you need deterministic ordering.

**readdirWithFileTypes(path)** `Promise\<Array\<\{ name: string; isFile: boolean; isDirectory: boolean; isSymbolicLink: boolean \}\>\>`

Return entry names with file type flags.

**realpath(path)** `Promise\<string\>`

Resolve symlinks and `..` segments to a canonical path.

**readlink(path)** `Promise\<string\>`

Return the target of a symlink.

**resolvePath(base, path)** `string`

Join and normalize a path against a base path without touching the filesystem.

**getAllPaths()** `string[]`

Return a synchronous snapshot of paths known to the filesystem.

### Mutations

**mkdir(path, options?)** `Promise\<void\>`

Create a directory. With `{ recursive: true }`, create missing parents and do nothing when the path already exists as a directory.

**rm(path, options?)** `Promise\<void\>`

Remove a file or directory. Use `{ recursive: true }` for non-empty directories and `{ force: true }` to ignore missing paths.

**cp(src, dest, options?)** `Promise\<void\>`

Copy a file or directory. Use `{ recursive: true }` for directories.

**mv(src, dest)** `Promise\<void\>`

Move or rename a file or directory.

**chmod(path, mode)** `Promise\<void\>`

Set permission bits, such as `0o755`.

**symlink(target, linkPath)** `Promise\<void\>`

Create a symlink. Relative targets are stored verbatim and resolve against the parent of `linkPath` at read time.

**utimes(path, atime, mtime)** `Promise\<void\>`

Set access and modification times with JavaScript `Date` values.

**link(existingPath, newPath)** `Promise\<void\>`

Create a hard link if supported by the native filesystem implementation.

### Subscriptions

MesaFS reads and writes are realtime by default. Use subscriptions only when your process needs an event stream that identifies which paths changed, such as to refetch data and rerender a frontend.

**subscribe(handler)** `MesaFileSystemSubscription`

Subscribe to filesystem invalidation events. The handler is called after the changed state is visible through this filesystem instance.

```ts theme={null}
const subscription = fs.subscribe(async (event) => {
  if (!event.recursive) {
    const content = await fs.readFile(event.path, 'utf8');
    console.log(event.path, content);
  }
});

subscription.unsubscribe();
```

**handler** `(event: WatchEvent) =\> void | Promise\<void\>`

Callback invoked for each filesystem invalidation.

**WatchEvent.path** `string`

Absolute MesaFS path that changed, such as `/workspace/src/index.ts`.

**WatchEvent.recursive** `boolean`

Whether descendants of `path` may have changed. Refresh any cached directory or subtree state below `path` when this is `true`.

**MesaFileSystemSubscription.unsubscribe()** `void`

Stop receiving events and close the underlying watcher.

### FsStat

`stat(...)` and `lstat(...)` return `FsStat`.

**isFile** `boolean`

Whether the path is a regular file.

**isDirectory** `boolean`

Whether the path is a directory.

**isSymbolicLink** `boolean`

Whether the path is a symlink. This is `false` from `stat(...)` when the target exists because `stat` follows symlinks.

**mode** `number`

POSIX mode bits.

**size** `number`

Size in bytes.

**mtime** `Date`

Modification time.

### Related filesystem methods

| Method | Reference |
| - | - |
| `fs.bash(...)` | [fs.bash()](https://docs.mesa.dev/content/reference/ts/fs-bash.md) |
| `fs.change` | [fs.change](https://docs.mesa.dev/content/reference/ts/fs-changes.md) |
| `fs.bookmark` | [fs.bookmark](https://docs.mesa.dev/content/reference/ts/fs-bookmarks.md) |
| `fs.subscribe(...)` | [Advanced Realtime](https://docs.mesa.dev/content/mesafs/advanced/realtime.md) |

## Errors

Throws `InvalidOptionsError` for a missing or empty layout, a `ttl` outside the private-key range (`1..14400` seconds), missing or rejected `authors`, or a layout that breaks the [structural rules](https://docs.mesa.dev/content/mesafs/layouts.md#declaration-fields). A missing layout and author problems fail at the `mesa.fs(...)` call; the empty-layout and structural checks run at `mount()` or `token()`, before any token is minted. Token signing or VCS connection failures can throw API errors or connection errors.


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