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

```python theme={null}
from mirage import Workspace
```

```python theme={null}
class Workspace(
    mounts: dict[str, VFS],
    mode: MountMode = MountMode.READ,
    ...,
)
```

One virtual terminal over the backends mounted at each prefix.

**mounts** `dict[str, VFS]` *required*

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

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

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

**profiles** `dict[str, SessionProfile]`

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

**profile** `str`

The profile a session gets when it names none.

**policies** `list[Policy]`

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

**on\_ask** `AskHandler`

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

**workspace\_id** `str`

The workspace's id, generated when unset.

**session\_id** `str`

The default session's id.

**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 `owns_store=True`.

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

```python theme={null}
from mirage import MountMode, Workspace
from mirage.vfs.ram import RAMVFS

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

Set the per-queue capacity when creating the workspace:

```python theme={null}
from mirage import IOConfig, Workspace
from mirage.vfs.ram import RAMVFS

ws = Workspace({"/": RAMVFS()}, io=IOConfig(buffer_bytes=262144))
```

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

```python theme={null}
from mirage import MountMode, Workspace
from mirage.vfs.ram import RAMVFS
from mirage.workspace.store.redis import RedisWorkspaceStateStore

store = RedisWorkspaceStateStore(url="redis://localhost:6379/0")
ws = Workspace(
    {"/": RAMVFS()},
    mode=MountMode.WRITE,
    workspace_id="agent-ws",
    session_id="s1",
    store=store,
)
```

### ws.session

```python theme={null}
await ws.session(
    session_id, mounts=None, *, profile=None, permissions=None
) -> 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 raise `ValueError` 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.create_session` is the synchronous version that initializes the session and returns its `SessionState` without returning an executable `Session` client.

```python theme={null}
session = await ws.session("agent")
```

### ws.set\_profile, ws.set\_session\_profile

```python theme={null}
ws.set_profile(name, profile) -> None
await ws.set_session_profile(session_id, profile) -> SessionState
```

Change the rules after the workspace is built. `set_profile` defines a profile name or replaces what it means; a document no session could run under raises `PolicyError` and leaves the table as it was. A live session keeps its rules until `set_session_profile` 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. `None` picks the workspace default, and a document passed directly runs without a name.

```python theme={null}
ws.set_profile(
    "user",
    {"commands": {"allow": ["ls", "cat"]}, "paths": {"hide": ["/data/secret"]}},
)
await ws.set_session_profile("agent", "user")
```

### ws.list\_sessions, ws.close\_session

```python theme={null}
ws.list_sessions() -> list[SessionState]
await ws.close_session(session_id) -> None
```

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

**SessionState**

**session\_id** `str`

**cwd** `str`

The working directory.

**env** `Mapping[str, str]`

The exported variables.

**profile** `str | None`

The profile it was created under.

**mount\_modes** `dict[str, MountMode] | None`

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

**last\_exit\_code** `int`

`$?`.

**created\_at** `float`

Unix time.

```python theme={null}
print([s.session_id for s in ws.list_sessions()])
await ws.close_session("agent")
```

### ws.cancel, ws.kill

```python theme={null}
await ws.cancel(session_id=None) -> int
await ws.kill(session_id=None) -> int
```

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 returns once they have ended; each ends with `MirageAbortError`. `kill` kills the background jobs (`cmd &`) and the programs machines started. Each answers how many it stopped.

```python theme={null}
await ws.cancel("agent")
await ws.kill()
```

### ws.snapshot, Workspace.load

```python theme={null}
await ws.snapshot(target, *, compress=None, s3=None) -> int
await Workspace.load(source, *, s3=None, ...) -> Workspace
```

Save the workspace to a tar and rebuild it from one. `target` and `source` are a path, a file object, or an object key with `s3=`. `snapshot` returns the tar's size in bytes.

* While it captures, new lines and file writes wait. Running ones get 30 seconds to end, else it raises `OSError` (`EBUSY`). Disk mount files are streamed, never held 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.

```python theme={null}
await ws.snapshot("run.tar")
restored = await Workspace.load("run.tar")
```

### ws.copy

```python theme={null}
await ws.copy() -> 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; a disk mount's copy lives in a new temporary directory. 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.

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

### ws.decisions

```python theme={null}
ws.decisions.pending(session_id="") -> tuple[Decision, ...]
await ws.decisions.answer(
    decision_id, outcome, scope=Scope.ONCE, note=""
) -> None
```

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` 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** `str`

The id to answer it by.

**session\_id** `str`

The session that ran the line.

**command** `str`

The command name.

**argv** `tuple[str, ...]`

The words after the name, expanded.

**cwd** `str`

**paths** `tuple[str, ...]`

The paths the line names.

**reason** `str`

The rule's reason.

**outcome** `Outcome | None`

The answer; `None` while it waits.

**scope** `Scope`

**note** `str`

What the host said when answering.

```python theme={null}
from mirage import Outcome

for ask in ws.decisions.pending():
    await ws.decisions.answer(ask.id, Outcome.ALLOW)
```

### ws.close

```python theme={null}
await ws.close() -> None
```

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

## Session

```python theme={null}
from mirage import Session
```

```python theme={null}
class Session(workspace: Workspace, session_id: str)
```

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.

**session\_id** `str`

**state** `SessionState`

The session's record, as returned by [`ws.list_sessions`](#ws-list_sessions-ws-close_session).

**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

```python theme={null}
await session.shell(
    command, stdin=None, cwd=None, env=None,
    cancel=None, record=True, stream=False, machine=None,
) -> IOResult | ShellExecution
```

Runs a shell line as the session. With `stream=False`, it collects the execution’s output and returns an `IOResult`. A non-zero exit is a result, not an exception. `ws.shell` has the same streaming option and accepts `session_id` to select the session.

**stdin** `bytes | AsyncIterator[bytes]`

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

**cwd** `str`

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** `dict[str, str]`

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

**cancel** `asyncio.Event`

Setting it stops the line and raises `MirageAbortError`.

**record** `bool` (default: True)

`False` keeps the line out of history.

**machine** `str`

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. Raises `ValueError` for a name the workspace does not have.

**IOResult**

**exit\_code** `int`

**stdout\_str()** `async -\> str`

The output as text. `materialize_stdout()` returns the raw bytes.

**stderr\_str()** `async -\> str`

The error output as text. `materialize_stderr()` returns the raw bytes.

**decision** `PolicyDecision | None`

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

**PolicyDecision**

**kind** `str`

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

**reason** `str`

The rule's or the policy's words.

**policy** `str`

The policy class that refused; empty for an ask.

**ask\_id** `str | None`

The ask's id, for `pending`.

```python theme={null}
result = await session.shell("wc -l", stdin=b"a\nb\n")
print(result.exit_code, await result.stdout_str())
```

### 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 `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 `IOResult`. That result carries the exit code and refusal; its output fields are empty because the bytes were already delivered as events. `IOResult` describes a finished result; `ShellExecution` owns the running work. The default collected call consumes these same events into its result.

A policy with a `post_execute` 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(on_event=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, `send_bytes` is the application's async output sink:

```python theme={null}
execution = await session.shell("echo ready; echo warning >&2", stream=True)
async with execution:
    async for event in execution.events:
        await send_bytes(event.stream, event.data)
    result = await execution.wait()
print(result.exit_code)
```

Do not await `wait()` before consuming the events: a producer may be waiting for queue space. Call `cancel()` to request cancellation; `wait()` then raises `MirageAbortError`. Use the async context manager, or `await execution.aclose()` in `finally`, to cancel unfinished work and join its cleanup when you stop reading early. Closing an execution that has finished is safe.

### session.glob

```python theme={null}
await session.glob(pattern) -> list[str]
```

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

```python theme={null}
paths = await session.glob("/src/**/*.py")
```

### session.explain

```python theme={null}
await session.explain.shell(line) -> ShellExplanation
await session.explain.vfs.<call>(...) -> 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).

```python theme={null}
from mirage import CommandExplanation

shell_res = await session.explain.shell("rm /data/x")
print(shell_res.exit_code, shell_res.reason)
for node in shell_res.node.children:
    if isinstance(node, CommandExplanation):
        print(node.command, [a.policy for a in node.answers])
vfs_res = await session.explain.vfs.write("/data/x", b"hi")
print(vfs_res.error, [a.policy for a in vfs_res.answers])
```

### session.vfs

The file API, run as the session. Paths are absolute, bytes are `bytes`. A missing path raises `FileNotFoundError` and a refused one `PermissionError`.

| Call | Answers |
| - | - |
| `read(path, offset=0, size=None)` | The bytes, whole or a range. |
| `write(path, data)`, `append(path, data)` | `None` |
| `stat(path, nofollow=False, fresh=False)` | A `FileStat`. |
| `readdir(path)` | The full path of each entry. |
| `exists(path)` | `True` or `False`. |
| `mkdir(path)`, `rmdir(path)`, `unlink(path)` | `None` |
| `rename(src, dst)` | `None` |
| `truncate(path, length)` | `None` |

`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. 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 `None`
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.

```python theme={null}
current = await session.vfs.stat("/s3/report.csv", fresh=True)
```

**FileStat**

**name** `str`

**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** `int | None`

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

**modified** `str | None`

ISO 8601.

**content** `ContentType | None`

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

**mode** `int | None`

The permission bits.

**uid, gid** `int | str | None`

**atime, ctime, birthtime** `str | None`

**fingerprint, revision** `str | None`

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

**extra** `dict`

Backend-specific fields.

```python theme={null}
await session.vfs.write("/notes.txt", b"hello\n")
print(await session.vfs.read("/notes.txt"))
```

### session.tools

```python theme={null}
await session.tools.shell(command) -> ToolResult
await session.tools.read(path, offset=0, limit=2000) -> ToolResult
await session.tools.write(path, content) -> ToolResult
await session.tools.edit(
    path, old_string, new_string, replace_all=False
) -> ToolResult
await session.tools.ls(path) -> ToolResult
await session.tools.grep(pattern, path, ignore_case=False, ...)
await session.tools.glob(pattern, path="/") -> ToolResult
await session.tools.call(name, arguments) -> ToolResult
session.tools.names() -> tuple[str, ...]
```

The seven agent tools, for a model rather than a program: every answer is text, and a failure is `is_error`, never an exception. `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**

**text** `str`

The text handed back to the agent.

**is\_error** `bool`

`True` when the call failed.

`mirage.workspace.tools.tool_descriptions` has each tool's description and JSON schema to hand the model, and the [agent adapters](https://docs.mirage.strukto.ai/python/agents/index.md) wire the tools into each framework. `MirageToolOperations(session, stale_write_protection=False)`, from `mirage.workspace.tools.tool_operations`, is a table without the read guard.

```python theme={null}
await session.tools.call("read", {"path": "/notes.txt"})
result = await session.tools.call("edit", {
    "path": "/notes.txt",
    "old_string": "hello",
    "new_string": "hi",
})
print(result.text, result.is_error)
```


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