> ## 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.

# In-App

> The TypeScript classes your app calls to run a workspace, each with an example.

Call these when your agent runs in the same process as the workspace. Every other way in ends in the same calls.

## Workspace

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

```ts theme={null}
class Workspace {
  constructor(
    mounts: Record<string, MountSpec>,
    options?: WorkspaceOptions,
  )
}
```

One virtual terminal over the backends mounted at each prefix.

**mounts** `Record\<string, MountSpec\>` *required*

The backend at each prefix, such as `{ '/': new RAMVFS(), '/s3': new S3VFS(config) }`.

**MountSpec**

A `MountSpec` takes one of four forms:

| Form | Mounts |
| - | - |
| `vfs` | With the workspace's `mode`. |
| `[vfs, mode]` | With its own mode. |
| `[vfs, mode, limits]` | With its own mode and [command limits](https://docs.mirage.strukto.ai/home/core/output-limits.md), keyed by command name. |
| `new Mount(vfs, options)` | With any of `mode`, `backend`, `mountpoint`, `commandLimits`, `index`, `read` and `write`, as the [mount settings](https://docs.mirage.strukto.ai/home/configuration/workspace.md#mount-settings) describe. |

**options.mode** `MountMode` (default: MountMode.READ)

The mode a mount gets when it sets none: `READ`, `WRITE` or `EXEC`.

**options.profiles** `Record\<string, SessionProfile\>`

Named [profiles](https://docs.mirage.strukto.ai/home/policy/overview.md) a session can be created under.

**options.profile** `string`

The profile a session gets when it names none.

**options.policies** `Policy[]`

[Policies](https://docs.mirage.strukto.ai/home/policy/overview.md) every line passes through.

**options.onAsk** `AskHandler`

Resolves an approval request (ask) while the line waits. Without a handler, asks are recorded in [`ws.decisions`](#ws-decisions).

**options.workspaceId** `string`

The workspace's id, generated when unset.

**options.sessionId** `string`

The default session's id.

**options.store** `WorkspaceStateStore`

Where the workspace keeps its [state](https://docs.mirage.strukto.ai/home/infrastructure/overview.md#workspace-state): symlinks and file attributes, command logs, sessions and background jobs. In memory when unset. A store passed in is borrowed: close it after `ws.close()`, or pass `ownsStore: true`.

See [Workspace configuration](https://docs.mirage.strukto.ai/home/configuration/workspace.md) for `snake_case` YAML settings.
Direct SDK construction defaults `mode` to `READ`; YAML defaults it to `write`.

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

const ws = new Workspace(
  { '/': new RAMVFS() },
  { mode: MountMode.WRITE },
)
```

Set the per-queue capacity when creating the workspace:

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

const ws = new Workspace(
  { '/': new RAMVFS() },
  { io: new IOConfig({ bufferBytes: 262144 }) },
)
```

Every process that builds the workspace on one Redis store, under the same ids, shares its sessions and background jobs:

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

const store = new RedisWorkspaceStateStore({ url: 'redis://localhost:6379/0' })
const ws = new Workspace(
  { '/': new RAMVFS() },
  { mode: MountMode.WRITE, workspaceId: 'agent-ws', sessionId: 's1', store },
)
```

### ws.session

```ts theme={null}
ws.session(sessionId, { profile?, mounts?, permissions? }): Promise<Session>
```

The [`Session`](#session) every call below runs as. It creates the session when the id is new and adopts it when it exists. `profile`, `mounts` and `permissions` apply only on create, and throw for an existing session. `permissions` adds rules for this session only, on top of its profile: ask and deny rules, hides and weaker mount modes. It cannot add an allow list or a policy. `ws.createSession` is the synchronous version that initializes the session and returns its `SessionState` without returning an executable `Session` client.

```ts theme={null}
const session = await ws.session('agent')
```

### ws.setProfile, ws.setSessionProfile

```ts theme={null}
ws.setProfile(name, profile): void
ws.setSessionProfile(sessionId, profile): Promise<SessionState>
```

Change the rules after the workspace is built. `setProfile` defines a profile name or replaces what it means; a document no session could run under throws `PolicyError` and leaves the table as it was. A live session keeps its rules until `setSessionProfile` moves it. Given a name, the session runs that profile's current definition and keeps the name, which `whoami` and the profile's policy programs read; its working directory, variables and history stay. `null` picks the workspace default, and a document passed directly runs without a name.

```ts theme={null}
ws.setProfile('user', { commands: { allow: ['ls', 'cat'] }, paths: { hide: ['/data/secret'] } })
await ws.setSessionProfile('agent', 'user')
```

### ws.listSessions, ws.closeSession

```ts theme={null}
ws.listSessions(): SessionState[]
ws.closeSession(sessionId): Promise<void>
```

List the sessions, or close one: its lines are cancelled and its jobs end. The default session cannot be closed.

**SessionState**

**sessionId** `string`

**cwd** `string`

The working directory.

**env** `Readonly\<Record\<string, string\>\>`

The exported variables.

**profile** `string | null`

The profile it was created under.

**mountModes** `ReadonlyMap\<string, MountMode\> | null`

Its mount modes, when narrower than the workspace's.

**lastExitCode** `number`

`$?`.

**createdAt** `number`

Unix time, in seconds.

```ts theme={null}
console.log(ws.listSessions().map((s) => s.sessionId))
await ws.closeSession('agent')
```

### ws.cancel, ws.kill

```ts theme={null}
ws.cancel(sessionId?): Promise<number>
ws.kill(sessionId?): Promise<number>
```

Stop a session's work, or every session's with no id, and leave the sessions open. `cancel` cancels the running and queued lines, whichever way they came in, and resolves once they have ended; each rejects with an `AbortError`. `kill` kills the background jobs (`cmd &`) and the programs machines started. Each answers how many it stopped.

```ts theme={null}
await ws.cancel('agent')
await ws.kill()
```

### ws.snapshot, Workspace.load

```ts theme={null}
ws.snapshot(): Promise<Uint8Array>
ws.snapshot(target, { s3? }): Promise<number>
Workspace.load(source, { s3?, ... }): Promise<Workspace>
```

Save the workspace to a tar and rebuild it from one. `target` and `source` are a path, or an object key with `s3`; `source` can also be the bytes. With no target, `snapshot` returns the tar's bytes; with one, its size.

* While it captures, new lines and file writes wait. Running ones get 30 seconds to end, else it rejects with an `EBUSY` error. A path target streams disk mount files rather than holding them whole.
* The tar keeps the profiles, the command limits and each store's `capacity`. Each session loads back under the restrictions it ran with.
* An override brings its own `capacity`, or none.
* The scratch root, the RAM root added when nothing is mounted at `/`, comes back as the scratch root, an override for it included.

```ts theme={null}
const tar = await ws.snapshot()
const restored = await Workspace.load(tar)
```

### ws.copy

```ts theme={null}
ws.copy(options?): Promise<Workspace>
```

A deep copy, without a tar in between. RAM and disk mounts are copied, so a write in the copy never reaches the original. Sessions, history, profiles, command limits (the workspace's and each mount's), secrets declarations and CLIs come along. Remote backends such as S3 or Redis are shared, so a write through the copy reaches the same bucket. Policy objects and the route policy are not copied.

```ts theme={null}
const fork = await ws.copy()
```

### ws.decisions

```ts theme={null}
ws.decisions.pending(sessionId?): Decision[]
ws.decisions.answer(
  decisionId, outcome, scope?, note?
): Promise<void>
```

The [asks](https://docs.mirage.strukto.ai/home/policy/policies.md#asks) waiting for a host. Each one belongs to the session that ran the line: `pending()` lists every session's, `pending('agent')` one session's, and an answer never reaches another session. `outcome` is `Outcome.ALLOW` or `Outcome.DENY`. `Scope.ONCE`, the default, resolves the pending ask for this line, allowing its retry to run or be refused; `Scope.SESSION` allows every line the rule covers for the rest of that session.

**Decision**

**id** `string`

The id to answer it by.

**sessionId** `string`

The session that ran the line.

**command** `string`

The command name.

**argv** `readonly string[]`

The words after the name, expanded.

**cwd** `string`

**paths** `readonly string[]`

The paths the line names.

**reason** `string`

The rule's reason.

**outcome** `Outcome | null`

The answer; `null` while it waits.

**scope** `Scope`

**note** `string`

What the host said when answering.

```ts theme={null}
import { Outcome } from '@struktoai/mirage-node'

for (const ask of ws.decisions.pending()) {
  await ws.decisions.answer(ask.id, Outcome.ALLOW)
}
```

### ws.close

```ts theme={null}
ws.close(): Promise<void>
```

Stops its jobs and closes its mounts. Sessions and history stay in the workspace's store.

## Session

```ts theme={null}
import { Session } from '@struktoai/mirage-node'
```

```ts theme={null}
class Session {
  constructor(workspace: Workspace, sessionId: string)
}
```

One session's handle, from [`ws.session`](#ws-session). Every call on it runs under the session's [profile](https://docs.mirage.strukto.ai/home/policy/overview.md), working directory and environment. `ws.shell`, `ws.glob`, `ws.vfs` and `ws.tools` are the same calls as the workspace's default session.

**sessionId** `string`

**state** `SessionState`

The session's record, as returned by [`ws.listSessions`](#ws-listsessions-ws-closesession).

**vfs** `Files`

The file API, below.

**tools** `MirageToolOperations`

The agent tools, below.

**decisions** `Decisions`

The workspace's [asks](https://docs.mirage.strukto.ai/home/policy/policies.md#asks) ledger, which records pending approval requests for this session.

### session.shell

```ts theme={null}
session.shell(
  command, { stdin?, cwd?, env?, signal?, record?, machine?, sink?, stream? },
): Promise<ExecuteResult | ShellExecution>
```

Runs a shell line as the session. With `stream: false` (the default), it collects the execution’s output and returns an `ExecuteResult`. A non-zero exit is a result, not an exception. `ws.shell` has the same streaming option and accepts `sessionId` to select the session.

**stdin** `Uint8Array | AsyncIterable\<Uint8Array\>`

The line's stdin. An async iterable streams it.

**cwd** `string`

A working directory for this line only. The line runs in a subshell of its own, beside the session's other lines rather than after them: a `cd` in it does not leak, and its jobs are its own.

**env** `Record\<string, string\>`

Variables for this line only. Like `cwd`, they run the line in a subshell of its own.

**signal** `AbortSignal`

Aborting it stops the line, which throws an `AbortError`.

**record** `boolean` (default: true)

`false` keeps the line out of history.

**machine** `string`

Run the commands this workspace [machine](https://docs.mirage.strukto.ai/home/setup/machine/overview.md) captures on it, by name, instead of where routing puts them. Throws for a name the workspace does not have.

**sink** `JobConsole`

Write the line's output to this console as each statement finishes. Cannot be combined with `stream: true`. The result then carries the exit code with empty `stdout` and `stderr`. The caller calls `finish()` on the console.

**ExecuteResult**

**exitCode** `number`

**stdoutText** `string`

The output as text. `stdout` is the bytes.

**stderrText** `string`

The error output as text. `stderr` is the bytes.

**decision** `PolicyDecision | null`

Why the line did not run, or `null`.

**PolicyDecision**

**kind** `string`

`deny` for a refusal, `pending` for an ask nobody answered, `failed` for a policy that raised.

**reason** `string`

The rule's or the policy's words.

**policy** `string`

The policy class that refused; empty for an ask.

**askId** `string | null`

The ask's id, for `pending`.

```ts theme={null}
const stdin = new TextEncoder().encode('a\nb\n')
const result = await session.shell('wc -l', { stdin })
console.log(result.exitCode, result.stdoutText)
```

### Streaming execution

`await session.shell(line, { stream: true })` returns a running `ShellExecution`. `events` yields ordered `{stream, data}` events with `stream: "stdout"` or `stream: "stderr"` and raw `Uint8Array` bytes. The event iterator has one reader. A slow consumer applies backpressure: the queue defaults to 64 KiB, configurable through workspace I/O settings, with chunks no larger than 16 KiB. It runs in the calling session, so `cd`, variable updates and other session changes behave as they do in a collected call.

Consume `events` while the line runs, then await `wait()` for its final `ExecuteResult`. That result carries the exit code and refusal; its output fields are empty because the bytes were already delivered as events. The result describes finished work; `ShellExecution` owns the running work. The default collected call consumes these same events into its result.

A policy with a `postExecute` method holds output until it approves the completed invocation. Such calls still use the same events and lifecycle, but their output arrives after that check. This policy buffer is separate from the bounded event queue.

To collect the complete result while observing output, use `await execution.collect(callback)`. The async callback receives each event and is awaited before the next one is read. Collection owns cleanup, including when the callback fails.

In this example, `sendBytes` is the application's async output sink:

```ts theme={null}
const execution = await session.shell('echo ready; echo warning >&2', { stream: true })
try {
  for await (const event of execution.events) {
    await sendBytes(event.stream, event.data)
  }
  const result = await execution.wait()
  console.log(result.exitCode)
} finally {
  await execution.close()
}
```

Do not await `wait()` before consuming the events: a producer may be waiting for queue space. Call `cancel()` to request cancellation; `wait()` then rejects with `AbortError`. Call `await execution.close()` in `finally` to cancel unfinished work and join its cleanup when you stop reading early. Closing an execution that has finished is safe.

Closing follows the workspace's cancellation grace. An uncooperative provider may remain tracked as stopping after that grace expires.

### session.glob

```ts theme={null}
session.glob(pattern): Promise<string[]>
```

The paths a pattern matches, as the session sees them.

```ts theme={null}
const paths = await session.glob('/src/**/*.ts')
```

### session.explain

```ts theme={null}
session.explain.shell(line): Promise<ShellExplanation>
session.explain.vfs.<call>(...): Promise<VfsExplanation>
```

What `session.shell` or a `session.vfs` call would do, without running it: a line's verdict and parse tree, a VFS call's verdict and error, each with every policy's answer. See [Explain](https://docs.mirage.strukto.ai/home/policy/explain.md).

```ts theme={null}
const shellRes = await session.explain.shell('rm /data/x')
console.log(shellRes.exitCode, shellRes.reason)
for (const node of shellRes.node.children) {
  if ('command' in node) console.log(node.command, node.answers.map((a) => a.policy))
}
const vfsRes = await session.explain.vfs.write('/data/x', 'hi')
console.log(vfsRes.error, vfsRes.answers.map((a) => a.policy))
```

### session.vfs

The file API, run as the session. Paths are absolute, bytes are `Uint8Array`. A failure throws an `Error` whose `code` is the POSIX name, as Node's `fs` does: `ENOENT`, `EACCES`, `EROFS`.

| Call | Answers |
| - | - |
| `read(path, { offset, size })` | The bytes, whole or a range. |
| `write(path, data)`, `append(path, data)` | Nothing. |
| `stat(path, undefined, { nofollow, fresh })` | A `FileStat`. |
| `readdir(path)` | The full path of each entry. |
| `exists(path)` | `true` or `false`. |
| `mkdir(path)`, `rmdir(path)`, `unlink(path)` | Nothing. |
| `rename(src, dst)` | Nothing. |
| `truncate(path, length)` | Nothing. |

`stat` can reuse metadata from the mount's listing index. Set `fresh: true` to
ask the backend past that index, for example after another client replaces or
deletes a file. It defaults to `false`. Later calls see the answer too: a
changed or deleted file leaves the index, and a cached copy the backend cannot
vouch for is dropped. Namespace attributes still apply. The result remains a
`FileStat`, with `null` for backend version fields the backend does not provide. `nofollow: true` still reports a
trailing symlink itself. Session visibility and access rules apply to both modes.

```ts theme={null}
const current = await session.vfs.stat('/s3/report.csv', undefined, { fresh: true })
```

**FileStat**

**name** `string`

**type** `FileType`

`FILE`, `DIRECTORY`, `SYMLINK`, `CHAR_DEVICE` under `/dev`, or `FIFO` for a process substitution's `/dev/fd/N`. `BLOCK_DEVICE` and `SOCKET` exist in the enum but are never returned.

**size** `number | null`

The bytes a read answers; `null` when unknown.

**modified** `string | null`

ISO 8601.

**content** `ContentType | null`

A file's content shape, such as `text`.

**mode** `number | null`

The permission bits.

**uid, gid** `number | string | null`

**atime, ctime, birthtime** `string | null`

**fingerprint, revision** `string | null`

The backend's ETag and version, when it has them.

**extra** `Record\<string, unknown\>`

Backend-specific fields.

```ts theme={null}
const data = new TextEncoder().encode('hello\n')
await session.vfs.write('/notes.txt', data)
const bytes = await session.vfs.read('/notes.txt')
console.log(new TextDecoder().decode(bytes))
```

### session.tools

```ts theme={null}
session.tools.shell(command, signal?): Promise<ToolResult>
session.tools.read(path, offset?, limit?): Promise<ToolResult>
session.tools.write(path, content): Promise<ToolResult>
session.tools.edit(
  path, oldString, newString, replaceAll?,
): Promise<ToolResult>
session.tools.ls(path, signal?): Promise<ToolResult>
session.tools.grep(pattern, path, { ignoreCase?, ... }, signal?)
session.tools.glob(pattern, path?): Promise<ToolResult>
session.tools.call(name, args, signal?): Promise<ToolResult>
session.tools.names(): readonly string[]
```

The seven agent tools, for a model rather than a program: every answer is text, and a failure is `isError`, never a throw. `call` takes a tool's name and its JSON input, the form an agent loop gets from the model. The session has one table, shared by every caller, so `write` and `edit` refuse a file the agent has not read in full, or one that changed since it read it. `names()` is the tools the session's [profile](https://docs.mirage.strukto.ai/home/policy/explain.md#which-tools-the-agent-gets) leaves it, which MCP, RPC and the agent adapters offer: `shell` needs a command the allow list allows, `ls` and `grep` those commands, `write` and `edit` a mount the session may write.

| Tool | Answers |
| - | - |
| `shell` | The line's stdout, stderr and exit status as one text. |
| `read` | Numbered lines, `limit` of them from `offset`. |
| `write` | Writes a new file; an existing one only after a full `read`. |
| `edit` | Replaces `old_string` once, or everywhere with `replace_all`. |
| `ls`, `grep` | `ls` and `grep -rn`, as text. |
| `glob` | The files a pattern matches, one per line. |

**ToolResult**

**content** `\{ type: 'text', text: string \}[]`

The text handed back to the agent.

**isError** `boolean | undefined`

`true` when the call failed.

`readMedia(path)` answers an image or a PDF as media instead of numbered text, for adapters that hand media to the model. `@struktoai/mirage-core/workspace/tools/tool_descriptions` (needs `pnpm add @struktoai/mirage-core`) has each tool's description and JSON schema to hand the model, and the [agent adapters](https://docs.mirage.strukto.ai/typescript/agents/index.md) wire the tools into each framework. `new MirageToolOperations(session, false)`, from `@struktoai/mirage-core/workspace/tools/tool_operations`, is a table without the read guard.

```ts theme={null}
await session.tools.call('read', { path: '/notes.txt' })
const result = await session.tools.call('edit', {
  path: '/notes.txt',
  old_string: 'hello',
  new_string: 'hi',
})
console.log(result.content[0]?.text, result.isError === true)
```


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