# Authentication Source: https://docs.mirage.strukto.ai/api/authentication Authenticate requests to your OSS Server. Use the bearer token configured on your server, or a JWT accepted by its issuer and audience settings. Default local mode without a configured token allows requests without authentication. ```bash theme={null} curl http://127.0.0.1:8765/v1/workspaces \ --header "Authorization: Bearer $MIRAGE_AUTH_TOKEN" ``` Omit the authorization header in local mode with no token configured. See [HTTP](/home/access/http#configure-authentication) for token, JWT, and OAuth settings. # Errors Source: https://docs.mirage.strukto.ai/api/errors HTTP errors, command exit codes and retry behavior. A `200` from `POST /v1/workspaces/{workspace_id}/shell` means the server ran the line, not that the line succeeded: check `exit_code`. Every HTTP error answers JSON in one shape, on both servers. Requests past a limit answer `429` with `Retry-After` ([rate limits](/home/access/http#rate-limits)). ## Error body ```json theme={null} { "error": { "code": "missing_field", "message": "config.mounts is required", "param": "config.mounts" } } ``` | Field | Present | Means | | - | - | - | | `code` | Always | What went wrong. Codes are stable: branch on them. A code your client does not know falls back to the HTTP status. | | `message` | Always | Human-readable text. Its wording can change, so do not parse it. It never repeats a value you sent in the body, a header or the query. | | `param` | Request-shape errors | The request field at fault. A body field is a dotted path from the body's root, such as `config.mounts` or `mounts[0].mode`. A query or path parameter is its bare name. | | `errno` | Failed file calls | The POSIX condition, such as `ENOENT` or `STALE_WRITE`. See [file call conditions](/home/access/errors#file-calls). | | `decision` | Policy refusals | The [decision record](/home/policy/policies): `kind`, `reason`, `policy` and `ask_id`. | | `missing` | Saved-config routes | Names that must exist first, such as the secret stores a config refers to. | Detect an error by its HTTP status, never by the presence of an `error` key: a success body can carry an `error` field of its own, such as a finished line's `error` in `GET /v1/workspaces/{workspace_id}/lines/{line_id}`. ## Status codes | Status | Codes | Means | Recovery | | - | - | - | - | | `400` | `invalid_request`, `invalid_json`, `missing_field`, `unknown_field`, `invalid_value` | The request is malformed, a field is missing, unknown or has a wrong value, or options conflict. | Fix the field named in `param`, or the request, before retrying. | | `401` | `unauthorized` | The token is missing or wrong. The response carries `WWW-Authenticate: Bearer`. | Send a valid bearer token; sign in again if it expired. | | `403` | `forbidden`, `policy_refused`, `host_not_allowed`, `origin_not_allowed`, `storage_full` | A mount mode, permission or policy refused the call, the `Host` or browser origin is not allowed, or the backend is out of space or quota. | Check policies, mount modes, the API host and the browser origin; free space for `storage_full`. | | `404` | `not_found` | The workspace, session, job, file or route does not exist, or you may not see it. | Verify the identifier, file path or URL. | | `405` | `method_not_allowed` | The path exists but does not take this method. | Use the method the endpoint documents. | | `409` | `conflict`, `already_exists`, `workspace_busy`, `workspace_stopped`, `stale_write` | An identifier is taken, the workspace is busy or stopped, or a file changed since it was read. | Resolve the conflict before retrying: start a stopped workspace, read a changed file again. | | `413` | `too_large` | A request body, multipart part or stdin exceeds its size limit. | Reduce the input size and check the endpoint's limits. | | `426` | `upgrade_required` | WebSocket routes only: a plain request reached a route that needs a WebSocket upgrade. | Open the route as a WebSocket. | | `429` | `rate_limited`, `session_limit` | A rate limit or the workspace's session limit was reached. | Wait for `Retry-After` on `rate_limited`; close unused sessions on `session_limit`. | | `499` | `canceled` | A running shell job was canceled. | Check its output and any side effects before rerunning it. | | `500` | `internal` | The server failed. The message is always `internal server error`; the cause is in the server log. | Check the server log and for side effects before retrying. | | `501` | `not_supported` | The server does not support the call, such as saved configs on a server with accounts. | Check the deployment's saved-configuration support. | | `503` | `unavailable`, `server_full`, `shutting_down` | The server is at its workspace limit, shutting down, or cannot reach a worker. | Retry after capacity or availability recovers. | A route that needs a running workspace answers `409` `workspace_stopped` when your workspace is stopped. A workspace that does not exist, or that you may not see, is `404` `not_found`. A failed file call picks its code from its POSIX condition: | Condition | Status | Code | | - | - | - | | `ENOENT`, `NO_XATTR` | `404` | `not_found` | | `EACCES`, `EPERM`, `EROFS` | `403` | `forbidden`, or `policy_refused` when a policy refused the call | | `EEXIST` | `409` | `already_exists` | | `ENOTEMPTY`, `EBUSY` | `409` | `conflict` | | `STALE_WRITE` | `409` | `stale_write` | | `ENOTDIR`, `EISDIR`, `EINVAL`, `EXDEV`, `ELOOP`, `ENOTSUP`, `EFBIG` | `400` | `invalid_request` | | `EDQUOT` | `403` | `storage_full` | | `EIO`, `EPIPE`, `EBADF` | `500` | `internal` | Each endpoint's **Errors** section lists its documented failures. The complete [OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) retains every response schema. Some bodies are not this shape. The [RPC](/home/access/rpc#errors) and [MCP](/home/access/mcp) endpoints answer JSON-RPC errors. A failed file call carries the inner object above, `{code, message, errno, decision}`, in an RPC error's `data`, and as the text of a failed MCP `vfs_` tool. Records inside an NDJSON stream follow the stream's own format once the `200` is sent. The readiness endpoint answers `503` with `{"status": "full"}` or `{"status": "shutting_down"}` when the server cannot accept new workspaces. ## Which error is reported A response reports one error, the first one found: 1. Query and path parameters, before the body. 2. The body's declared fields, in the order the endpoint's schema lists them. 3. Unknown keys, last, in the order they appear in the body. The server reads a body as JSON whatever its `Content-Type` says, except `multipart/*` and `application/octet-stream`, so `curl -d` works without a header. Request-shape errors use these messages, where `` is the field's path: | Problem | Code | Message | | - | - | - | | The body is not JSON | `invalid_json` | `body must be JSON` | | The body is JSON but not an object | `invalid_request` | `body must be a JSON object` | | A required field is missing | `missing_field` | ` is required` | | A key the endpoint does not know | `unknown_field` | ` is not a known field` | | A value of the wrong type or outside its choices | `invalid_value` | ` must be ` | `` is `a string`, `an integer`, `a number`, `a boolean`, `an object`, `an array` or `one of a, b, c`. ## Examples ### Missing or invalid credentials A request without a valid token returns HTTP `401` with `WWW-Authenticate: Bearer`: ```json theme={null} {"error": {"code": "unauthorized", "message": "unauthorized"}} ``` Supply a valid token before retrying. See [Authentication](/api/authentication). ### Workspace identifier conflict Creating `demo` again with a different configuration returns HTTP `409`: ```json theme={null} {"error": {"code": "already_exists", "message": "workspace id already exists"}} ``` Choose another identifier for a different workspace. Retrying the original configuration with the same identifier returns HTTP `200` and the existing workspace, with the same response shape as a successful `201` creation. ### Invalid request field Sending a numeric workspace `id` returns HTTP `400`: ```json theme={null} {"error": {"code": "invalid_value", "message": "id must be a string", "param": "id"}} ``` Change `id` to a string before retrying. ### Unknown runtime or machine A shell request whose `runtime` or `machine` the workspace does not have is refused with HTTP `400` before anything runs: ```json theme={null} {"error": {"code": "invalid_value", "message": "runtime must be one of python", "param": "runtime"}} ``` The message lists the names the workspace has, or says the field must be unset when the workspace has none. ### Policy refusal of a file call A VFS call a policy refuses returns HTTP `403`: ```json theme={null} { "error": { "code": "policy_refused", "message": "Permission denied", "errno": "EACCES", "decision": { "kind": "deny", "reason": "writes under /data are not allowed", "policy": "PermissionsPolicy", "ask_id": null } } } ``` A shell line a policy refuses still returns `200`; check its `decision`. ### Failed shell job A shell job that fails inside the server returns HTTP `500` with the fixed message: ```json theme={null} {"error": {"code": "internal", "message": "internal server error"}} ``` The job's own error stays readable as `error` in `GET /v1/workspaces/{workspace_id}/lines/{line_id}`, and in the final record of a stream. Check for side effects before retrying. ## Shell exit codes A completed shell request can return HTTP `200` with a nonzero `exit_code`. Inspect `exit_code`, `stdout`, `stderr` and `decision` before treating the command as successful. The response's HTTP status describes the request, while `exit_code` describes the shell command. # List asks Source: https://docs.mirage.strukto.ai/api/operations/asks/list-asks /openapi.yaml get /v1/workspaces/{workspace_id}/asks List pending approval requests. Set `all=true` to include requests that have already been approved or denied. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Respond to ask Source: https://docs.mirage.strukto.ai/api/operations/asks/respond-to-ask /openapi.yaml post /v1/workspaces/{workspace_id}/asks/{ask_id} Approve or deny a pending request and return the recorded decision. Returns `409` if the request has already been answered. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Check readiness Source: https://docs.mirage.strukto.ai/api/operations/daemon/check-readiness /openapi.yaml get /v1/daemon/ready Check whether the server can accept new workspaces. Returns `503` when capacity is reached or shutdown is in progress. Use this endpoint for load balancer readiness checks. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `503` | The server is full or shutting down and cannot accept new workspaces. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Shut down server Source: https://docs.mirage.strukto.ai/api/operations/daemon/shut-down-server /openapi.yaml post /v1/daemon/shutdown Request graceful shutdown of the server and its active workspaces. This operation is unavailable to account-scoped callers. A custom server must configure `on_idle_exit` in Python or `onIdleExit` in TypeScript. Without that callback, it continues serving. See [server shutdown configuration](/home/access/http#shut-down). > [accordion] Errors > > | Status | Meaning | > | - | - | > | `401` | The token is missing or wrong (`unauthorized`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Read SKILL.md Source: https://docs.mirage.strukto.ai/api/operations/documents/read-skillmd /openapi.yaml get /v1/workspaces/{workspace_id}/skill-md Read SKILL.md as Markdown for the selected session. ```markdown 200 --- name: workspace-commands description: The CLIs registered in this workspace and how to call them. --- # Available commands No CLIs are registered. ``` > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Read VFS.md Source: https://docs.mirage.strukto.ai/api/operations/documents/read-vfsmd /openapi.yaml get /v1/workspaces/{workspace_id}/vfs-md Read VFS.md as Markdown for the selected session. ```markdown 200 --- name: workspace-filesystem description: The virtual filesystem layout of this workspace. --- # Virtual Filesystem You work in a terminal over a virtual filesystem. Read files with shell commands; access is checked for each operation. | Path | Description | | --- | --- | | `/` | write | | `/dev` | write | ## 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 | | --- | --- | | `/` | Almost all Unix commands. | | `/dev` | Almost all Unix commands. | ## Limitations of Unix Commands for VFS Where a path differs from a local filesystem: | Path | Limitations | | --- | --- | | `/` | `grep -r`, `find` and `du` stop after 10000 files; a glob matching more, `tar -c`, `cp -r` and `rm -r` are refused. | | `/dev` | `grep -r`, `find` and `du` stop after 10000 files; a glob matching more, `tar -c`, `cp -r` and `rm -r` are refused. | Run `man ` or ` --help` for one command's usage. ``` > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Write SKILL.md Source: https://docs.mirage.strukto.ai/api/operations/documents/write-skillmd /openapi.yaml put /v1/workspaces/{workspace_id}/skill-md Write SKILL.md to the specified path for the selected session. ```markdown 200 --- name: workspace-commands description: The CLIs registered in this workspace and how to call them. --- # Available commands No CLIs are registered. ``` > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Write VFS.md Source: https://docs.mirage.strukto.ai/api/operations/documents/write-vfsmd /openapi.yaml put /v1/workspaces/{workspace_id}/vfs-md Write VFS.md to the specified path for the selected session. ```markdown 200 --- name: workspace-filesystem description: The virtual filesystem layout of this workspace. --- # Virtual Filesystem You work in a terminal over a virtual filesystem. Read files with shell commands; access is checked for each operation. | Path | Description | | --- | --- | | `/` | write | | `/dev` | write | ## 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 | | --- | --- | | `/` | Almost all Unix commands. | | `/dev` | Almost all Unix commands. | ## Limitations of Unix Commands for VFS Where a path differs from a local filesystem: | Path | Limitations | | --- | --- | | `/` | `grep -r`, `find` and `du` stop after 10000 files; a glob matching more, `tar -c`, `cp -r` and `rm -r` are refused. | | `/dev` | `grep -r`, `find` and `du` stop after 10000 files; a glob matching more, `tar -c`, `cp -r` and `rm -r` are refused. | Run `man ` or ` --help` for one command's usage. ``` > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Get job Source: https://docs.mirage.strukto.ai/api/operations/jobs/get-job /openapi.yaml get /v1/workspaces/{workspace_id}/jobs/{job_id} Get a job with its process IDs, including descendant processes still tracked by the workspace. Completed jobs remain available until the session removes them. Running `wait` or `jobs` can remove completed jobs after reporting them. Timestamps are Unix seconds. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # List jobs Source: https://docs.mirage.strukto.ai/api/operations/jobs/list-jobs /openapi.yaml get /v1/workspaces/{workspace_id}/jobs List jobs tracked by workspace sessions. Filter by session, state, or command execution. Completed jobs remain available until the session removes them. Running `wait` or `jobs` can remove completed jobs after reporting them. Timestamps are Unix seconds. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Close stdin Source: https://docs.mirage.strukto.ai/api/operations/lines/close-stdin /openapi.yaml delete /v1/workspaces/{workspace_id}/lines/{line_id}/stdin Close stdin for a running command. The command can read any buffered input before reaching end of file. ```http 204 No Content HTTP/1.1 204 No Content ``` > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `409` | The request conflicts with the current state. The id or name is taken (`already_exists`), the workspace is busy on another server or starting or stopping (`workspace_busy`), the workspace is stopped (`workspace_stopped`), a file changed since it was read (`stale_write`), or the state allows no such change (`conflict`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Get command Source: https://docs.mirage.strukto.ai/api/operations/lines/get-command /openapi.yaml get /v1/workspaces/{workspace_id}/lines/{line_id} Get a command execution with its job, process, and machine IDs. Use the `line_id` returned by the shell endpoint. Completed commands are retained for up to one hour, with a maximum of 1,024 records. Servers sharing a workspace store share these records; snapshots preserve completed records. Timestamps are Unix seconds. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # List commands Source: https://docs.mirage.strukto.ai/api/operations/lines/list-commands /openapi.yaml get /v1/workspaces/{workspace_id}/lines List running and recently completed commands, oldest first. Each record represents one submitted shell command or script. Completed commands are retained for up to one hour, with a maximum of 1,024 records. Servers sharing a workspace store share these records; snapshots preserve completed records. Timestamps are Unix seconds. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Write stdin Source: https://docs.mirage.strukto.ai/api/operations/lines/write-stdin /openapi.yaml post /v1/workspaces/{workspace_id}/lines/{line_id}/stdin Send input to a running command with open stdin. The request completes when the bytes are buffered. If the command reads slowly, the request waits. ```http 204 No Content HTTP/1.1 204 No Content ``` > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `409` | The request conflicts with the current state. The id or name is taken (`already_exists`), the workspace is busy on another server or starting or stopping (`workspace_busy`), the workspace is stopped (`workspace_stopped`), a file changed since it was read (`stale_write`), or the state allows no such change (`conflict`). | > | `499` | The caller disconnected before the bytes were buffered. The bytes not yet buffered are dropped. The response has no body. | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Get machine Source: https://docs.mirage.strukto.ai/api/operations/machines/get-machine /openapi.yaml get /v1/workspaces/{workspace_id}/machines/{machine_id} Get machine status and the tracked processes found on it. The machine is checked when requested. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # List machines Source: https://docs.mirage.strukto.ai/api/operations/machines/list-machines /openapi.yaml get /v1/workspaces/{workspace_id}/machines List machines used to run workspace programs, with the local host first. Each machine is checked when requested. `managed` means Mirage can inspect and stop every process started by its programs. `reachable` limits control to processes Mirage started directly. `unreachable` means the latest check failed. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Create policy Source: https://docs.mirage.strukto.ai/api/operations/policies/create-policy /openapi.yaml post /v1/policies Save a named Python policy program. Returns `409` if the name already exists. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `409` | The request conflicts with the current state. The id or name is taken (`already_exists`), the workspace is busy on another server or starting or stopping (`workspace_busy`), the workspace is stopped (`workspace_stopped`), a file changed since it was read (`stale_write`), or the state allows no such change (`conflict`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Delete policy Source: https://docs.mirage.strukto.ai/api/operations/policies/delete-policy /openapi.yaml delete /v1/policies/{ref} Delete a saved policy. Returns `204 No Content` with no response body. ```http 204 No Content HTTP/1.1 204 No Content ``` > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Get policy Source: https://docs.mirage.strukto.ai/api/operations/policies/get-policy /openapi.yaml get /v1/policies/{ref} Get saved policy source code. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # List policies Source: https://docs.mirage.strukto.ai/api/operations/policies/list-policies /openapi.yaml get /v1/policies List saved policy names in alphabetical order. Use the get endpoint to read policy source code. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `401` | The token is missing or wrong (`unauthorized`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Update policy Source: https://docs.mirage.strukto.ai/api/operations/policies/update-policy /openapi.yaml put /v1/policies/{ref} Replace saved policy source code. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Get process Source: https://docs.mirage.strukto.ai/api/operations/processes/get-process /openapi.yaml get /v1/workspaces/{workspace_id}/processes/{pid} Get a tracked process by its process ID. Ended processes are retained for up to one hour, with a maximum of 1,024 records. Servers sharing a workspace store share these records; snapshots preserve ended records. Timestamps are Unix seconds. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # List processes Source: https://docs.mirage.strukto.ai/api/operations/processes/list-processes /openapi.yaml get /v1/workspaces/{workspace_id}/processes List running and recently ended processes, ordered by process ID. Filter by session, state, command execution, job, or machine. Ended processes are retained for up to one hour, with a maximum of 1,024 records. Servers sharing a workspace store share these records; snapshots preserve ended records. Timestamps are Unix seconds. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | A query parameter is not valid (`invalid_value`, with `param`), such as an unknown `state` or a `machine` not in `provider:name` format. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Create CLI Source: https://docs.mirage.strukto.ai/api/operations/saved-clis/create-cli /openapi.yaml post /v1/clis Save a named CLI configuration. Fields are validated for the selected type. Secret values are stored securely and omitted from read responses. String fields can reference secrets in a saved store. Returns `409` if the name exists. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed or a field is not valid for the type (`param` names it), or the fields refer to a secret store that is not saved yet (`invalid_request`; `missing` lists the stores to add first). | > | `401` | The token is missing or wrong (`unauthorized`). | > | `409` | The request conflicts with the current state. The id or name is taken (`already_exists`), the workspace is busy on another server or starting or stopping (`workspace_busy`), the workspace is stopped (`workspace_stopped`), a file changed since it was read (`stale_write`), or the state allows no such change (`conflict`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Delete CLI Source: https://docs.mirage.strukto.ai/api/operations/saved-clis/delete-cli /openapi.yaml delete /v1/clis/{ref} Delete a saved CLI configuration. ```http 204 No Content HTTP/1.1 204 No Content ``` > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Get CLI Source: https://docs.mirage.strukto.ai/api/operations/saved-clis/get-cli /openapi.yaml get /v1/clis/{ref} Get a saved CLI configuration without secret values. The `sealed` field lists stored secret names. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # List CLI types Source: https://docs.mirage.strukto.ai/api/operations/saved-clis/list-cli-types /openapi.yaml get /v1/clis/types List supported CLI configuration types and their fields. Available types depend on the server. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `401` | The token is missing or wrong (`unauthorized`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # List CLIs Source: https://docs.mirage.strukto.ai/api/operations/saved-clis/list-clis /openapi.yaml get /v1/clis List saved CLI configurations for reuse in workspace templates. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Update CLI Source: https://docs.mirage.strukto.ai/api/operations/saved-clis/update-cli /openapi.yaml put /v1/clis/{ref} Update a saved CLI configuration. The name and type cannot change. Omitted secret fields keep their values; `null` removes a field. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed or a field is not valid for the type (`param` names it), or the fields refer to a secret store that is not saved yet (`invalid_request`; `missing` lists the stores to add first). | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Create machine Source: https://docs.mirage.strukto.ai/api/operations/saved-machines/create-machine /openapi.yaml post /v1/machines Save a named machine configuration. Fields are validated for the selected type. Secret values are stored securely and omitted from read responses. String fields can reference secrets in a saved store. Returns `409` if the name exists. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed or a field is not valid for the type (`param` names it), or the fields refer to a secret store that is not saved yet (`invalid_request`; `missing` lists the stores to add first). | > | `401` | The token is missing or wrong (`unauthorized`). | > | `409` | The request conflicts with the current state. The id or name is taken (`already_exists`), the workspace is busy on another server or starting or stopping (`workspace_busy`), the workspace is stopped (`workspace_stopped`), a file changed since it was read (`stale_write`), or the state allows no such change (`conflict`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Delete machine Source: https://docs.mirage.strukto.ai/api/operations/saved-machines/delete-machine /openapi.yaml delete /v1/machines/{ref} Delete a saved machine configuration. ```http 204 No Content HTTP/1.1 204 No Content ``` > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Get machine Source: https://docs.mirage.strukto.ai/api/operations/saved-machines/get-machine /openapi.yaml get /v1/machines/{ref} Get a saved machine configuration without secret values. The `sealed` field lists stored secret names. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # List machine types Source: https://docs.mirage.strukto.ai/api/operations/saved-machines/list-machine-types /openapi.yaml get /v1/machines/types List supported machine configuration types and their fields. Available types depend on the server. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `401` | The token is missing or wrong (`unauthorized`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # List machines Source: https://docs.mirage.strukto.ai/api/operations/saved-machines/list-machines /openapi.yaml get /v1/machines List saved machine configurations for reuse in workspace templates. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Update machine Source: https://docs.mirage.strukto.ai/api/operations/saved-machines/update-machine /openapi.yaml put /v1/machines/{ref} Update a saved machine configuration. The name and type cannot change. Omitted secret fields keep their values; `null` removes a field. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed or a field is not valid for the type (`param` names it), or the fields refer to a secret store that is not saved yet (`invalid_request`; `missing` lists the stores to add first). | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Create runtime Source: https://docs.mirage.strukto.ai/api/operations/saved-runtimes/create-runtime /openapi.yaml post /v1/runtimes Save a named runtime configuration. Fields are validated for the selected type. Secret values are stored securely and omitted from read responses. String fields can reference secrets in a saved store. Returns `409` if the name exists. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed or a field is not valid for the type (`param` names it), or the fields refer to a secret store that is not saved yet (`invalid_request`; `missing` lists the stores to add first). | > | `401` | The token is missing or wrong (`unauthorized`). | > | `409` | The request conflicts with the current state. The id or name is taken (`already_exists`), the workspace is busy on another server or starting or stopping (`workspace_busy`), the workspace is stopped (`workspace_stopped`), a file changed since it was read (`stale_write`), or the state allows no such change (`conflict`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Delete runtime Source: https://docs.mirage.strukto.ai/api/operations/saved-runtimes/delete-runtime /openapi.yaml delete /v1/runtimes/{ref} Delete a saved runtime configuration. ```http 204 No Content HTTP/1.1 204 No Content ``` > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Get runtime Source: https://docs.mirage.strukto.ai/api/operations/saved-runtimes/get-runtime /openapi.yaml get /v1/runtimes/{ref} Get a saved runtime configuration without secret values. The `sealed` field lists stored secret names. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # List runtime types Source: https://docs.mirage.strukto.ai/api/operations/saved-runtimes/list-runtime-types /openapi.yaml get /v1/runtimes/types List supported runtime configuration types and their fields. Available types depend on the server. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `401` | The token is missing or wrong (`unauthorized`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # List runtimes Source: https://docs.mirage.strukto.ai/api/operations/saved-runtimes/list-runtimes /openapi.yaml get /v1/runtimes List saved runtime configurations for reuse in workspace templates. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Update runtime Source: https://docs.mirage.strukto.ai/api/operations/saved-runtimes/update-runtime /openapi.yaml put /v1/runtimes/{ref} Update a saved runtime configuration. The name and type cannot change. Omitted secret fields keep their values; `null` removes a field. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed or a field is not valid for the type (`param` names it), or the fields refer to a secret store that is not saved yet (`invalid_request`; `missing` lists the stores to add first). | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Create VFS Source: https://docs.mirage.strukto.ai/api/operations/saved-vfs/create-vfs /openapi.yaml post /v1/vfs Save a named VFS configuration. Fields are validated for the selected type. Secret values are stored securely and omitted from read responses. String fields can reference secrets in a saved store. Returns `409` if the name exists. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed or a field is not valid for the type (`param` names it), or the fields refer to a secret store that is not saved yet (`invalid_request`; `missing` lists the stores to add first). | > | `401` | The token is missing or wrong (`unauthorized`). | > | `409` | The request conflicts with the current state. The id or name is taken (`already_exists`), the workspace is busy on another server or starting or stopping (`workspace_busy`), the workspace is stopped (`workspace_stopped`), a file changed since it was read (`stale_write`), or the state allows no such change (`conflict`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Delete VFS Source: https://docs.mirage.strukto.ai/api/operations/saved-vfs/delete-vfs /openapi.yaml delete /v1/vfs/{ref} Delete a saved VFS configuration. ```http 204 No Content HTTP/1.1 204 No Content ``` > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Get VFS Source: https://docs.mirage.strukto.ai/api/operations/saved-vfs/get-vfs /openapi.yaml get /v1/vfs/{ref} Get a saved VFS configuration without secret values. The `sealed` field lists stored secret names. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # List VFS Source: https://docs.mirage.strukto.ai/api/operations/saved-vfs/list-vfs /openapi.yaml get /v1/vfs List saved VFS configurations for reuse in workspace templates. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # List VFS types Source: https://docs.mirage.strukto.ai/api/operations/saved-vfs/list-vfs-types /openapi.yaml get /v1/vfs/types List supported VFS configuration types and their fields. Available types depend on the server. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `401` | The token is missing or wrong (`unauthorized`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Update VFS Source: https://docs.mirage.strukto.ai/api/operations/saved-vfs/update-vfs /openapi.yaml put /v1/vfs/{ref} Update a saved VFS configuration. The name and type cannot change. Omitted secret fields keep their values; `null` removes a field. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed or a field is not valid for the type (`param` names it), or the fields refer to a secret store that is not saved yet (`invalid_request`; `missing` lists the stores to add first). | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Check health Source: https://docs.mirage.strukto.ai/api/operations/service/check-health /openapi.yaml get /v1/health Check whether the server is running. This endpoint does not require authentication. # Run shell command Source: https://docs.mirage.strukto.ai/api/operations/shell/run-shell-command /openapi.yaml post /v1/workspaces/{workspace_id}/shell Run a shell command or script in the workspace and return its exit code and output. One endpoint serves three modes: | Mode | Request | Response | | - | - | - | | Run (default) | no query flags | One JSON result when the command ends. | | Stream | `stream=true` | NDJSON output records as they are produced, then a status record. | | Explain | `explain=true` | The policy decision. Nothing runs. | A `200` means the request was accepted, not that the command succeeded. Check `exit_code`. A policy refusal also returns `200`; check `decision` to know whether a policy refused anything. See Refused commands below. The request stays open until the command ends, and closing it cancels the command. To leave work running, end the command with `&`; it returns at once and the work appears under [jobs](/api/operations/jobs/list-jobs). Every result carries a `line_id` for the [lines](/api/operations/lines/get-command) endpoints. To send input, use a `multipart/form-data` body with a `stdin` part, or set `open_stdin=true` with `stream=true` to write while the command runs. See [Streaming and stdin](/api/streaming). ## Stream output Set `stream=true` to receive output as it is produced. Each line is one JSON record: output records carry base64 `data`, and the last record carries `status` and the final `result`. ```bash curl --no-buffer --request POST \ --url 'http://127.0.0.1:8765/v1/workspaces/{workspace_id}/shell?stream=true' \ --header 'Authorization: Bearer ' \ --header 'Content-Type: application/json' \ --data '{"command":"echo hello"}' ``` ```json {"stream":"stdout","data":"aGVsbG8K"} {"status":"done","result":{"exit_code":0,"stdout":"","stderr":"","decision":null,"line_id":"line_019a5e2c-7b41-7c3e-9f20-4d8e1a6b5c37"},"error":null} ``` ## Explain a command Set `explain=true` to get the policy decision without running the command. The response has one `node` per part of the line; the example below is trimmed to one command. ```bash curl --request POST \ --url 'http://127.0.0.1:8765/v1/workspaces/{workspace_id}/shell?explain=true' \ --header 'Authorization: Bearer ' \ --header 'Content-Type: application/json' \ --data '{"command":"echo hello"}' ``` ```json { "line": "echo hello", "outcome": "allow", "reason": "", "decision": null, "exit_code": 0, "node": { "type": "line", "text": "echo hello", "children": [ { "type": "command", "text": "echo hello", "command": "echo", "outcome": "allow", "children": [] } ] } } ``` ## Refused commands A policy refusal returns `200`. `decision` is set whenever a policy refused something on the line, and is `null` otherwise. The exit code alone does not tell you: * A command refused before it runs usually exits `126` with `: Permission denied`. * A refusal about a path appears as that path's own error, such as exit `1`. * A policy that judges a command after it ran sets exit `126` but does not undo its effects, and output already sent stays sent. A policy that judges the whole line after it ran drops the line's output. * A pipeline exits with its last stage's status unless `pipefail` is set, so a refused earlier stage can leave the exit code at `0`. A refusal does not always mean nothing ran, so do not retry a refused command blindly. A command denied before it ran: ```json { "exit_code": 126, "stdout": "", "stderr": "rm: Permission denied\n", "decision": { "kind": "deny", "reason": "rm is not allowed in this workspace", "policy": "PermissionsPolicy", "ask_id": null }, "line_id": "line_019a5e2c-7b41-7c3e-9f20-4d8e1a6b5c38" } ``` ## Keep stdin open With `stream=true` and `"open_stdin": true`, the first record carries the `line_id`, and you write input to that line while the command runs. See [Streaming and stdin](/api/streaming) for the full flow. ```json 200 { "exit_code": 0, "stdout": "hello\n", "stderr": "", "decision": null, "line_id": "line_019a5e2c-7b41-7c3e-9f20-4d8e1a6b5c37" } ``` > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed or its options conflict. The body is not JSON (`invalid_json`), a field is missing, unknown or of the wrong type (`missing_field`, `unknown_field`, `invalid_value`, with `param`; a field of the multipart `request` part is named as in a JSON body), or `runtime` or `machine` names one the workspace does not have (`invalid_value`, `param` `runtime` or `machine`), refused before anything runs. Or the multipart parts are malformed, missing or out of order, or the options conflict, as `stream` with `explain`, `open_stdin` without `stream=true` or with a stdin part, or `explain` with a multipart body, `cwd`, `runtime`, `machine` or `open_stdin` set to `true` (`invalid_request`). | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `409` | Another server owns command execution for this workspace (`workspace_busy`; the message names that server), or the workspace is stopped (`workspace_stopped`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `499` | The running shell job was canceled (`canceled`). | > | `500` | The command's job failed internally (`internal`). The message is always `internal server error`. The job's own error stays readable as `error` at `GET /v1/workspaces/{workspace_id}/lines/{line_id}`, and in a stream's final record. | > | `503` | The server is shutting down and accepts no new commands (`shutting_down`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Create template Source: https://docs.mirage.strukto.ai/api/operations/templates/create-template /openapi.yaml post /v1/templates Save a reusable workspace configuration. The server validates it when saved and preserves environment placeholders as written. Returns `409` if the name already exists. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Delete template Source: https://docs.mirage.strukto.ai/api/operations/templates/delete-template /openapi.yaml delete /v1/templates/{ref} Delete a saved template. Use the restore endpoint to recover it. ```http 204 No Content HTTP/1.1 204 No Content ``` > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Get template Source: https://docs.mirage.strukto.ai/api/operations/templates/get-template /openapi.yaml get /v1/templates/{ref} Get a saved workspace template. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # List templates Source: https://docs.mirage.strukto.ai/api/operations/templates/list-templates /openapi.yaml get /v1/templates List saved workspace templates by name. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `401` | The token is missing or wrong (`unauthorized`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Restore template Source: https://docs.mirage.strukto.ai/api/operations/templates/restore-template /openapi.yaml post /v1/templates/{ref}/restore Restore a deleted template. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `501` | The server does not support this call (`not_supported`). Saved configs are kept only on a server of one account. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Append to file Source: https://docs.mirage.strukto.ai/api/operations/vfs/append-to-file /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/append Append the supplied bytes to a file. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Call VFS function Source: https://docs.mirage.strukto.ai/api/operations/vfs/call-vfs-function /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/{name} Call a VFS function by name using the selected session and its permissions. Request arguments and the JSON response depend on the function. The response example shows headers only. ```http 200 Headers only HTTP/1.1 200 OK Content-Type: application/json ``` > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Check path exists Source: https://docs.mirage.strukto.ai/api/operations/vfs/check-path-exists /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/exists Check whether a file or directory exists at the path. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Check path is directory Source: https://docs.mirage.strukto.ai/api/operations/vfs/check-path-is-directory /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/is_dir Check whether the path identifies a directory. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Check path is file Source: https://docs.mirage.strukto.ai/api/operations/vfs/check-path-is-file /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/is_file Check whether the path identifies a file. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Create directory Source: https://docs.mirage.strukto.ai/api/operations/vfs/create-directory /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/mkdir Create a directory at the path. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Create empty file Source: https://docs.mirage.strukto.ai/api/operations/vfs/create-empty-file /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/create Create an empty file at the path. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Create symbolic link Source: https://docs.mirage.strukto.ai/api/operations/vfs/create-symbolic-link /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/symlink Create a symbolic link at the path. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Delete empty directory Source: https://docs.mirage.strukto.ai/api/operations/vfs/delete-empty-directory /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/rmdir Delete an empty directory. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Delete file Source: https://docs.mirage.strukto.ai/api/operations/vfs/delete-file /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/unlink Delete a file at the path. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Get extended attribute Source: https://docs.mirage.strukto.ai/api/operations/vfs/get-extended-attribute /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/getxattr Read the value of an extended attribute. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Get path metadata Source: https://docs.mirage.strukto.ai/api/operations/vfs/get-path-metadata /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/stat Get metadata for a file or directory. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # List directory entries Source: https://docs.mirage.strukto.ai/api/operations/vfs/list-directory-entries /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/readdir List entries in a directory. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # List extended attributes Source: https://docs.mirage.strukto.ai/api/operations/vfs/list-extended-attributes /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/listxattr List extended attribute names for a path. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # List file names Source: https://docs.mirage.strukto.ai/api/operations/vfs/list-file-names /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/list_files List file names in a directory. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Read file Source: https://docs.mirage.strukto.ai/api/operations/vfs/read-file /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/read Read file bytes, optionally starting at an offset. Set `stream=true` to receive raw bytes instead of JSON. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Read symbolic link Source: https://docs.mirage.strukto.ai/api/operations/vfs/read-symbolic-link /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/readlink Read the target path of a symbolic link. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Remove extended attribute Source: https://docs.mirage.strukto.ai/api/operations/vfs/remove-extended-attribute /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/removexattr Remove an extended attribute. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Rename path Source: https://docs.mirage.strukto.ai/api/operations/vfs/rename-path /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/rename Rename a file or directory within the same mount. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Resize file Source: https://docs.mirage.strukto.ai/api/operations/vfs/resize-file /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/truncate Resize a file to the specified byte length. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Set extended attribute Source: https://docs.mirage.strukto.ai/api/operations/vfs/set-extended-attribute /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/setxattr Set the value of an extended attribute. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Update path attributes Source: https://docs.mirage.strukto.ai/api/operations/vfs/update-path-attributes /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/setattr Update permissions, ownership, or timestamps for a file or directory. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Write at file offset Source: https://docs.mirage.strukto.ai/api/operations/vfs/write-at-file-offset /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/pwrite Write bytes at the specified file offset. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Write file Source: https://docs.mirage.strukto.ai/api/operations/vfs/write-file /openapi.yaml post /v1/workspaces/{workspace_id}/vfs/write Replace file contents with the supplied bytes. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Cancel all commands Source: https://docs.mirage.strukto.ai/api/operations/workspaces/cancel-all-commands /openapi.yaml post /v1/workspaces/{workspace_id}/cancel Cancel all running and queued commands across every session. The workspace and sessions remain open. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Create workspace Source: https://docs.mirage.strukto.ai/api/operations/workspaces/create-workspace /openapi.yaml post /v1/workspaces Create a workspace from a configuration or saved template. Returns `201` when created, `200` for an identical retry with the same ID, or `409` if that ID has a different configuration. Set `explain=true` to check policies without creating anything. ```json 201 Created { "id": "demo", "status": "running", "created_at": 1794009600, "system_time": null, "sessions": [ { "session_id": "01a1b425-ec80-7038-86e0-75b597344043", "cwd": "/" } ], "mounts": [ { "prefix": "/", "vfs": "ram", "mode": "write", "description": "", "backend": "workspace", "mountpoint": null } ], "internals": null } ``` > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `409` | The identifier already exists with a different workspace configuration. | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `503` | The server cannot take the request now. It is at max\_workspaces (`server_full`), shutting down (`shutting_down`), or no worker can take the request (`unavailable`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Delete workspace Source: https://docs.mirage.strukto.ai/api/operations/workspaces/delete-workspace /openapi.yaml delete /v1/workspaces/{workspace_id} Stop the workspace and delete its saved state. Files in external storage are not deleted. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `409` | The request conflicts with the current state. The id or name is taken (`already_exists`), the workspace is busy on another server or starting or stopping (`workspace_busy`), the workspace is stopped (`workspace_stopped`), a file changed since it was read (`stale_write`), or the state allows no such change (`conflict`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `500` | The server failed internally (`internal`). The message is always `internal server error` and the cause goes to the server log. Check for side effects before retrying. | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Get workspace Source: https://docs.mirage.strukto.ai/api/operations/workspaces/get-workspace /openapi.yaml get /v1/workspaces/{workspace_id} Get workspace details, including mounts and sessions. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # List workspace logs Source: https://docs.mirage.strukto.ai/api/operations/workspaces/list-workspace-logs /openapi.yaml get /v1/workspaces/{workspace_id}/logs List completed commands with captured output and related file operations, newest first. Use `limit` and `after` for pagination, or `format=jsonl` to export all matching commands. Log retention depends on the server. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # List workspaces Source: https://docs.mirage.strukto.ai/api/operations/workspaces/list-workspaces /openapi.yaml get /v1/workspaces Running workspaces first, then stopped ones, which keep only their config and state until a start. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `401` | The token is missing or wrong (`unauthorized`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Set profile Source: https://docs.mirage.strukto.ai/api/operations/workspaces/set-profile /openapi.yaml put /v1/workspaces/{workspace_id}/profiles/{name} Create or replace a named permissions profile in the running workspace. Existing sessions keep their current permissions until explicitly updated. This does not change the saved workspace configuration. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Start workspace Source: https://docs.mirage.strukto.ai/api/operations/workspaces/start-workspace /openapi.yaml post /v1/workspaces/{workspace_id}/start Start the workspace using its saved configuration and retained state. The server checks policies and reloads credentials. If already running, return the existing workspace. RAM-backed files do not survive a stop/start cycle. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `403` | The call is refused. A policy refused it (`policy_refused`, with `decision`), a mount mode or permission refused it (`forbidden`), the backend is out of space or quota (`storage_full`), or the request came for a host or from a browser origin that is not allowed (`host_not_allowed`, `origin_not_allowed`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `409` | The request conflicts with the current state. The id or name is taken (`already_exists`), the workspace is busy on another server or starting or stopping (`workspace_busy`), the workspace is stopped (`workspace_stopped`), a file changed since it was read (`stale_write`), or the state allows no such change (`conflict`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > | `503` | The server cannot take the request now. It is at max\_workspaces (`server_full`), shutting down (`shutting_down`), or no worker can take the request (`unavailable`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Stop all background jobs Source: https://docs.mirage.strukto.ai/api/operations/workspaces/stop-all-background-jobs /openapi.yaml post /v1/workspaces/{workspace_id}/kill Stop background jobs and runtime processes across every session. The workspace and sessions remain open. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Stop workspace Source: https://docs.mirage.strukto.ai/api/operations/workspaces/stop-workspace /openapi.yaml post /v1/workspaces/{workspace_id}/stop Stop the workspace while keeping its saved state and configuration. Calling this again on a stopped workspace has no effect. RAM-backed files do not survive a stop/start cycle. Save them to persistent storage first. > [accordion] Errors > > | Status | Meaning | > | - | - | > | `400` | The request is malformed: the body is not JSON (`invalid_json`) or not a JSON object, a field is missing (`missing_field`), unknown (`unknown_field`) or has a wrong value (`invalid_value`), or the request is otherwise invalid (`invalid_request`). `param` names the field at fault. | > | `401` | The token is missing or wrong (`unauthorized`). | > | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). | > | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). | > > See [error examples and recovery steps](/api/errors). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema. # Overview Source: https://docs.mirage.strukto.ai/api/overview Access Mirage workspaces through the open-source HTTP server. The Mirage HTTP API creates workspaces, runs shell commands, and reads or writes files. Run the Python or TypeScript server on your own machine or infrastructure. Both implementations follow the same [OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml). ## Base URL A local server uses `http://127.0.0.1:8765` by default. Examples in this reference use that address. For a server on another machine, replace it with your server's base URL. Routes are under `/v1`. ## Make a request [Launch a server](/home/access/http#launch-a-server), then list its workspaces. Set `MIRAGE_AUTH_TOKEN` to the token configured on your server: ```bash theme={null} curl --request GET \ --url 'http://127.0.0.1:8765/v1/workspaces' \ --header "Authorization: Bearer $MIRAGE_AUTH_TOKEN" ``` Local mode without a configured token accepts requests without the authorization header. See [Authentication](/api/authentication) for token and JWT settings. ## Start here > [card] [Quickstart](/api/quickstart) > > Create a workspace and run a shell command. > [card] [API reference](/api/reference) > > Find an endpoint by resource, parameter, or response field. > [card] [HTTP](/home/access/http) > > Start a server and configure authentication and limits. > [card] [Errors](/api/errors) > > Handle HTTP failures and command exit codes. ## Resource groups **Workspaces** groups lifecycle operations, Shell, VFS, Agent Instructions, Approval requests, Commands, Jobs, Processes, and Machines. Each operation acts on a workspace. **Configuration** groups reusable templates, policies, and saved VFS, CLI, runtime, and machine configurations. **Server** groups Service health checks and Daemon readiness and shutdown operations. ## OpenAPI contract [`openapi.yaml`](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) defines the endpoints, request and response schemas, and examples shown in this reference. It retains every documented status code. The right pane shows successful response examples. Each endpoint's collapsed **Errors** section explains its documented failures. # Quickstart Source: https://docs.mirage.strukto.ai/api/quickstart Create a workspace and run your first shell command with the OSS Server API. First, [start a local server](/home/access/http#launch-a-server) and leave it running. The examples below use `http://127.0.0.1:8765`. In a second terminal, check that the server is reachable: ```bash theme={null} curl --fail --silent --show-error http://127.0.0.1:8765/v1/health ``` The response includes `"status": "ok"`. Set the same token you configured on the server in this terminal before sending authenticated requests: ```bash theme={null} export MIRAGE_AUTH_TOKEN='replace-with-your-token' ``` The requests below use `--fail-with-body`, available in curl 7.76.0 or newer. Check with `curl --version`. With an older curl, replace it with `--fail`; HTTP errors still exit nonzero, but their response bodies are omitted. Create a workspace with an in-memory mount: ```bash theme={null} curl --fail-with-body --request POST \ --url 'http://127.0.0.1:8765/v1/workspaces' \ --header "Authorization: Bearer $MIRAGE_AUTH_TOKEN" \ --header 'Content-Type: application/json' \ --data '{"id":"demo","config":{"mounts":{"/":{"vfs":"ram","mode":"write"}}}}' ``` A successful response has status `201` and includes the workspace ID `demo`. Supply either `config` or a saved `template`. An identical retry can return `200`; an existing ID with a different configuration returns `409`. Run a shell command: ```bash theme={null} curl --fail-with-body --request POST \ --url 'http://127.0.0.1:8765/v1/workspaces/demo/shell' \ --header "Authorization: Bearer $MIRAGE_AUTH_TOKEN" \ --header 'Content-Type: application/json' \ --data '{"command":"echo hello"}' ``` The response contains the output and command exit status: ```json theme={null} {"exit_code":0,"stdout":"hello\n","stderr":"","decision":null,"line_id":"line_019a5e2c-7b41-7c3e-9f20-4d8e1a6b5c37"} ``` Read workspace command logs: ```bash theme={null} curl --fail-with-body --request GET \ --url 'http://127.0.0.1:8765/v1/workspaces/demo/logs?limit=50' \ --header "Authorization: Bearer $MIRAGE_AUTH_TOKEN" ``` Logs return an object with `items` and `next`. Follow `next` using the `after` query parameter for another page. See [List workspace logs](/api/operations/workspaces/list-workspace-logs) for the fields and a complete response example. Browse the resource groups on the left or use [endpoint search](/api/reference). # API reference Source: https://docs.mirage.strukto.ai/api/reference Find endpoints by resource, path, parameter, or response field. Browse the resource groups in the sidebar, or search the operations below. Each endpoint includes request fields, response schemas, and examples from the [OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml). GET List workspaces /v1/workspaces Workspaces / Lifecycle [Open](/api/operations/workspaces/list-workspaces) POST Create workspace /v1/workspaces Workspaces / Lifecycle [Open](/api/operations/workspaces/create-workspace) GET Get workspace /v1/workspaces/\{workspace\_id} Workspaces / Lifecycle [Open](/api/operations/workspaces/get-workspace) DELETE Delete workspace /v1/workspaces/\{workspace\_id} Workspaces / Lifecycle [Open](/api/operations/workspaces/delete-workspace) POST Cancel all commands /v1/workspaces/\{workspace\_id}/cancel Workspaces / Lifecycle [Open](/api/operations/workspaces/cancel-all-commands) POST Stop all background jobs /v1/workspaces/\{workspace\_id}/kill Workspaces / Lifecycle [Open](/api/operations/workspaces/stop-all-background-jobs) GET List workspace logs /v1/workspaces/\{workspace\_id}/logs Workspaces / Lifecycle [Open](/api/operations/workspaces/list-workspace-logs) PUT Set profile /v1/workspaces/\{workspace\_id}/profiles/\{name} Workspaces / Lifecycle [Open](/api/operations/workspaces/set-profile) POST Start workspace /v1/workspaces/\{workspace\_id}/start Workspaces / Lifecycle [Open](/api/operations/workspaces/start-workspace) POST Stop workspace /v1/workspaces/\{workspace\_id}/stop Workspaces / Lifecycle [Open](/api/operations/workspaces/stop-workspace) POST Run shell command /v1/workspaces/\{workspace\_id}/shell Workspaces / Shell [Open](/api/operations/shell/run-shell-command) POST Append to file /v1/workspaces/\{workspace\_id}/vfs/append Workspaces / VFS [Open](/api/operations/vfs/append-to-file) POST Create empty file /v1/workspaces/\{workspace\_id}/vfs/create Workspaces / VFS [Open](/api/operations/vfs/create-empty-file) POST Check path exists /v1/workspaces/\{workspace\_id}/vfs/exists Workspaces / VFS [Open](/api/operations/vfs/check-path-exists) POST Get extended attribute /v1/workspaces/\{workspace\_id}/vfs/getxattr Workspaces / VFS [Open](/api/operations/vfs/get-extended-attribute) POST Check path is directory /v1/workspaces/\{workspace\_id}/vfs/is\_dir Workspaces / VFS [Open](/api/operations/vfs/check-path-is-directory) POST Check path is file /v1/workspaces/\{workspace\_id}/vfs/is\_file Workspaces / VFS [Open](/api/operations/vfs/check-path-is-file) POST List file names /v1/workspaces/\{workspace\_id}/vfs/list\_files Workspaces / VFS [Open](/api/operations/vfs/list-file-names) POST List extended attributes /v1/workspaces/\{workspace\_id}/vfs/listxattr Workspaces / VFS [Open](/api/operations/vfs/list-extended-attributes) POST Create directory /v1/workspaces/\{workspace\_id}/vfs/mkdir Workspaces / VFS [Open](/api/operations/vfs/create-directory) POST Write at file offset /v1/workspaces/\{workspace\_id}/vfs/pwrite Workspaces / VFS [Open](/api/operations/vfs/write-at-file-offset) POST Read file /v1/workspaces/\{workspace\_id}/vfs/read Workspaces / VFS [Open](/api/operations/vfs/read-file) POST List directory entries /v1/workspaces/\{workspace\_id}/vfs/readdir Workspaces / VFS [Open](/api/operations/vfs/list-directory-entries) POST Read symbolic link /v1/workspaces/\{workspace\_id}/vfs/readlink Workspaces / VFS [Open](/api/operations/vfs/read-symbolic-link) POST Remove extended attribute /v1/workspaces/\{workspace\_id}/vfs/removexattr Workspaces / VFS [Open](/api/operations/vfs/remove-extended-attribute) POST Rename path /v1/workspaces/\{workspace\_id}/vfs/rename Workspaces / VFS [Open](/api/operations/vfs/rename-path) POST Delete empty directory /v1/workspaces/\{workspace\_id}/vfs/rmdir Workspaces / VFS [Open](/api/operations/vfs/delete-empty-directory) POST Update path attributes /v1/workspaces/\{workspace\_id}/vfs/setattr Workspaces / VFS [Open](/api/operations/vfs/update-path-attributes) POST Set extended attribute /v1/workspaces/\{workspace\_id}/vfs/setxattr Workspaces / VFS [Open](/api/operations/vfs/set-extended-attribute) POST Get path metadata /v1/workspaces/\{workspace\_id}/vfs/stat Workspaces / VFS [Open](/api/operations/vfs/get-path-metadata) POST Create symbolic link /v1/workspaces/\{workspace\_id}/vfs/symlink Workspaces / VFS [Open](/api/operations/vfs/create-symbolic-link) POST Resize file /v1/workspaces/\{workspace\_id}/vfs/truncate Workspaces / VFS [Open](/api/operations/vfs/resize-file) POST Delete file /v1/workspaces/\{workspace\_id}/vfs/unlink Workspaces / VFS [Open](/api/operations/vfs/delete-file) POST Write file /v1/workspaces/\{workspace\_id}/vfs/write Workspaces / VFS [Open](/api/operations/vfs/write-file) POST Call VFS function /v1/workspaces/\{workspace\_id}/vfs/\{name} Workspaces / VFS [Open](/api/operations/vfs/call-vfs-function) GET Read SKILL.md /v1/workspaces/\{workspace\_id}/skill-md Workspaces / Agent Instructions [Open](/api/operations/documents/read-skillmd) PUT Write SKILL.md /v1/workspaces/\{workspace\_id}/skill-md Workspaces / Agent Instructions [Open](/api/operations/documents/write-skillmd) GET Read VFS.md /v1/workspaces/\{workspace\_id}/vfs-md Workspaces / Agent Instructions [Open](/api/operations/documents/read-vfsmd) PUT Write VFS.md /v1/workspaces/\{workspace\_id}/vfs-md Workspaces / Agent Instructions [Open](/api/operations/documents/write-vfsmd) GET List templates /v1/templates Configuration / Templates [Open](/api/operations/templates/list-templates) POST Create template /v1/templates Configuration / Templates [Open](/api/operations/templates/create-template) GET Get template /v1/templates/\{ref} Configuration / Templates [Open](/api/operations/templates/get-template) DELETE Delete template /v1/templates/\{ref} Configuration / Templates [Open](/api/operations/templates/delete-template) POST Restore template /v1/templates/\{ref}/restore Configuration / Templates [Open](/api/operations/templates/restore-template) GET List VFS /v1/vfs Configuration / VFS [Open](/api/operations/saved-vfs/list-vfs) POST Create VFS /v1/vfs Configuration / VFS [Open](/api/operations/saved-vfs/create-vfs) GET List VFS types /v1/vfs/types Configuration / VFS [Open](/api/operations/saved-vfs/list-vfs-types) GET Get VFS /v1/vfs/\{ref} Configuration / VFS [Open](/api/operations/saved-vfs/get-vfs) PUT Update VFS /v1/vfs/\{ref} Configuration / VFS [Open](/api/operations/saved-vfs/update-vfs) DELETE Delete VFS /v1/vfs/\{ref} Configuration / VFS [Open](/api/operations/saved-vfs/delete-vfs) GET List CLIs /v1/clis Configuration / CLI [Open](/api/operations/saved-clis/list-clis) POST Create CLI /v1/clis Configuration / CLI [Open](/api/operations/saved-clis/create-cli) GET List CLI types /v1/clis/types Configuration / CLI [Open](/api/operations/saved-clis/list-cli-types) GET Get CLI /v1/clis/\{ref} Configuration / CLI [Open](/api/operations/saved-clis/get-cli) PUT Update CLI /v1/clis/\{ref} Configuration / CLI [Open](/api/operations/saved-clis/update-cli) DELETE Delete CLI /v1/clis/\{ref} Configuration / CLI [Open](/api/operations/saved-clis/delete-cli) GET List runtimes /v1/runtimes Configuration / Runtime [Open](/api/operations/saved-runtimes/list-runtimes) POST Create runtime /v1/runtimes Configuration / Runtime [Open](/api/operations/saved-runtimes/create-runtime) GET List runtime types /v1/runtimes/types Configuration / Runtime [Open](/api/operations/saved-runtimes/list-runtime-types) GET Get runtime /v1/runtimes/\{ref} Configuration / Runtime [Open](/api/operations/saved-runtimes/get-runtime) PUT Update runtime /v1/runtimes/\{ref} Configuration / Runtime [Open](/api/operations/saved-runtimes/update-runtime) DELETE Delete runtime /v1/runtimes/\{ref} Configuration / Runtime [Open](/api/operations/saved-runtimes/delete-runtime) GET List machines /v1/machines Configuration / Machine [Open](/api/operations/saved-machines/list-machines) POST Create machine /v1/machines Configuration / Machine [Open](/api/operations/saved-machines/create-machine) GET List machine types /v1/machines/types Configuration / Machine [Open](/api/operations/saved-machines/list-machine-types) GET Get machine /v1/machines/\{ref} Configuration / Machine [Open](/api/operations/saved-machines/get-machine) PUT Update machine /v1/machines/\{ref} Configuration / Machine [Open](/api/operations/saved-machines/update-machine) DELETE Delete machine /v1/machines/\{ref} Configuration / Machine [Open](/api/operations/saved-machines/delete-machine) GET List policies /v1/policies Configuration / Policies [Open](/api/operations/policies/list-policies) POST Create policy /v1/policies Configuration / Policies [Open](/api/operations/policies/create-policy) GET Get policy /v1/policies/\{ref} Configuration / Policies [Open](/api/operations/policies/get-policy) PUT Update policy /v1/policies/\{ref} Configuration / Policies [Open](/api/operations/policies/update-policy) DELETE Delete policy /v1/policies/\{ref} Configuration / Policies [Open](/api/operations/policies/delete-policy) GET List asks /v1/workspaces/\{workspace\_id}/asks Workspaces / Approval requests [Open](/api/operations/asks/list-asks) POST Respond to ask /v1/workspaces/\{workspace\_id}/asks/\{ask\_id} Workspaces / Approval requests [Open](/api/operations/asks/respond-to-ask) GET List commands /v1/workspaces/\{workspace\_id}/lines Workspaces / Commands [Open](/api/operations/lines/list-commands) GET Get command /v1/workspaces/\{workspace\_id}/lines/\{line\_id} Workspaces / Commands [Open](/api/operations/lines/get-command) POST Write stdin /v1/workspaces/\{workspace\_id}/lines/\{line\_id}/stdin Workspaces / Commands [Open](/api/operations/lines/write-stdin) DELETE Close stdin /v1/workspaces/\{workspace\_id}/lines/\{line\_id}/stdin Workspaces / Commands [Open](/api/operations/lines/close-stdin) GET List jobs /v1/workspaces/\{workspace\_id}/jobs Workspaces / Jobs [Open](/api/operations/jobs/list-jobs) GET Get job /v1/workspaces/\{workspace\_id}/jobs/\{job\_id} Workspaces / Jobs [Open](/api/operations/jobs/get-job) GET List processes /v1/workspaces/\{workspace\_id}/processes Workspaces / Processes [Open](/api/operations/processes/list-processes) GET Get process /v1/workspaces/\{workspace\_id}/processes/\{pid} Workspaces / Processes [Open](/api/operations/processes/get-process) GET List machines /v1/workspaces/\{workspace\_id}/machines Workspaces / Machines [Open](/api/operations/machines/list-machines) GET Get machine /v1/workspaces/\{workspace\_id}/machines/\{machine\_id} Workspaces / Machines [Open](/api/operations/machines/get-machine) GET Check health /v1/health Server / Service [Open](/api/operations/service/check-health) GET Check readiness /v1/daemon/ready Server / Daemon [Open](/api/operations/daemon/check-readiness) POST Shut down server /v1/daemon/shutdown Server / Daemon [Open](/api/operations/daemon/shut-down-server) # Streaming and stdin Source: https://docs.mirage.strukto.ai/api/streaming Stream shell output and send input over HTTP. Use [Run shell command](/api/operations/shell/run-shell-command) with an existing workspace. Set `MIRAGE_AUTH_TOKEN` to your server's configured token, or omit the authorization header in local mode without a token. ## Stream command output The server supports streaming shell output. Set `stream=true` and use `curl --no-buffer` to display the response as it arrives: ```bash theme={null} curl --no-buffer --request POST \ --url 'http://127.0.0.1:8765/v1/workspaces/demo/shell?stream=true' \ --header "Authorization: Bearer $MIRAGE_AUTH_TOKEN" \ --header 'Content-Type: application/json' \ --data '{"command":"echo hello"}' ``` The response has content type `application/x-ndjson`. Each line is a JSON record. Output records identify `stdout` or `stderr` and carry base64-encoded `data`: ```json theme={null} {"stream":"stdout","data":"aGVsbG8K"} {"status":"done","result":{"exit_code":0,"stdout":"","stderr":"","decision":null,"line_id":"line_019a5e2c-7b41-7c3e-9f20-4d8e1a6b5c37"},"error":null} ``` Decode each output record's `data` to display the bytes. The output example decodes to `hello\n` on stdout. Records labeled `stderr` carry stderr bytes in the same format. Read through the final record: | Field | Meaning | | - | - | | `status` | `done`, `failed`, or `canceled`. | | `result` | The shell result when available. Check `exit_code` to determine whether the command succeeded. | | `error` | A request or execution error when available. | A stream without a final status record was interrupted. HTTP `200` alone does not mean the shell command succeeded. Closing the request cancels the running line. Streaming cannot be combined with `explain`. The server includes `line_id` in the result. Use it to [get the line record](/api/operations/lines/get-command). ## Send stdin The server accepts `multipart/form-data` with a JSON `request` part followed by a `stdin` part. It accepts up to 64 MiB of input and supplies the bytes to the command as they arrive. ```bash cURL theme={null} printf 'b\na\n' | curl 'http://127.0.0.1:8765/v1/workspaces/demo/shell' \ --header "Authorization: Bearer $MIRAGE_AUTH_TOKEN" \ --form 'request={"command":"sort"};type=application/json' \ --form 'stdin=@-' ``` ```python Python theme={null} import json import os import httpx headers = {"Authorization": f"Bearer {os.environ['MIRAGE_AUTH_TOKEN']}"} with httpx.Client(base_url="http://127.0.0.1:8765/v1", headers=headers) as client: response = client.post("/workspaces/demo/shell", files={ "request": (None, json.dumps({"command": "sort"}), "application/json"), "stdin": ("stdin", b"b\na\n"), }) response.raise_for_status() print(response.json()["stdout"], end="") ``` ```typescript TypeScript theme={null} const form = new FormData() form.append('request', new Blob([JSON.stringify({ command: 'sort' })], { type: 'application/json' })) form.append('stdin', new Blob(['b\na\n'])) const response = await fetch('http://127.0.0.1:8765/v1/workspaces/demo/shell', { method: 'POST', headers: { Authorization: `Bearer ${process.env.MIRAGE_AUTH_TOKEN}` }, body: form, }) if (!response.ok) throw new Error(`HTTP ${response.status}`) const result = await response.json() process.stdout.write(result.stdout) ``` The command sorts the input and returns `a\nb\n` in `stdout`. ## Write to a running command A `stdin` part is one upload. To keep sending input after the line starts, from any request, set `open_stdin` and `stream=true`. The first record names the line: ```bash theme={null} curl --no-buffer --request POST \ --url 'http://127.0.0.1:8765/v1/workspaces/demo/shell?stream=true' \ --header "Authorization: Bearer $MIRAGE_AUTH_TOKEN" \ --header 'Content-Type: application/json' \ --data '{"command":"cat","open_stdin":true}' ``` ```json theme={null} {"line_id":"line_019a5e2c-7b41-7c3e-9f20-4d8e1a6b5c37"} ``` Output keeps arriving on this response. From another request, [write stdin](/api/operations/lines/write-stdin): ```bash theme={null} curl --request POST \ --url 'http://127.0.0.1:8765/v1/workspaces/demo/lines/line_019a5e2c-7b41-7c3e-9f20-4d8e1a6b5c37/stdin' \ --header "Authorization: Bearer $MIRAGE_AUTH_TOKEN" \ --header 'Content-Type: application/octet-stream' \ --data-binary $'hello\n' ``` Then [close its stdin](/api/operations/lines/close-stdin) to send end of file: ```bash theme={null} curl --request DELETE \ --url 'http://127.0.0.1:8765/v1/workspaces/demo/lines/line_019a5e2c-7b41-7c3e-9f20-4d8e1a6b5c37/stdin' \ --header "Authorization: Bearer $MIRAGE_AUTH_TOKEN" ``` | Status | Meaning | | - | - | | `204` | The bytes are buffered, or stdin is closed. | | `404` | That line is not running in this workspace. | | `409` | Its stdin is not open: the line did not set `open_stdin`, stdin was closed, or the command stopped reading. | A write waits while the buffer is full, so a command that reads slowly holds its writer back. Send one write at a time and wait for its answer, to keep the bytes in order. Total input has no limit. `open_stdin` needs `stream=true` and takes no `stdin` part. Closing the streaming request cancels the line. See [Run shell command](/api/operations/shell/run-shell-command) for the complete request fields and response schemas. # CLI Source: https://docs.mirage.strukto.ai/home/access/cli Every mirage command, the same in the Python and TypeScript packages. `mirage` is a client of the server's [HTTP routes](/home/access/http), with the same commands in Python and TypeScript. When its `url` is on this machine, `workspace create`, `workspace load`, `mcp`, `rpc`, `ssh-proxy` and `codex-exec` start the server if it is not running; other commands need it running. A remote server is never started. ## Install > [tab] script > > ```bash theme={null} > curl -fsSL https://strukto.ai/mirage/install.sh | sh > ``` > [tab] pip > > ```bash theme={null} > pip install mirage-ai > ``` > [tab] uv > > ```bash theme={null} > uv tool install mirage-ai > ``` > [tab] npm > > ```bash theme={null} > npm install -g @struktoai/mirage-cli > ``` ## Quickstart Create a RAM-backed workspace that needs no credentials: ```bash theme={null} cat > workspace.yaml <<'EOF' mounts: /data: vfs: ram mode: write EOF mirage workspace create workspace.yaml --id demo mirage shell -w demo -c 'echo "hello mirage" > /data/hello.txt && grep -n hello /data/hello.txt' ``` This prints `1:hello mirage`. Keep `demo` for the [MCP](/home/access/mcp) or [RPC](/home/access/rpc) examples, then remove it with `mirage workspace delete demo`. See [Workspace configuration](/home/configuration) for YAML settings and defaults. ## Write a config A config is a YAML file listing what the workspace mounts. Each key under `mounts` is a path in the workspace: `vfs` names the backend, and `config` holds the fields its [VFS guide](/home/setup/vfs) lists. ```yaml workspace.yaml theme={null} mode: read mounts: /data: vfs: s3 config: bucket: my-bucket region: us-east-1 aws_access_key_id: ${AWS_ACCESS_KEY_ID} aws_secret_access_key: ${AWS_SECRET_ACCESS_KEY} /repo: vfs: github config: token: ${GITHUB_TOKEN} owner: strukto-ai repo: mirage command_limits: "@all": walk_limit: 2000 /scratch: vfs: ram mode: write ``` * `mode: read` makes every mount read-only unless it sets its own `mode`, as `/scratch` does. * `${NAME}` is read from the environment when the config loads, so keys stay out of the file. A missing variable is an error. * `command_limits` bounds the commands that run on that mount; its `"@all"` entry's `walk_limit` is the most files one command walks there. ```bash theme={null} mirage workspace create workspace.yaml --id work mirage shell -w work -c 'ls /repo && echo draft > /scratch/notes.txt' ``` `clis`, `runtimes`, `profiles` and the other top-level keys are in [Workspace configuration](/home/configuration). ## Exit codes | Code | Means | | - | - | | `0` | Success. | | `1` | A tool failed, a VFS call was refused or failed, or the server could not be reached. | | `2` | A usage error, a bad config, or a refusal from the server. | | `130` | The line was interrupted with Ctrl-C, or a streamed `shell` line was canceled. | | `141` | `shell` output went to a pipe that closed, as with `\| head`. | | `N` | `shell` exits with the line's own status. | ## Run lines, VFS calls and tools | Command | Does | | - | - | | `mirage workspace shell -c LINE` | Run a line, streaming its stdout and stderr. | | `mirage workspace vfs CALL ARGS` | Make one of the 23 [VFS calls](/api/reference). | | `mirage workspace tools TOOL ARGS` | Run one of the [agent tools](/home/access/mcp#tools). | The workspace is `-w`, else `MIRAGE_WORKSPACE`, else the current one that `mirage workspace use ID` set for the [context](#log-in). With none, the command exits 2. Each takes `-s SESSION`, the default session when absent. `shell` and `vfs` take `--explain`, which says what the line or call would do and runs nothing; see [Explain](/home/policy/explain). `mirage shell` is a short form of `mirage workspace shell`, with the same options. ### `mirage workspace shell` | Option | Does | | - | - | | `--cwd PATH` | Run the line in this directory. | | `--runtime NAME` | Run its programs on this [runtime](/home/setup/runtime/overview). | | `--machine NAME` | Run its programs on this [machine](/home/setup/machine/overview). | | `--no-record` | Keep the line out of the session's [history](/home/infrastructure/history). | | `--json` | Print one `{exit_code, stdout, stderr, decision}` result instead of streaming. | * Output streams as raw bytes as it arrives, and piped stdin streams in, so a line can answer before its input ends. * The CLI exits with the line's code. Ctrl-C cancels the line. * `--json` decodes stdout and stderr as UTF-8, replacing invalid bytes. ```bash theme={null} mirage shell -w demo -c 'cat /data/archive.gz' > archive.gz cat events.txt | mirage shell -w demo -c 'head -n 10' mirage shell -w demo -c 'ls /data' --json | jq .stdout ``` ### `mirage-bash` `mirage-bash -c LINE` runs a line as `mirage workspace shell`, for a coding agent that takes a shell path, such as [Claude Code](/home/agents/claude-code#shell). Both packages install it beside `mirage`. | Variable | Does | | - | - | | `MIRAGE_WORKSPACE` | The workspace the line runs in. Required. | | `MIRAGE_SESSION` | The session it runs as; the default session when unset. | * The line runs in the process's working directory, which must be a path in the workspace. * It takes only `-c LINE`; other bash options are read and dropped. * It exits with the line's code, and with `2` when the arguments or `MIRAGE_WORKSPACE` are missing. ```bash theme={null} MIRAGE_WORKSPACE=demo mirage-bash -c 'ls /data | wc -l' ``` ### `mirage workspace vfs` * Calls are spelled with dashes: `mirage workspace vfs is-dir /data -w demo`. * Required arguments come in order, the rest as `--name VALUE`. * Bytes come from `--data` or `--value`, else from stdin. * `read` prints the file's bytes as they arrive, so binary files and large files pass through whole. `--json` prints the JSON answer, with the bytes in base64. * Other calls print their JSON when piped. In a terminal, a list prints one entry per line. A call that returns nothing prints nothing. ```bash theme={null} echo "hello" | mirage workspace vfs write /data/hi.txt -w demo mirage workspace vfs read /data/hi.txt -w demo mirage workspace vfs read /data/img.png -w demo > img.png ``` ### Relays | Command | Does | | - | - | | `mirage mcp [CONFIG] [-w ID] [-s S] [--all-calls]` | Serve a session's [MCP](/home/access/mcp) tools on stdio. `--all-calls` adds the [VFS calls](/home/access/mcp#vfs-calls). | | `mirage rpc [CONFIG] [-w ID] [-s S]` | Serve [RPC](/home/access/rpc) on stdio. | | `mirage ssh-proxy ID` | Carry [SSH](/home/access/ssh#over-https) to workspace `ID` over the server's HTTPS port, for ssh's `ProxyCommand`. | | `mirage codex-exec ID [--listen HOST:PORT]` | Serve workspace `ID` on a local port to [`codex exec-server forward`](/home/agents/codex#exec-server-forward). | With `-w`, `mcp` and `rpc` serve a workspace the server already holds. Without it, they create one from `CONFIG`, then `MIRAGE_MCP_CONFIG` (`MIRAGE_RPC_CONFIG`) or `MIRAGE_CONFIG`, then a `workspace.yaml` found walking up from the working directory. They delete it when the client disconnects, unless the config names a `workspace_id`. ## Workspaces | Command | Does | | - | - | | `mirage workspace create CONFIG [-w ID]` | Create a workspace from a YAML or JSON config. `--id` is another name for `-w`. | | `mirage workspace create --template NAME [-w ID]` | Create a workspace from a saved [template](#from-a-template). | | `mirage workspace create CONFIG --explain` | Show what the [server policies](/home/access/http#server-policies) say of the config, and create nothing. | | `mirage workspace list` | List workspaces, running and stopped, with the status of each. | | `mirage workspace use ID` | Make it the current workspace of the [context](#log-in). | | `mirage workspace get ID [--verbose]` | Show its status, mounts and sessions. A stopped workspace shows the mounts its config names and no sessions. | | `mirage workspace delete ID` | Delete a workspace, running or stopped, with its state and config. | | `mirage workspace stop ID` | Stop a workspace and keep its state and config. A `ram` mount, and the sessions on a `ram` store, come back empty. Stopping a stopped workspace does nothing. | | `mirage workspace start ID` | Start a stopped workspace again from the config it was created with. Starting a running workspace does nothing. | | `mirage workspace set-profile ID NAME FILE` | Add a [profile](/home/policy/overview) from a YAML or JSON file, or replace what `NAME` means. Sessions keep their rules until `session update` moves them, and the workspace's config is not rewritten. | | `mirage workspace logs [-w ID] [-s S] [--limit N] [--after CURSOR] [--jsonl]` | Show completed commands newest first, with cursor pagination. `--jsonl` exports all retained matching commands oldest first. | | `mirage workspace clone SRC [--id ID]` | Copy a workspace. | | `mirage workspace snapshot ID FILE.tar` | Save it to a tar here: the server sends the tar back, on this machine or another. | | `mirage workspace snapshot ID --key KEY` | Save it to the server's snapshot store instead. | | `mirage workspace load FILE.tar [CONFIG] [--id ID]` | Restore a tar from here, uploading it. `CONFIG` gives back the credentials the snapshot left out. | | `mirage workspace load --key KEY [CONFIG] [--id ID]` | Restore one from the server's snapshot store. | | `mirage workspace vfs-md ID [--session S] [--path PATH] [--profile P]` | Print the VFS.md, or expose it as a live file at `PATH`. | | `mirage workspace skill-md ID [--session S] [--path PATH] [--profile P]` | The same for SKILL.md. | ### From a template A template is a saved workspace config. `-f` takes a workspace config, or a file with `name`, an optional `description`, and `config`, as `mirage template get ID -o yaml` prints one: ```bash theme={null} mirage template create ram-only -f workspace.yaml --description "One RAM mount" mirage workspace create --template ram-only -w demo ``` | Command | Does | | - | - | | `mirage template create NAME -f FILE [--description TEXT]` | Save a config as a template. | | `mirage template list` | List templates. | | `mirage template get ID [-o yaml]` | Print one; `-o yaml` is a file `create -f` reads back. | | `mirage template delete ID` | Delete one. | | `mirage template restore ID` | Bring a deleted one back. | The file is saved as written: `${NAME}` is not read from the environment. The server checks the config when it saves the template, as a create would. A workspace gets a copy of the template's config, so a later change to the template leaves it as it is, and a template's config cannot set `workspace_id`: `-w` names the workspace. Give a config file or `--template`, not both. The local daemon keeps templates under `~/.mirage/resources`, as `resource_store` sets. `get`, `delete` and `restore` take the template's ID or its name: a name is unique, so it works as an ID. On the local daemon a template's ID is its name. ### Saved policies `mirage policy` keeps Python programs by name on the daemon, or on the hosted API, through the [`/v1/policies`](/api/operations/policies/list-policies) routes. A name ends in `.py`. `--source @FILE` reads a file; any other value is the program itself. `get`, `update` and `delete` take the policy's ID or its name, which works as an ID; on the local daemon the two are the same. | Command | Does | | - | - | | `mirage policy create NAME --source @FILE\|TEXT` | Save a new policy. A name already saved exits 2. | | `mirage policy list` | List the saved names. | | `mirage policy get ID [-o yaml]` | Show one; in a terminal, its source. | | `mirage policy update ID --source @FILE\|TEXT` | Replace its source. | | `mirage policy delete ID` | Delete it. | ```bash theme={null} mirage policy create guard.py --source @guard.py mirage policy get guard.py -o yaml ``` A profile program's `script: guard.py` names the saved policy, on the daemon as on the hosted API; `template create` and `workspace create` send the name as written. The daemon reads the policy's source when it creates or starts the workspace. A path such as `./guard.py` is a file next to the config, and a name the daemon has no saved policy for is read as a file too. ### Asks | Command | Does | | - | - | | `mirage workspace list-asks [-w ID] [-s S] [--all]` | List pending [asks](/home/policy/policies#asks). | | `mirage workspace allow ID ASK [--scope once\|session]` | Allow one. | | `mirage workspace deny ID ASK` | Deny one. | ### Lines, jobs and processes | Command | Does | | - | - | | `mirage workspace list-lines [-s S] [--state STATE]` | List the lines the workspace keeps. | | `mirage workspace list-jobs [-s S] [--state STATE] [--line LINE]` | List its jobs. | | `mirage workspace list-processes [-s S] [--state STATE] [--line LINE] [--job JOB] [--machine M]` | List its processes. | | `mirage workspace list-machines` | Check each [machine](/home/setup/machine/overview#machine-states) it runs programs on, and print its state. | Each takes `-w ID`, else the current workspace, as `shell` and `vfs` do. `-s` keeps only that session's records. ## Saved connections `mirage vfs`, `mirage cli`, `mirage runtime` and `mirage machine` keep connections on the server: a type, its settings and its credentials, saved once under a name. They are the [`/v1/vfs`, `/v1/clis`, `/v1/runtimes` and `/v1/machines`](/api/reference) routes, and work the same against the local daemon and the hosted API. `ID` is an entry's ID or its name: a name is unique, so it works as an ID. On the local daemon an entry's ID is its name. | Command | Does | | - | - | | `mirage vfs types [TYPE]` | List the types, with their required and secret fields; with `TYPE`, its fields. | | `mirage vfs create NAME --type TYPE [--set K=V] [--secret K] [-f FILE]` | Save a new entry. | | `mirage vfs list [--type TYPE] [-q TEXT]` | List the entries, by name, with how many saved templates use each. | | `mirage vfs get ID [-o yaml]` | Show an entry. A secret field shows as `(sealed)`, never its value. | | `mirage vfs update ID [--set K=V] [--secret K] [--unset K] [-f FILE]` | Change an entry. Fields not named keep their values. | | `mirage vfs delete ID` | Delete an entry and wipe its secrets. There is no restore. | `mirage cli`, `mirage runtime` and `mirage machine` take the same commands. ```bash theme={null} mirage vfs types github mirage vfs create github --type github --set owner=strukto-ai --set repo=mirage --secret token Token for github: ******** mirage vfs get github mirage vfs update github --secret token mirage vfs delete github ``` * `--set KEY=VALUE` sets a plain field and can be repeated. A value that starts with `{` or `[` is read as JSON. * `--secret KEY` reads a secret field from a hidden prompt, or from the next line of stdin when stdin is not a terminal. `--secret KEY=@FILE` reads a file, without its last newline. A secret value on the command line is refused, by `--secret KEY=VALUE` and by `--set` alike. * `--unset KEY` removes a field, plain or secret. * `-f FILE` reads the entry from YAML or JSON: `name`, `type`, `fields`, and `secrets`, a list of the secret fields to read as `--secret` reads them. The output of `get -o yaml` reads back too. * In a terminal, a missing required field is prompted for. Otherwise the command exits `2` and names every missing field. * Piped, every command prints JSON. `-o yaml` on `get` prints a file that `create -f` and `update -f` read back. ```yaml github.yaml theme={null} name: github type: github fields: owner: strukto-ai repo: mirage secrets: [token] ``` ```bash theme={null} mirage vfs create -f github.yaml < token.txt ``` `update` keeps a secret field you leave out, so `--secret token` rotates a token while the entry stays in use. `delete` is refused while a saved template uses the entry. The local daemon keeps entries under `~/.mirage/resources`, their secrets in a separate file only you can read. ### Use a saved connection A workspace config or a template names a saved field with `{from: strukto, ref: NAME, key: FIELD}`, where it would write the value: ```yaml workspace.yaml theme={null} mounts: /github: vfs: github config: owner: {from: strukto, ref: github, key: owner} repo: {from: strukto, ref: github, key: repo} token: {from: strukto, ref: github, key: token} ``` The server fills each pointer in when it creates or starts the workspace, so a later `update` reaches the next start. A workspace built in your own code cannot read `from: strukto`. ## Sessions | Command | Does | | - | - | | `mirage workspace session create [-s S] [-p PROFILE] [-m /prefix:mode]...` | Add a session under a [profile](/home/policy/overview), with mounts narrowed to `r`, `rw` or `rwx`. | | `mirage workspace session list` | List sessions. | | `mirage workspace session delete -s S` | Close a session. | | `mirage workspace session cancel -s S` | Cancel the session's running lines. | | `mirage workspace session kill -s S` | Kill the session's background jobs. | | `mirage workspace session update -s S (-p PROFILE \| --profile-file FILE \| --default-profile)` | Replace the session's profile with a profile's current definition, a profile document, or the default; its cwd, env and history stay. | Each takes `-w ID`, else the current workspace, as `shell` and `vfs` do. ## Daemon The server the CLI starts. It exits 30 seconds after its last running workspace stops or is deleted, and logs to `~/.mirage/daemon.log`. | Command | Does | | - | - | | `mirage daemon status` | Show PID, uptime and workspace count. | | `mirage daemon stop` | Stop its workspaces and exit. They stay stopped until `mirage workspace start`. | | `mirage daemon restart [--eager]` | Stop it; the next command, or `--eager`, starts a new one. Its workspaces stay stopped until `mirage workspace start`. | | `mirage daemon kill` | Kill it. A last resort. | ## Log in A context is a server the CLI talks to, with its login, team and current workspace. `local` is the daemon on this machine, which needs no login and is always there. `mirage login` adds a context and makes it current: ```bash theme={null} mirage login # the hosted API, context "strukto" mirage login https://mirage.example.com # context "mirage.example.com" mirage login https://dev.example.com --name dev mirage context use local ``` | Command | Does | | - | - | | `mirage login [URL] [--name NAME] [--token TOKEN]` | Log in to `URL`, `https://api.strukto.ai` when left out, and make its context current. The context is `--name`, else `strukto` for the hosted API, `local` for this machine, else the server's host. | | `mirage context list` | List the contexts; `*` marks the current one. | | `mirage context use NAME` | Make a context current. | | `mirage context delete NAME` | Forget a context and its login. `local` stays. | | `mirage whoami` | Show the context, its URL, team, user and workspace, and the date to log in again by. | | `mirage logout` | Forget the current context's login; the context stays. | `--context NAME` before a command, or `MIRAGE_CONTEXT=NAME`, runs one command in another context. `MIRAGE_DAEMON_URL` points any context at another URL. On a terminal, a command that changes something names its context first, as `strukto · team acme · created demo`. > [accordion] How login works > > * `mirage login` asks the server where to sign in, opens your browser there, > and waits. If you are already signed in, the browser comes straight back. > * The CLI keeps each context in `~/.mirage/contexts/NAME.json`, its > tokens in `~/.mirage/logins/NAME.json`, and the current context's name > in `~/.mirage/current_context`, all readable only by you. > * On a machine with no browser, `mirage login --token TOKEN` keeps a token > you paste once the server accepts it. `--token -` reads it from stdin, so > it stays out of your shell history. > * Every command sends the login's token, `ssh-proxy` and `codex-exec` > included, but only to the server it was made for. `MIRAGE_TOKEN` wins > over it, and so does `auth_token` in the `local` context. > * The token refreshes on its own; you log in again 30 days after you > signed in. > * A server that publishes no login, such as the one the CLI starts on your > machine, needs none, and `mirage login` says so. > [accordion] Set up login on a server > > A server publishes a login when it runs in [`jwt` mode](/home/access/http#jwt) > with an issuer and `MIRAGE_LOGIN_CLIENT_ID` set to an OAuth client that > `MIRAGE_JWT_AUDIENCE` lists: > > ```bash theme={null} > export MIRAGE_JWT_ISSUER=https://clerk.example.com > export MIRAGE_JWT_AUDIENCE=client_cli > export MIRAGE_LOGIN_CLIENT_ID=client_cli > ``` > > `mirage login` then reads the issuer and client from the server's > `/.well-known/oauth-protected-resource`, signs in through the browser, and > exchanges the code for tokens with PKCE. > > In Clerk, create an OAuth application with no client secret and PKCE > enabled. Add the redirect `http://127.0.0.1/callback` (the CLI picks a free > port), allow the `offline_access` scope for a refresh token, and turn the > consent screen off so a signed-in user comes straight back to the CLI. ## Call any route `mirage api` calls a route of the current context's server with the CLI's login or token, as `gh api` does, so a script needs no token of its own: ```bash theme={null} mirage api /v1/workspaces mirage api /v1/workspaces/demo/shell --command 'ls /data | wc -l' mirage api /v1/workspaces/demo/clone --id demo-2 \ --override '{"mounts": {"/data": {"vfs": "ram"}}}' mirage api /v1/workspaces --input workspace.json mirage api /v1/workspaces/demo -X DELETE ``` Every option after the route is a field, except these: | Flag | Does | | - | - | | `--input FILE` | The body, from a YAML or JSON file; `-` reads stdin. | | `-X METHOD` | The method: GET, or POST once there are fields or `--input`. | A field is `--key value` or `--key=value`. A value that starts with `{` or `[` is JSON, `@FILE` is the file's text (`@-` reads stdin), anything else is a string, and a bare `--flag` is `true`. Fields make a JSON body, or the query string of a GET. The answer prints as JSON, a 204 prints nothing, and an error exits 2 with its detail. `api` takes only a route, never a URL, so the token goes nowhere but its own server. ## Daemon config `mirage daemon config set|get|unset|list` edits `~/.mirage/config.toml`. An environment variable wins over the file. Changes apply on the next start. | Key | Env var | Default | | - | - | - | | `port` | `MIRAGE_DAEMON_PORT` | `8765`; the `local` context follows it | | `url` | `MIRAGE_DAEMON_URL` | `http://127.0.0.1:PORT`: the `local` context's URL; `mirage login URL` adds another server | | `auth_token` | `MIRAGE_TOKEN` | your [login](#log-in) for the `local` context, else `~/.mirage/auth_token` | | `auth_mode` | `MIRAGE_AUTH_MODE` | `local` | | `allowed_hosts` | `MIRAGE_ALLOWED_HOSTS` | `127.0.0.1,localhost,::1` | | `idle_grace_seconds` | `MIRAGE_IDLE_GRACE_SECONDS` | `30` | | `max_workspaces` | `MIRAGE_MAX_WORKSPACES` | no cap; past it a new workspace answers 503 | | `max_sessions` | `MIRAGE_MAX_SESSIONS` | `16`; past it a new session answers 429 | | `max_memory` | `MIRAGE_MAX_MEMORY` | none; the most any workspace's `max_memory` reaches, as a [size](/home/configuration#sizes) | | `max_processes` | `MIRAGE_MAX_PROCESSES` | none; the most any session's `processes.max` reaches | | `max_line_seconds` | `MIRAGE_MAX_LINE_SECONDS` | none; the most seconds any line runs | | `max_env` | `MIRAGE_MAX_ENV` | none; the most any workspace's `max_env` reaches, as a [size](/home/configuration#sizes) | | `workers` | `MIRAGE_WORKERS` | `1`; see [Workers](/typescript/access/server#workers) | | `worker_type` | `MIRAGE_WORKER_TYPE` | `thread` in TypeScript; in Python, `thread` without the GIL, else `process` | | `rate_limits` | `MIRAGE_RATE_LIMITS` | `ip=1000/minute`; see [Rate limits](/home/access/http#rate-limits) | | `forwarded_allow_ips` | `MIRAGE_FORWARDED_ALLOW_IPS` | none; the proxies whose `X-Forwarded-For` names the client | | `graceful_timeout` | `MIRAGE_GRACEFUL_TIMEOUT` | `0`; seconds running lines get to finish on shutdown | | `policy_file` | `MIRAGE_POLICY_FILE` | none; see [Server policies](/home/access/http#server-policies) | | `resource_store` | `MIRAGE_RESOURCE_STORE` | `files`, under `~/.mirage/resources`; `memory` keeps saved templates and connections only until the daemon stops, and does not combine with `workers` | | `ssh_*` | `MIRAGE_SSH_*` | see [SSH](/home/access/ssh#set-up) | | `jwt_*` | `MIRAGE_JWT_*` | see [Configure authentication](/home/access/http#configure-authentication) | | `login_client_id` | `MIRAGE_LOGIN_CLIENT_ID` | see [Log in](#log-in) | `jwt_clock_skew` is `MIRAGE_JWT_CLOCK_SKEW_SECONDS`, and `MIRAGE_JWT_PUBKEY` has no key: use `jwt_pubkey_file`. `MIRAGE_HOME` moves everything under `~/.mirage`. # Errors Source: https://docs.mirage.strukto.ai/home/access/errors What a failure looks like on each surface, from a file call's POSIX condition to a shell line's exit status. Mirage names a failure once and each surface reports it in its own form. A file call fails with a POSIX condition, a shell line ends with an exit status and a GNU-worded line on stderr, and HTTP, RPC, MCP and the kernel mounts carry one of those two. ## File calls A file call (`read`, `write`, `stat`, `readdir`, `rename`, ...) names its failure with one of these conditions, whatever the backend. A service's own error becomes the condition it means, such as an object that is not there becoming `ENOENT`. One that means none keeps its own words in an exception and in a shell diagnostic. HTTP returns status `500`, and RPC `-32603`, with code `internal`, message `internal server error` and no `errno`, since those words can carry credentials or host paths; they stay in the server's logs. | Condition | Message | HTTP | Means | | - | - | - | - | | `ENOENT` | No such file or directory | `404` | The path is not there, or no mount owns it. | | `ENOTDIR` | Not a directory | `400` | A component of the path is a file. | | `EISDIR` | Is a directory | `400` | The call needs a file. | | `EEXIST` | File exists | `409` | The name is taken. | | `ENOTEMPTY` | Directory not empty | `409` | `rmdir` on a directory with entries. | | `EACCES` | Permission denied | `403` | A policy refused the call, or the service denied access. | | `EPERM` | Operation not permitted | `403` | The call is not allowed on this entry. | | `EROFS` | Read-only file system | `403` | The mount's mode stops below write. | | `EXDEV` | Invalid cross-device link | `400` | A rename across two mounts. | | `ENOTSUP` | Operation not supported | `400` | The backend does not offer the call. | | `ELOOP` | Too many levels of symbolic links | `400` | A link loop stands in the path. | | `EINVAL` | Invalid argument | `400` | The call's arguments are invalid. | | `EBUSY` | Device or resource busy | `409` | A mount root, or the workspace is busy. | | `EFBIG` | File too large | `400` | A read the backend will not serve whole. | | `EDQUOT` | Disk quota exceeded | `403` | A write past the mount's capacity. | | `EPIPE` | Broken pipe | `500` | A write to a closed pipe. | | `EIO` | Input/output error | `500` | The backend failed. | | `EBADF` | Bad file descriptor | `500` | A read from a closed or write-only descriptor. | | `NO_XATTR` | No data available | `404` | The attribute is not set. Python on macOS says `Attribute not found`. | | `STALE_WRITE` | changed since it was read; read it again before writing | `409` | A [conditional write](/home/configuration#read-and-write-policies) lost its condition. | Each surface carries the condition its own way: | Surface | Form | | - | - | | Python | An `OSError` with `errno` set, raised as the builtin class for it (`FileNotFoundError`, `PermissionError`, ...). A path no mount owns raises `NoMountError`, a `ValueError`. `mirage.errors.classify(exc)` names the condition for either. | | TypeScript | An `Error` whose `code` is the condition's name (`ENODATA` for `NO_XATTR`), as Node's `fs` does. A path no mount owns sets `noMount`. `classify(err)` from `@struktoai/mirage-core/errors/classify` names either. | | Shell | A line on stderr, `cat: /data/x: No such file or directory`, and the command's exit status. | | [HTTP](/api/errors) | `{"error": {code, message, errno}}` with the status above, plus a `decision` record when a policy refused the call. The [code](/api/errors#status-codes) follows from the condition. | | [RPC](/home/access/rpc#errors) | `-32004` for `ENOENT` and `-32603` for the rest, with HTTP's error object, `{code, message, errno}`, in `data`. | | [MCP](/home/access/mcp#tools) | The tool result with `isError` set: `Error: /data/x: No such file or directory`. | | [FUSE](/home/setup/fuse) | The host's errno number. A failure with no errno reads as `EIO`. | | SFTP | An SFTP status code, such as `3` for permission denied and `4` for a general failure. | | NFS | An NFS3 status code, such as `NFS3ERR_NOTSUPP` (`10004`) for an unsupported call. | | [Runtimes](/home/setup/runtime/overview) | The guest's own error: an `OSError` with its errno in Python, the WASI errno in a WebAssembly guest. | ## Shell lines A line that runs to completion returns `exit_code`, `stdout` and `stderr`. A non-zero status is the line's result, not a failed call: HTTP returns `200`, RPC a result, and MCP sets `isError`. Canceling the request is a failed call instead: HTTP returns status `499` and RPC returns error `-32800`. A command's stderr follows GNU coreutils, and its status is the one the real command exits with. These statuses come from the shell itself: | Status | Means | | - | - | | `0` | Success. | | `1` | The command failed. | | `2` | A usage or syntax error. Some commands use their own (`git` exits `128` and `129`). | | `124` | The line, or `timeout`, ran past its time limit. | | `126` | The command was found but not run: it is not executable, a policy refused it, no runtime takes it, or its argument list is too long, as a glob past a mount's [`walk_limit`](/home/integration/search#walk_limit) is. | | `127` | The command was not found, or an unset variable was read under `set -u`. | | `128` + n | Signal n ended it: `130` for an interrupt (the CLI and SSH report a Ctrl-C so), `141` for a write to a closed pipe. | | `254` | The session's `processes.max` refused a fork. | ## Service errors A command that reaches a service through a mount reports the service's failure as the condition it maps to, or in the service's own words after the command's name. An [account CLI](/home/setup/clis) such as `gh` or `ntn` reports a service error the way the real CLI does, with its wording and exit status. In code, every backend's service error extends `ApiError` (`mirage.core.api.errors`, `@struktoai/mirage-core/core/api/errors`): the service's message and `status`, the HTTP status or null. A service's own error code stays on its subclass, since `code` on a TypeScript error is always the file condition. # HTTP Source: https://docs.mirage.strukto.ai/home/access/http Start and configure a self-hosted Mirage HTTP server. Run the Python or TypeScript server to access your Mirage workspaces over HTTP. This guide covers setup, authentication, limits, and server operations. Use the [API reference](/api/reference) for endpoint fields and responses. ## Launch a server Set a token in the server's environment before starting the process: ```bash theme={null} export MIRAGE_AUTH_MODE=token export MIRAGE_AUTH_TOKEN='replace-with-your-token' ``` > [tab] Python > > In an activated Python environment, install the server: > > ```bash theme={null} > python -m pip install mirage-ai > ``` > > Save this as `server.py`: > > ```python server.py theme={null} > import uvicorn > > from mirage.server.app import build_app > > uvicorn.run(build_app(), host="127.0.0.1", port=8765) > ``` > > Start it in the terminal where you set the token, and leave it running: > > ```bash theme={null} > python server.py > ``` > [tab] TypeScript > > In your Node project, install the server and TypeScript runner: > > ```bash theme={null} > npm install @struktoai/mirage-server > npm install -D tsx typescript > ``` > > Save this as `server.mts`. The `.mts` extension uses ES modules without > changing how other files in your project load: > > ```typescript server.mts theme={null} > import { buildApp } from '@struktoai/mirage-server' > > await buildApp().listen({ host: '127.0.0.1', port: 8765 }) > ``` > > Start it in the terminal where you set the token, and leave it running: > > ```bash theme={null} > npx tsx server.mts > ``` The server accepts only the host names in `MIRAGE_ALLOWED_HOSTS`: `127.0.0.1`, `localhost` and `::1` by default. Add the name your clients use. It also refuses a browser page served from any other origin, a page on another port of `localhost` included, even when the list is `*`. Other options are on the [Python](/python/access/server) and [TypeScript](/typescript/access/server) server pages. ## Verify the connection From another terminal, check that the server is running: ```bash theme={null} curl --fail --silent --show-error http://127.0.0.1:8765/v1/health ``` The response includes `"status": "ok"`. Health checks do not require a token. Use `http://127.0.0.1:8765` as the base URL for requests to this server and send `Authorization: Bearer ` on authenticated requests. For workspace creation and command execution, see [Create a workspace](/api/operations/workspaces/create-workspace) and [Run shell command](/api/operations/shell/run-shell-command). Replace the example API host with your server's base URL. ## Configure authentication `MIRAGE_AUTH_MODE` picks what the server accepts on its HTTP, MCP and RPC routes. | Mode | Accepts | Set on the server | | - | - | - | | `local` (default) | The configured token or `~/.mirage/auth_token` if either exists, otherwise any request | `MIRAGE_AUTH_TOKEN` (optional) | | `token` | One shared token | `MIRAGE_AUTH_TOKEN` | | `jwt` | A signed JWT, whose `sub` is the caller's [account](#accounts) | the [JWT settings](#jwt) | ### JWT Point the server at your issuer's keys: ```bash theme={null} export MIRAGE_AUTH_MODE=jwt export MIRAGE_JWT_ALG=RS256 export MIRAGE_JWT_JWKS_URL=https://issuer.example.com/.well-known/jwks.json export MIRAGE_JWT_ISSUER=https://issuer.example.com export MIRAGE_JWT_AUDIENCE=https://mirage.example.com ``` Every token needs `exp` and `sub`. A token with `aud` must name an entry in `MIRAGE_JWT_AUDIENCE`; with none set, every such token is refused. | Setting | Does | | - | - | | `MIRAGE_JWT_ALG` | The one algorithm accepted, such as `RS256`. Required. | | `MIRAGE_JWT_JWKS_URL` | Fetch the signing keys from this URL. Rotating them needs no restart. | | `MIRAGE_JWT_PUBKEY`, `MIRAGE_JWT_PUBKEY_FILE` | A fixed key instead of a JWKS URL. Changing it needs a restart. | | `MIRAGE_JWT_ISSUER` | Require this `iss`. | | `MIRAGE_JWT_AUDIENCE` | The `aud` values a token may name, comma-separated. | | `MIRAGE_JWT_AUTHORIZED_PARTIES` | The `azp` values a token without `aud` may name, comma-separated. | | `MIRAGE_JWT_CLOCK_SKEW_SECONDS` | Clock difference allowed when checking times. Default `5`. | Set one of the JWKS URL or a fixed key, not both. > [accordion] Accept both app session tokens and OAuth access tokens > > A token with `aud` must name an entry in `MIRAGE_JWT_AUDIENCE`. A token > without `aud` needs an `azp` in `MIRAGE_JWT_AUTHORIZED_PARTIES` when that is > set, and is refused when only an audience is set. So one server can accept an > app's session tokens (`azp`) and an OAuth client's access tokens (`aud`), as > Clerk issues them: > > ```bash theme={null} > export MIRAGE_AUTH_MODE=jwt > export MIRAGE_JWT_ALG=RS256 > export MIRAGE_JWT_JWKS_URL=https://clerk.example.com/.well-known/jwks.json > export MIRAGE_JWT_ISSUER=https://clerk.example.com > export MIRAGE_JWT_AUTHORIZED_PARTIES=https://app.example.com > export MIRAGE_JWT_AUDIENCE=client_cli > ``` > > To let `mirage login` sign in to this server, see > [Log in](/home/access/cli#log-in). ### Accounts In `jwt` mode, a token's `sub` is its account, and an account reaches only the workspaces it created. Another account's workspace, session or ask returns HTTP 404 Not Found, matching a missing resource. An [SSH key](/home/access/ssh#auth-optional) joins an account with its `mirage-account` option. > [accordion] What else an account changes > > * `GET /v1/workspaces` lists only the caller's. > * A stored workspace reopens after a restart only for its owner. One stored > before the server used `jwt` mode has no owner, and no account can create > its id. > * Snapshot keys live under `accounts//` in the snapshot store. > * `POST /v1/daemon/shutdown` returns HTTP 403 Forbidden. > [!WARNING] > > Accounts keep workspaces apart, not the host: a workspace config can still > mount a host directory or run the `local` runtime, unless a > [server policy](#server-policies) refuses it. In `local` and `token` mode, > any accepted token can use every route and every workspace, including > `POST /v1/daemon/shutdown`. ## Rate limits By default, the server allows 1000 requests per minute per client IP, counted before authentication so rejected tokens consume the same budget. Configured limits replace this default; include an `ip` limit to keep unauthenticated requests bounded. An explicit empty list in code or `rate_limits = ""` in `config.toml` disables rate limiting. Each limit allows a number of requests per second, minute, hour or day for each value of its key, and answers `429` with `Retry-After` past it until the window that value's first request opened ends. Set them in `config.toml`: ```toml theme={null} [daemon] rate_limits = "ip=1000/minute, account=600/minute, header:x-tenant=50/second" forwarded_allow_ips = "10.0.0.0/8" ``` | Key | Counts requests by | | - | - | | `ip` | The client address. Behind a proxy, list it in `forwarded_allow_ips`, or every client counts as the proxy. | | `account` | The signed-in [account](#accounts). | | `workspace` | The workspace the path names. | | `header:` | That header's value. | A request with no value for a key (no account, no workspace in its path, no such header) is not counted by that limit. `/v1/health`, `/v1/daemon/ready` and the OAuth protected-resource metadata are never counted. WebSocket handshakes consume the same budget as HTTP requests; messages on an established connection do not. In code, a key may also be a function of the request that returns the value to count by, or nothing to skip the limit: ```python Python theme={null} from mirage.server import RateLimit, build_app app = build_app( rate_limits=[ RateLimit("account", "600/minute"), RateLimit(lambda request: request.headers.get("x-tenant"), "50/second"), ] ) ``` ```ts TypeScript theme={null} import { buildApp } from '@struktoai/mirage-server' const app = buildApp({ rateLimits: [ { key: 'account', rate: '600/minute' }, { key: (request) => request.headers['x-tenant']?.toString() ?? null, rate: '50/second' }, ], }) ``` ## Server policies Apply server policies to every workspace the server builds. A workspace's own configuration cannot remove these policies. See [Server policies](/home/policy/policies#pre_workspace) for the policy methods, and [Policy programs](/home/policy/scripts) for file-based rules. Set the policy file in the daemon's configuration: ```toml ~/.mirage/config.toml theme={null} [daemon] policy_file = "policy.yaml" ``` When you build the server in code, pass its policies through [`build_app`](/python/access/server) or [`buildApp`](/typescript/access/server). A workspace's [network configuration](/home/configuration#network) controls where its connections may go. ## Monitor the server ### Health and readiness Use `/v1/health` for a load balancer's liveness check. Use `/v1/daemon/ready` for readiness: it returns `200` while the server accepts new workspaces and `503` when it is full or shutting down. Readiness and shutdown control the server process. ### Metrics The server records workspace, session, command, and refusal metrics under the OpenTelemetry meter `mirage.server`. Configure an SDK and exporter to collect them. > [accordion] Configure metric collection > > The server records its metrics through [OpenTelemetry](https://opentelemetry.io/docs/concepts/signals/metrics/), > under the meter `mirage.server`. Nothing is sent until the process sets up an > OpenTelemetry SDK, and the exporter it picks decides where they go: OTLP to > Datadog, New Relic, Honeycomb, Grafana Cloud, CloudWatch or Google Cloud, a > Prometheus page, or the console. They are server-wide and name no workspace or > account. > > | Instrument | Kind | Value | > | - | - | - | > | `mirage.workspace.count` | up-down counter | Workspaces it holds. | > | `mirage.workspace.limit` | up-down counter | Its `max_workspaces`, when set. | > | `mirage.session.count` | up-down counter | Sessions across its workspaces. | > | `mirage.job.running` | up-down counter | Shell lines running. | > | `mirage.server.shutting_down` | gauge | `1` while it shuts down. | > | `mirage.request.refused` | counter | Requests refused for a server limit, by `reason`: `rate_limit`, `max_sessions`, `max_workspaces` or `shutting_down`. | > > In Python, run the app under `opentelemetry-instrument`, which also records > each HTTP request: > > ```bash theme={null} > pip install opentelemetry-distro opentelemetry-exporter-otlp > OTEL_METRICS_EXPORTER=otlp OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.example.com \ > opentelemetry-instrument uvicorn main:app > ``` > > In TypeScript, register a meter provider before `buildApp`: > > ```ts theme={null} > import { metrics } from '@opentelemetry/api' > import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http' > import { MeterProvider, PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics' > import { buildApp } from '@struktoai/mirage-server' > > metrics.setGlobalMeterProvider( > new MeterProvider({ > readers: [new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter() })], > }), > ) > const app = buildApp() > ``` ### Shut down Request a graceful shutdown of a server you operate: ```bash theme={null} curl --request POST http://127.0.0.1:8765/v1/daemon/shutdown \ --header "Authorization: Bearer $MIRAGE_AUTH_TOKEN" ``` The daemon shuts down through its exit hook. A server created in code needs an `on_idle_exit` callback in Python or `onIdleExit` in TypeScript; without a hook, it keeps serving. See the [Python](/python/access/server) or [TypeScript](/typescript/access/server) server configuration. ## Lines, jobs and processes Inspect active and recently completed work with [List commands](/api/operations/lines/list-commands), [List jobs](/api/operations/jobs/list-jobs), and [List processes](/api/operations/processes/list-processes). A shell result's `line_id` identifies its [line record](/api/operations/lines/get-command). Servers using the same workspace store share these records, and snapshots keep ended records. See those endpoint pages for retention, filters, and response fields. ## Streaming and stdin See [Streaming and stdin](/api/streaming) in the API reference for output records, cancellation, and multipart input examples. ## Next steps > [card] [API reference](/api/reference) > > Look up request fields, response schemas, and endpoint examples. # MCP Source: https://docs.mirage.strukto.ai/home/access/mcp Connect Claude Code, Cursor, VS Code or Codex to a workspace. Every workspace on the Mirage server is an [MCP](https://modelcontextprotocol.io) server at: ``` http://127.0.0.1:8765/v1/workspaces/{id}/mcp ``` An agent connected to it gets a shell and six file tools over the workspace's files. ## Connect On your own machine, let the client launch `mirage mcp`. It starts the server if needed and sends your token. These examples use the `demo` workspace from the [CLI quickstart](/home/access/cli#quickstart). > [tab] Claude Code > > ```bash theme={null} > claude mcp add mirage -- mirage mcp -w demo > ``` > [tab] Cursor > > ```json .cursor/mcp.json theme={null} > { > "mcpServers": { > "mirage": { "command": "mirage", "args": ["mcp", "-w", "demo"] } > } > } > ``` > [tab] VS Code > > ```json .vscode/mcp.json theme={null} > { > "servers": { > "mirage": { "type": "stdio", "command": "mirage", "args": ["mcp", "-w", "demo"] } > } > } > ``` > [tab] Codex > > ```toml ~/.codex/config.toml theme={null} > [mcp_servers.mirage] > command = "mirage" > args = ["mcp", "-w", "demo"] > ``` For a server elsewhere, give the client the URL and a token: > [tab] Claude Code > > ```bash theme={null} > claude mcp add --transport http mirage https://mirage.example.com/v1/workspaces/demo/mcp \ > --header "Authorization: Bearer $MIRAGE_TOKEN" > ``` > [tab] Cursor > > ```json .cursor/mcp.json theme={null} > { > "mcpServers": { > "mirage": { > "url": "https://mirage.example.com/v1/workspaces/demo/mcp", > "headers": { "Authorization": "Bearer ${env:MIRAGE_TOKEN}" } > } > } > } > ``` > [tab] VS Code > > ```json .vscode/mcp.json theme={null} > { > "servers": { > "mirage": { > "type": "http", > "url": "https://mirage.example.com/v1/workspaces/demo/mcp", > "headers": { "Authorization": "Bearer ${env:MIRAGE_TOKEN}" } > } > } > } > ``` > [tab] Codex > > ```toml ~/.codex/config.toml theme={null} > [mcp_servers.mirage] > url = "https://mirage.example.com/v1/workspaces/demo/mcp" > bearer_token_env_var = "MIRAGE_TOKEN" > ``` ## Auth MCP uses the same bearer token as [HTTP](/home/access/http#configure-authentication). `mirage mcp` sends the CLI's token for you: a saved [login](/home/access/cli#log-in), `MIRAGE_TOKEN`, or the local token file. A client that connects by URL sends the header itself; the endpoint does not start an OAuth sign-in. ## Tools Every tool answers text, with `isError` set when it fails. | Tool | Does | Read-only | | - | - | - | | [`shell`](#shell) | Run a shell line. | | | [`read`](#read) | Read a file as numbered lines. | yes | | [`write`](#write) | Write a file. | | | [`edit`](#edit) | Replace a string in a file. | | | [`ls`](#ls) | List a directory. | yes | | [`grep`](#grep) | Search file contents. | yes | | [`glob`](#glob) | Find paths by pattern. | yes | A session sees only the tools its [agent profile](/home/policy/explain#which-tools-the-agent-gets) allows: `shell` needs a command the allow list allows, `ls` and `grep` need those commands, and `write` and `edit` need a mount the session may write. A tool it does not see answers `not found`. ### shell Runs a shell line in the session's working directory. A `cd` or `export` holds for the next call. **command** `string` *required* The line to run. Answers stdout, then stderr. `isError` is set when the line exits non-zero. ```text theme={null} x = 2 print(x) ls: cannot access '/nope': No such file or directory ``` ### read Reads a file as numbered lines. **path** `string` *required* Absolute path of the file. **offset** `integer` (default: 0) First line to return, zero-based. **limit** `integer` (default: 2000) Most lines to return. ```text theme={null} 1 x = 1 2 print(x) ``` ### write Writes a file, creating missing parent directories. To replace a file that exists, `read` all of it first; the write fails if it changed since. Use [`edit`](#edit) to change part of a file. **path** `string` *required* Absolute path of the file. **content** `string` *required* The text to write. ```text theme={null} Written: /data/a.py ``` ### edit Replaces a string in a file. Fails if the file changed since it was read, or if `old_string` is missing or appears more than once without `replace_all`. **path** `string` *required* Absolute path of the file. **old\_string** `string` *required* The exact text to replace. **new\_string** `string` *required* The text to put in its place. **replace\_all** `boolean` (default: false) Replace every occurrence. ```text theme={null} Edited: /data/a.py (1 occurrence(s)) ``` ### ls Lists a directory, one name per line. **path** `string` *required* Absolute path of the directory. ```text theme={null} a.py sub ``` ### grep Searches files under a path for a regular expression, as `grep -rn` does. Finding nothing is not an error. **pattern** `string` *required* The regular expression. **path** `string` *required* Absolute path of the file or directory to search. **ignore\_case** `boolean` (default: false) Match case-insensitively (`-i`). **fixed\_strings** `boolean` (default: false) Read the pattern as plain text (`-F`). **include** `string` Search only files whose name matches this glob, such as `*.py` (`--include`). **context** `integer` Lines of context around each match (`-C`). **files\_with\_matches** `boolean` (default: false) Print only the names of matching files (`-l`). **count** `boolean` (default: false) Print only a count of matching lines per file (`-c`). **max\_count** `integer` Stop each file after this many matches (`-m`). ```text theme={null} /data/a.py:2:print(x) ``` ### glob Finds files whose path matches a pattern, sorted. `**` matches any number of directories. A pattern that matches more files than a mount's [`walk_limit`](/home/integration/search#walk_limit) is an error that names the limit. **pattern** `string` *required* The pattern, such as `**/*.py`. A relative one is matched under `path`. **path** `string` (default: /) The directory a relative pattern is matched under. ```text theme={null} /data/a.py ``` ## Output progress A `shell` call can send output previews while it runs. Pass a progress token in the request's `_meta`: ```json theme={null} { "jsonrpc": "2.0", "id": 7, "method": "tools/call", "params": { "name": "shell", "arguments": { "command": "echo ready; sleep 1; echo done" }, "_meta": { "progressToken": "run-7" } } } ``` Mirage then sends `notifications/progress` messages that start with `[stdout]` or `[stderr]`, over HTTP and `mirage mcp` alike. Previews are trimmed and batched, so take the full output from the final result. ## VFS calls Add `?calls=all` to the URL, or `--all-calls` to `mirage mcp`, for 23 more tools: `vfs_read`, `vfs_is_dir` and the rest, one per [VFS call](/api/reference). They take the same arguments and return the same JSON as HTTP. A failed call sets `isError` and answers the [HTTP error object](/api/errors#error-body) as its text, such as `{"code": "not_found", "message": "No such file or directory", "errno": "ENOENT"}`. With them enabled, `shell` and every `vfs_` also take `explain: true`, which reports what the call would do without running it; see [Explain](/home/policy/explain). ## Sessions Calls run in the workspace's default session. To use another, add `?session_id=` to the URL, or `-s ` to `mirage mcp`. The session's [agent profile](/home/profiles) applies as it does to a shell line: a path hidden from `cat` is hidden from `read`. Command rules apply only to `shell`, `ls` and `grep`. # Access Source: https://docs.mirage.strukto.ai/home/access/overview How agents, and sometimes humans, reach a Mirage virtual terminal. ![Every client reaches one core, the Workspace. An app calls it directly. The mirage CLI, MCP clients and RPC clients reach the server's HTTP routes. SSH clients reach its SSH server. Both servers call the Workspace.](https://mintcdn.com/struktoai/P2GwmHfVdrabAh4w/images/access-light.svg?fit=max\&auto=format\&n=P2GwmHfVdrabAh4w\&q=85\&s=ea2fef1ebc98119a48a7fb1beb0a2456) | Way in | For | Reach it with | | - | - | - | | In-app | an agent in your own process | `Workspace` and `Session`, in [Python](/python/access/in-app) or [TypeScript](/typescript/access/in-app) | | [HTTP](/home/access/http) | programs and services | `/v1/...` routes, or [`mirage api`](/home/access/cli#call-any-route) with the CLI's login | | [MCP](/home/access/mcp) | agent harnesses such as Claude Code, Cursor and Codex | `/v1/workspaces/{id}/mcp`, or `mirage mcp` on stdio | | [RPC](/home/access/rpc) | programs that run lines and move bytes | `/v1/workspaces/{id}/rpc`, or `mirage rpc` on stdio | | [CLI](/home/access/cli) | people and scripts | `mirage ` | | [SSH](/home/access/ssh) | people and tools that speak SSH | `ssh`, `sftp`, `scp`, on the SSH port or through `mirage ssh-proxy` | | [FUSE](/home/setup/fuse) | editors, language servers and other host programs | a folder on the machine running Mirage | HTTP, MCP, RPC, CLI and SSH connections go through the Mirage server, a FastAPI app in [Python](/python/access/server) and a Fastify app in [TypeScript](/typescript/access/server) that speak the same protocol. It serves HTTP, and SSH on its own port when `ssh_port` is set or over HTTP through `mirage ssh-proxy`. The CLI starts the server on your machine when it needs one. In-app access reaches the workspace directly. ## What each one exposes Each way in exposes what its own protocol defines. A dash means the protocol has no such operation. | | In-app | HTTP | MCP | RPC | CLI | SSH | | - | - | - | - | - | - | - | | Create, list, delete workspaces | ✓ | ✓ | – | – | ✓ | – | | Create, list, delete sessions | ✓ | ✓ | – | – | ✓ | – | | Run a line | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | Send stdin to a line | ✓ | ✓ | – | ✓ | ✓ | ✓ | | Cancel a running line | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | Cancel or kill all of a session's or workspace's work | ✓ | ✓ | – | – | ✓ | – | | VFS.md, SKILL.md and session profiles | ✓ | ✓ | – | – | ✓ | – | | The seven agent tools | ✓ | ✓ | ✓ | ✓ | ✓ | – | | File operations on bytes | ✓ | ✓ | ✓ | ✓ | ✓ | `sftp`, `scp`, `sshfs` | | Explain a line or a VFS call | ✓ | ✓ | ✓ | ✓ | ✓ | – | | Snapshots | ✓ | ✓ | – | – | ✓ | – | | Asks | ✓ | ✓ | – | – | ✓ | – | | Jobs | – | ✓ | – | – | ✓ | – | | History | ✓ | ✓ | – | – | ✓ | – | ## Sessions A session is one shell inside a workspace. It keeps its own working directory, environment variables and history, and runs under one [agent profile](/home/profiles). Agents in different sessions share the workspace's files but not their shell state. | Way in | Specify the session with | | - | - | | HTTP, MCP, RPC | `?session_id=` | | MCP or RPC over stdio | `-s` | | CLI | `-s` | | SSH, `sshfs` included | Each login opens a new session under its key's profile. | A call that specifies no session runs in the workspace's default session. Its profile is the one the config's `profile:` names, else the one called `default`, else none. ## Cancel | Way in | Cancel a running line with | | - | - | | CLI, SSH | Ctrl-C | | MCP | `notifications/cancelled` | | RPC | `$/cancelRequest` | | HTTP | A dropped request | To stop a whole session, whichever way its lines came in: | Stop | HTTP | CLI | | - | - | - | | A session's running lines | `POST /v1/workspaces/{id}/sessions/{session_id}/cancel` | `mirage workspace session cancel -w ID -s S` | | A session's background jobs | `POST /v1/workspaces/{id}/sessions/{session_id}/kill` | `mirage workspace session kill -w ID -s S` | ## Auth When authentication is configured, every way in proves who is calling. `GET /v1/health` and OAuth discovery stay public. | Way in | Authenticates with | | - | - | | HTTP, MCP, RPC | A bearer token: `Authorization: Bearer ` | | CLI, and MCP or RPC over stdio | The CLI's local token, sent for you | | SSH on the SSH port | A public key | | SSH through `mirage ssh-proxy` | The CLI's token | A server you start directly in `local` mode, with no token configured, accepts requests without one. In `jwt` mode a token's `sub` is an [account](/home/access/http#accounts) that reaches only its own workspaces, and an SSH key names its account with `mirage-account`. See [Auth](/home/access/http#configure-authentication). # RPC Source: https://docs.mirage.strukto.ai/home/access/rpc Drive a workspace session from a program over JSON-RPC 2.0. RPC is a session's in-app API over [JSON-RPC 2.0](https://www.jsonrpc.org/specification). Each method is named after the call it makes: `shell` is `session.shell`, `vfs/read` is `session.vfs.read`. Use it when a program drives the workspace and needs exact bytes, with stdout, stderr and the exit code apart. Every workspace on the Mirage server answers RPC at: ``` http://127.0.0.1:8765/v1/workspaces/{id}/rpc ``` ## Connect These examples use the `demo` workspace from the [CLI quickstart](/home/access/cli#quickstart). > [tab] stdio > > `mirage rpc` reads one message per line on stdin and writes one answer per > line on stdout. It starts the server if needed and sends your token. > > ```bash theme={null} > echo '{"jsonrpc": "2.0", "id": 1, "method": "shell", "params": {"command": "ls / | wc -l"}}' | mirage rpc -w demo > ``` > [tab] HTTP > > One message, or a batch, per `POST`. The answer is the body. > > ```bash theme={null} > curl -s http://127.0.0.1:8765/v1/workspaces/demo/rpc \ > -H "Authorization: Bearer $MIRAGE_TOKEN" \ > -H 'Content-Type: application/json' \ > -d '{"jsonrpc": "2.0", "id": 1, "method": "shell", "params": {"command": "ls / | wc -l"}}' > ``` Both answer: ```json theme={null} {"jsonrpc": "2.0", "id": 1, "result": {"exit_code": 0, "stdout": "3\n", "stderr": "", "decision": null}} ``` Answers come back as calls finish, so match them by `id`. ## Auth RPC uses the same bearer token as [HTTP](/home/access/http#configure-authentication). `mirage rpc` sends the CLI's token for you: a saved [login](/home/access/cli#log-in), `MIRAGE_TOKEN`, or the local token file. A client that posts to the URL sends the header itself. ## Methods | Method | Params | Result | | - | - | - | | `initialize` | | `{server_info, protocol_version, workspace_id, session_id, methods}` | | `shell` | `command`, `cwd?`, `env?`, `stdin?`, `open_stdin?`, `explain?` | `{exit_code, stdout, stderr, decision}` | | `stdin/write` | `id`, `data` | `null` | | `stdin/close` | `id` | `null` | | `vfs/` | the call's arguments, `explain?` | what the call returns | | `tools/` | the tool's input | `{text, is_error}` | | `tools/list` | | `{tools}`, as MCP lists them | | `tools/call` | `name`, `arguments` | `{text, is_error}` | * `?` marks an optional param. * `initialize` is optional and creates nothing: it reports the server, and the workspace and session the connection uses. * `vfs/` is each of the 23 [VFS calls](/api/reference), with the same arguments and results as HTTP. The [tools](/home/access/mcp#tools) take the inputs listed on the MCP page. * `explain: true` on `shell` or `vfs/` says what it would do and runs nothing; see [Explain](/home/policy/explain). * Bytes, `stdin` included, are base64 strings. A message is at most 4 MiB, so send larger stdin over [HTTP](/api/streaming#send-stdin) or SSH. * A line that exits non-zero is a result, not an error. ## Sessions Calls run in the workspace's default session. To use another, add `?session_id=` to the URL, or `-s ` to `mirage rpc`. The session's [agent profile](/home/profiles) applies to every method. ## Cancel Send the notification `$/cancelRequest` with the id of a running request. That request answers `-32800`, and its job ends `canceled`. A dropped HTTP request cancels its calls too. ```json theme={null} {"jsonrpc": "2.0", "method": "$/cancelRequest", "params": {"id": 7}} ``` ## Write to a running line A `shell` with `open_stdin: true` reads what `stdin/write` sends until `stdin/close`. Both name the `id` of that `shell` request, as `$/cancelRequest` does, and its answer comes when the line ends. ```json theme={null} {"jsonrpc": "2.0", "id": 7, "method": "shell", "params": {"command": "cat", "open_stdin": true}} {"jsonrpc": "2.0", "id": 8, "method": "stdin/write", "params": {"id": 7, "data": "aGVsbG8K"}} {"jsonrpc": "2.0", "id": 9, "method": "stdin/close", "params": {"id": 7}} ``` `stdin/write` answers once the bytes are buffered, so a command that reads slowly holds it back. Send one at a time to keep the bytes in order. ## Errors | Code | Means | | - | - | | `-32700` | The message is not JSON. | | `-32600` | Not a JSON-RPC 2.0 request: no `"jsonrpc": "2.0"`, or no method. | | `-32601` | No such method. | | `-32602` | Bad params. | | `-32004` | No such path (`ENOENT`), or no running `shell` opened that stdin. | | `-32603` | Anything else, such as a refused path. | | `-32800` | Canceled. | A file error carries the [HTTP error object](/api/errors#error-body) in `data`: its `code`, `message` and `errno`, plus a `decision` record when a policy refused it: ```json theme={null} {"jsonrpc": "2.0", "id": 2, "error": {"code": -32004, "message": "No such file or directory", "data": {"code": "not_found", "message": "No such file or directory", "errno": "ENOENT"}}} ``` # SSH Source: https://docs.mirage.strukto.ai/home/access/ssh Reach a workspace with ssh, sftp, scp and sshfs. The Mirage server can listen for SSH next to HTTP. The SSH username names the workspace, every line runs in Mirage's shell, and every file operation goes through the workspace's mounts. ## Set up **1. Install the SSH library** > [tab] Python > > ```bash theme={null} > pip install 'mirage-ai[ssh]' > ``` > [tab] TypeScript > > ```bash theme={null} > npm install -g ssh2 > ``` **2. Pick a port** ```bash theme={null} mirage daemon config set ssh_port 2222 ``` SSH stays off until a port is set. **3. Authorize your key** ```bash theme={null} mkdir -p ~/.mirage/ssh cat ~/.ssh/id_ed25519.pub >> ~/.mirage/ssh/authorized_keys ``` Only public keys log in, and the file is read on every login. **4. Restart the server** ```bash theme={null} mirage daemon restart mirage workspace create workspace.yaml --id demo ``` > [accordion] Settings > > An environment variable wins over `~/.mirage/config.toml`, which wins over the > default. > > | Key | Env var | Default | > | - | - | - | > | `ssh_port` | `MIRAGE_SSH_PORT` | unset (off) | > | `ssh_host` | `MIRAGE_SSH_HOST` | `127.0.0.1` | > | `ssh_host_key_file` | `MIRAGE_SSH_HOST_KEY_FILE` | `~/.mirage/ssh/host_ed25519_key` | > | `ssh_authorized_keys` | `MIRAGE_SSH_AUTHORIZED_KEYS` | `~/.mirage/ssh/authorized_keys` | > > The server makes its host key on first start and keeps it, so your > `known_hosts` entry stays valid. ## Connect | Command | Does | | - | - | | `ssh -p 2222 demo@127.0.0.1` | Open a shell in workspace `demo`. | | `ssh -p 2222 demo@127.0.0.1 'ls /data \| wc -l'` | Run one line. | | `ssh -T -p 2222 demo@127.0.0.1 < setup.sh` | Run a script. | | `sftp -P 2222 demo@127.0.0.1` | Transfer files. | | `scp -P 2222 notes.txt demo@127.0.0.1:/data/` | Copy a file in. | | `sshfs -p 2222 -o direct_io demo@127.0.0.1:/ ~/mnt/demo` | Show the workspace as a local folder. | Each run gets a fresh session, so a `cd` or `export` never leaks between them. Ctrl-C cancels the running line, and `ssh host cmd` exits with the line's status. To mount a folder on the machine running Mirage instead, use [FUSE](/home/setup/fuse). ### Over HTTPS A hosted server carries SSH over its HTTPS port, so it needs no SSH port or key. `mirage ssh-proxy` relays it with the CLI's token: ```text ~/.ssh/config theme={null} Host mirage ProxyCommand mirage ssh-proxy %r ``` Then `ssh demo@mirage`, `sftp demo@mirage`, `scp notes.txt demo@mirage:/data/` and `sshfs -o direct_io demo@mirage:/ ~/mnt/demo` all work. The CLI sends its token, your [`mirage login`](/home/access/cli#log-in) on a hosted server, and the login runs under the workspace's default profile. ## Auth (optional) In `local` and `token` mode, an authorized key opens every workspace under the workspace's default profile. Options in front of a key in `authorized_keys` narrow it: ```text ~/.mirage/ssh/authorized_keys theme={null} mirage-profile="guarded" ssh-ed25519 AAAA... agent-a mirage-account="alice",mirage-profile="guarded" ssh-ed25519 AAAA... alice-agent ssh-ed25519 AAAA... me ``` | Option | Does | | - | - | | `mirage-profile` | Runs every login of the key under this [agent profile](/home/profiles). The server reads it, so a key cannot pick looser rules. | | `mirage-account` | Opens only the workspaces this [account](/home/access/http#accounts) created. Another account's workspace answers like a missing one. | On a [`jwt`](/home/access/http#jwt) server, each login reaches only its account's workspaces: | Way in | How | | - | - | | [Over HTTPS](#over-https) | `mirage login`, then connect through `mirage ssh-proxy`. Your JWT is the account; no key needed. | | SSH port | The operator adds `mirage-account="you"` to your key. A key without it opens nothing. | > [accordion] Account rules in detail > > * The account holds for shell, exec, `sftp` and `scp` alike. > * In `local` and `token` mode, a key without `mirage-account` opens every > workspace. > * An option that is empty or given twice opens nothing. > [accordion] How sessions behave > > * Each `ssh`, `sftp` or `scp` run gets a fresh session, closed when it ends. > * The session's profile and the mount modes apply as in any shell: a > read-only mount refuses `sftp put`. > * Output streams as the line prints it. > * Ctrl-C cancels the running line and sets `$?` to 130. A dropped connection > cancels it too. > * The server sends a keepalive every 15 seconds and closes a connection that > misses three, so a half-open one cancels its line as well. > * Nothing is forwarded: no ports, no agent, no X11. # Agents Source: https://docs.mirage.strukto.ai/home/agents Give your agent a composable, scriptable and durable Mirage virtual terminal. ## Access These connections work independently of your agent's programming language. | Connection | What the agent gets | | - | - | | [MCP](/home/access/mcp) | Shell and file tools through an MCP client. | | [FUSE](/home/setup/fuse) | A VFS exposed by your own app as a folder its existing file tools can read and write. | | [SSH](/home/access/ssh) | A remote shell, plus file access through SFTP, SCP or SSHFS. | | [HTTP](/home/access/http) or [RPC](/home/access/rpc) | An API for running commands and working with files. | | [CLI](/home/access/cli) | Workspace access through `mirage` commands. | ## Supported agents ### Coding agents Run the agent as it is, on a workspace the `mirage` CLI creates. | Agent | Shell | MCP | SSH | FUSE | | - | :-: | :-: | :-: | :-: | | [Claude Code](/home/agents/claude-code) | ✓ | ✓ | | ✓ | | [Codex](/home/agents/codex) | | ✓ | ✓ | ✓ | | [Grok Build](/home/agents/grok-build) | | ✓ | | ✓ | * **Shell**: the agent's own shell is [`mirage-bash`](/home/access/cli#mirage-bash), so every command it runs goes to the workspace. * **MCP**: the agent adds Mirage's seven tools, from its plugin or `mirage mcp`. * **SSH**: the agent's own tools run in the workspace. * **FUSE**: the agent's own tools work on the workspace, mounted as a folder. Or load Mirage into the agent as a TypeScript plugin, which replaces its own file and shell tools: | Agent | Plugin | | - | - | | [Pi Coding Agent](/typescript/agents/pi) | `@struktoai/mirage-pi` | | [OpenCode](/typescript/agents/opencode) | `@struktoai/mirage-opencode` | | [DeepSeek Harness](/typescript/agents/dsh) | `@struktoai/mirage-dsh` | ### Agent frameworks | Framework | Python | TypeScript | | - | - | - | | Claude Agent SDK | [Guide](/python/agents/claude-agent-sdk) | [Guide](/typescript/agents/claude-agent-sdk) | | OpenAI Agents SDK | [Guide](/python/agents/openai-agents) | [Guide](/typescript/agents/openai) | | LangChain Deep Agents | [Guide](/python/agents/langchain) | [Guide](/typescript/agents/langchain) | | Agno | [Guide](/python/agents/agno) | — | | Pydantic AI | [Guide](/python/agents/pydantic-ai) | — | | Haystack | [Guide](/python/agents/haystack) | — | | Vercel AI SDK | — | [Guide](/typescript/agents/vercel) | | Mastra | — | [Guide](/typescript/agents/mastra) | ### Hosted agents | Service | Python | TypeScript | | - | - | - | | OpenAI Agents API | [Guide](/python/agents/openai-agents-api) | [Guide](/typescript/agents/openai-agents-api) | | Claude Managed Agents | [Guide](/python/agents/claude-managed-agents) | [Guide](/typescript/agents/claude-managed-agents) | For an agent you build yourself, use the [Python](/python/access/in-app) or [TypeScript](/typescript/access/in-app) workspace API. [Agent profiles](/home/profiles) control what each session can see and do. # Claude Code Source: https://docs.mirage.strukto.ai/home/agents/claude-code Connect Claude Code to a Mirage workspace through its shell, MCP or a FUSE mount. | Way | Claude Code gets | Needs | | - | - | - | | [Shell](#shell) | its own Bash, run in the workspace | the `mirage` CLI | | [MCP](#mcp) | Mirage's seven tools, beside its own | the `mirage` CLI, or Node.js for the plugin | | [FUSE](#fuse) | its own tools, on the workspace as a folder | the `mirage` CLI and a [FUSE driver](/home/setup/fuse) | ## Install ```bash uv theme={null} uv tool install mirage-ai ``` ```bash npm theme={null} npm install -g @struktoai/mirage-cli ``` Both install `mirage` and [`mirage-bash`](/home/access/cli#mirage-bash). Install [Claude Code](https://docs.claude.com/en/docs/claude-code/setup) separately. ## Shell `mirage-bash` takes the place of bash, so every command Claude Code's Bash tool runs goes to a workspace session. Mount the project and `/tmp` at their own paths, beside your data: ```yaml workspace.yaml theme={null} mounts: /Users/me/project: { vfs: disk, mode: write, config: { root: /Users/me/project } } /tmp: { vfs: disk, mode: write, config: { root: /tmp } } /data: { vfs: ram, mode: write } ``` * The project mount gives Claude's Bash and its own Read and Edit tools the same files at the same paths. * Claude Code keeps its working directory in `/tmp` between commands, so `cd` carries over. ```bash theme={null} mirage workspace create workspace.yaml --id demo ``` Point Claude Code at it in the project's settings, with the path `command -v mirage-bash` prints: ```json .claude/settings.json theme={null} { "env": { "CLAUDE_CODE_SHELL": "/Users/me/.local/bin/mirage-bash", "MIRAGE_WORKSPACE": "demo" } } ``` Then run `claude` in the project. For one run instead: ```bash theme={null} MIRAGE_WORKSPACE=demo CLAUDE_CODE_SHELL="$(command -v mirage-bash)" claude ``` ### Session and profile Commands run as the workspace's default session. To run them under a [profile](/home/profiles), define it in the workspace: ```yaml workspace.yaml theme={null} profiles: reviewer: mounts: /data: { mode: read } builder: {} ``` Then create a session under it and name the session: ```bash theme={null} mirage workspace session create -w demo -s agent -p reviewer ``` ```json .claude/settings.json theme={null} { "env": { "CLAUDE_CODE_SHELL": "/Users/me/.local/bin/mirage-bash", "MIRAGE_WORKSPACE": "demo", "MIRAGE_SESSION": "agent" } } ``` * Each command runs in a copy of the session, from Claude's working directory. `cd` carries over, since Claude Code tracks it; `export` lasts for that one command, as in Claude Code's own shell. Commands run side by side, so one running in the background does not hold up the next. * The profile applies to every command. Under `reviewer`, `echo x > /data/a.txt` fails with `Read-only file system`, as on a read-only disk; [what the agent reads](/home/policy/explain#what-the-agent-reads) lists every refusal. * `mirage workspace session update -w demo -s agent -p builder` moves the session to another profile while Claude runs. Claude Code's Read, Edit, Write, Glob and Grep still run on the host, outside the profile. To route them through Mirage too, add [MCP](#mcp) and deny them, or use [FUSE](#fuse). ## MCP > [tab] Plugin > > ```text theme={null} > /plugin marketplace add strukto-ai/mirage > /plugin install mirage@mirage > ``` > > The plugin adds a filesystem skill, a VFS authoring skill and an MCP server that runs `npx -y @struktoai/mirage-cli mcp` on your project's `.mirage/workspace.yaml`. > [tab] mirage mcp > > ```bash theme={null} > claude mcp add mirage -- mirage mcp -w demo > ``` > > Add `-s agent` to serve the tools as a session, under its profile. Claude Code gets `shell`, `read`, `write`, `edit`, `ls`, `grep` and `glob` from the workspace's [MCP server](/home/access/mcp), beside its own tools. With [Shell](#shell), serve the same session and deny the tools that would bypass it: ```bash theme={null} claude mcp add mirage -- mirage mcp -w demo -s agent ``` ```json .claude/settings.json theme={null} { "permissions": { "deny": ["Read", "Edit", "Write", "Glob", "Grep", "mcp__mirage__shell"] } } ``` Claude then reads and edits through Mirage's tools and runs commands through its own Bash, all as session `agent`. ## FUSE Install your platform's [FUSE driver](/home/setup/fuse). With uv, install `'mirage-ai[fuse]'`; with npm on macOS, also follow the [macFUSE 4 workaround](/typescript/setup/fuse#macfuse-4-symlink-workaround). Then expose the workspace at a local folder: ```yaml workspace.yaml theme={null} mounts: /: vfs: ram mode: write backend: fuse mountpoint: /tmp/mirage-demo ``` ```bash theme={null} mirage workspace create workspace.yaml --id demo-fuse cd /tmp/mirage-demo && claude ``` File operations inside `/tmp/mirage-demo` go through Mirage, with Claude's own tools. The mount does not restrict the agent's access to other host paths. `mirage workspace delete demo-fuse` unmounts it. On macOS the daemon holds one FUSE mount at a time. # OpenAI Codex Source: https://docs.mirage.strukto.ai/home/agents/codex Connect Codex to a Mirage workspace through SSH, MCP, a FUSE mount or exec-server forward. | Way | Codex gets | Needs | | - | - | - | | [SSH](#ssh) | its own tools, run in the workspace | the daemon's [SSH server](/home/access/ssh) | | [MCP](#mcp) | Mirage's seven tools, beside its own | the `mirage` CLI, or Node.js for the plugin | | [FUSE](#fuse) | its own tools, on the workspace as a folder | the `mirage` CLI and a [FUSE driver](/home/setup/fuse) | | [Exec-server forward](#exec-server-forward) | its own tools, run in the workspace, for a remote harness | `codex exec-server forward` | ## Install ```bash uv theme={null} uv tool install 'mirage-ai[ssh]' ``` ```bash npm theme={null} npm install -g @struktoai/mirage-cli ``` The `ssh` extra is for SSH and exec-server forward. Install [Codex](https://github.com/openai/codex) separately. ## Workspace ```yaml workspace.yaml theme={null} mounts: /: vfs: ram mode: write ``` ```bash theme={null} mirage workspace create workspace.yaml --id demo ``` ## SSH Codex runs its shell commands, file reads and patches in the workspace. Turn on the daemon's [SSH server](/home/access/ssh#set-up), then add it as a Codex environment: ```toml ~/.codex/environments.toml theme={null} default = "mirage" include_local = false [[environments]] id = "mirage" program = "ssh" args = ["-T", "-p", "2222", "demo@127.0.0.1", "-s", "codex-exec"] ``` ```bash theme={null} codex -C / ``` * It works in the Codex TUI and in `codex exec`, not the Codex app. * Commands run under the SSH key's [profile](/home/profiles). * Commands run side by side, each in its own shell, so what one exports stays in it. * Codex checks `-C` on the local disk, so pass `-C /` and use absolute workspace paths. * The protocol is experimental and follows Codex 0.147. ## MCP > [tab] Plugin > > ```bash theme={null} > codex plugin marketplace add strukto-ai/mirage > codex plugin add mirage@mirage > ``` > > The plugin adds a filesystem skill, a VFS authoring skill and an MCP server that runs `npx -y @struktoai/mirage-cli mcp` on your project's `.mirage/workspace.yaml`. > [tab] mirage mcp > > ```bash theme={null} > codex mcp add mirage -- mirage mcp -w demo > ``` > > Add `-s SESSION` to serve the tools as a session, under its profile. Codex gets `shell`, `read`, `write`, `edit`, `ls`, `grep` and `glob` from the workspace's [MCP server](/home/access/mcp), beside its own tools. ## FUSE Install your platform's [FUSE driver](/home/setup/fuse). With uv, install `'mirage-ai[fuse]'`; with npm on macOS, also follow the [macFUSE 4 workaround](/typescript/setup/fuse#macfuse-4-symlink-workaround). Then expose the workspace at a local folder: ```yaml workspace.yaml theme={null} mounts: /: vfs: ram mode: write backend: fuse mountpoint: /tmp/mirage-demo ``` ```bash theme={null} mirage workspace create workspace.yaml --id demo-fuse cd /tmp/mirage-demo && codex ``` File operations inside `/tmp/mirage-demo` go through Mirage, with Codex's own tools. The mount does not restrict the agent's access to other host paths. In the Codex app, open the mountpoint as the project folder. `mirage workspace delete demo-fuse` unmounts it. On macOS the daemon holds one FUSE mount at a time. ## Exec-server forward `codex exec-server forward` carries the tool calls of a remote harness, such as an OpenAI Agents API session ([Python](/python/agents/openai-agents-api), [TypeScript](/typescript/agents/openai-agents-api)), to an exec server. `mirage codex-exec` makes the workspace that exec server: it listens on a local port and relays each connection to the server's codex-exec route with the CLI's token, which forward cannot send itself. ```bash theme={null} npm install -g @openai/codex@alpha mirage codex-exec demo --listen 127.0.0.1:8790 ``` ```bash theme={null} CODEX_API_KEY="$OPENAI_EXECUTOR_API_KEY" codex exec-server forward \ --connect ws://127.0.0.1:8790 \ --remote "$REMOTE_URL" \ --environment-id "$ENVIRONMENT_ID" ``` The remote URL and environment id come from the harness's session, and `CODEX_API_KEY` is its environment key. * Each connection runs in a fresh session under the workspace's default profile, closed when the connection ends. A reconnect starts a new session; the files stay. * `mirage codex-exec` lets in any connection on its port, as you, and refuses one from a browser page. Keep it on loopback. * On a hosted server, run [`mirage login`](/home/access/cli#log-in) first; the relay asks for its token on every connection. # Grok Build Source: https://docs.mirage.strukto.ai/home/agents/grok-build Connect Grok Build to a Mirage workspace through MCP or a FUSE mount. | Way | Grok Build gets | Needs | | - | - | - | | [MCP](#mcp) | Mirage's seven tools, beside its own | Node.js | | [FUSE](#fuse) | its own tools, on the workspace as a folder | the `mirage` CLI and a [FUSE driver](/home/setup/fuse) | ## Install Install [Grok Build](https://x.ai/cli) separately; its command is `grok`. FUSE also needs the `mirage` CLI: ```bash uv theme={null} uv tool install 'mirage-ai[fuse]' ``` ```bash npm theme={null} npm install -g @struktoai/mirage-cli ``` ## Workspace ```yaml .mirage/workspace.yaml theme={null} mode: write mounts: /: vfs: ram ``` ## MCP Install the Mirage plugin: ```bash theme={null} grok plugin install strukto-ai/mirage ``` It adds a filesystem skill, a VFS authoring skill and an MCP server that runs `npx -y @struktoai/mirage-cli mcp` on your project's `.mirage/workspace.yaml`. Open `/plugins` in `grok` to check that it is on. ## FUSE Install your platform's [FUSE driver](/home/setup/fuse). With npm on macOS, also follow the [macFUSE 4 workaround](/typescript/setup/fuse#macfuse-4-symlink-workaround). Then expose the workspace at a local folder: ```yaml .mirage/workspace.yaml theme={null} mode: write mounts: /: vfs: ram backend: fuse mountpoint: /tmp/mirage-demo ``` ```bash theme={null} mirage workspace create .mirage/workspace.yaml --id demo cd /tmp/mirage-demo && grok ``` File operations inside `/tmp/mirage-demo` go through Mirage. The mount does not restrict the agent's access to other host paths. `mirage workspace delete demo` unmounts it. On macOS the daemon holds one FUSE mount at a time. # Service credentials Source: https://docs.mirage.strukto.ai/home/authentication Connect VFS, CLI and runtime credentials from the environment or a secret store. Give each VFS, virtual CLI or runtime the credentials it needs to reach its service. These differ from the bearer tokens and JWTs protecting a Mirage server; see [HTTP authentication](/home/access/http#configure-authentication) for those. ## Connect from the environment Set the credential in the environment of the process running Mirage, including on the server when your CLI connects remotely: ```bash theme={null} export SLACK_BOT_TOKEN=xoxb-your-token ``` If the local CLI daemon is already running, run `mirage daemon restart` after exporting the token. The next workspace creation inherits the updated environment. Restarting stops every workspace and keeps it; `mirage workspace start ID` brings one back. See [daemon commands](/home/access/cli#daemon). ```yaml workspace.yaml theme={null} mounts: /slack: vfs: slack config: token: from: env key: SLACK_BOT_TOKEN ``` See [Slack setup](/home/setup/slack) for the token and required scopes. Then create the workspace and check a read: ```bash theme={null} mirage workspace create workspace.yaml --id credentials-demo && mirage shell -w credentials-demo -c 'ls /slack | head' ``` Remove the example workspace afterward with `mirage workspace delete credentials-demo`. The same pointer format works in credential fields for registered virtual CLIs, and in a machine entry, such as E2B's or Daytona's `api_key`: ```yaml workspace.yaml theme={null} machines: box: provider: e2b sandbox_id: ${E2B_SANDBOX_ID} api_key: from: 1password ref: op://Engineering/E2B/credential key: credential ``` ## Pointer fields | Key | Meaning | | - | - | | `from` | A built-in source name or a named instance under `secrets`. | | `ref` | Source-specific address, such as a secret name or file path. Defaults to an empty string. | | `key` | Field selected from the secret. Required in mount, CLI and source config pointers. Managed `env` entries default it to the variable's name. | The `env` source uses only `key`, with no `ref`. A source needing settings is declared under `secrets`, and pointers use that instance's name in `from`. ## Read a dotenv file Python needs the `dotenv` extra in the environment running Mirage. For the `uv tool` CLI, run `uv tool install 'mirage-ai[dotenv]'`. In a Python project, use `uv add 'mirage-ai[dotenv]'` and run its CLI with `uv run mirage`. The Node package includes dotenv support. ```dotenv .env theme={null} SLACK_BOT_TOKEN=xoxb-your-token ``` ```yaml workspace.yaml theme={null} secrets: team: source: dotenv config: path: .env mounts: /slack: vfs: slack config: token: from: team key: SLACK_BOT_TOKEN ``` Use this config with the same workspace creation and read commands above. Relative dotenv paths use the Mirage process's working directory. A pointer's non-empty `ref` overrides the source's configured `path`. ## Other credential sources | `from` | `ref` example | `key` example | Prerequisite | | - | - | - | - | | `aws-sm` | `mirage/slack` or a secret ARN | `SLACK_BOT_TOKEN` | AWS credentials and region in the SDK's normal environment. Python needs `mirage-ai[aws-sm]`; Node includes the source dependency. | | `1password` | `op://Engineering/Slack/credential` | `credential` | `OP_SERVICE_ACCOUNT_TOKEN` in the Mirage process environment. Python needs `mirage-ai[1password]`; Node needs `@1password/sdk`. | | `strukto` | `slack`, a saved entry's name | `token` | A Mirage server, the daemon or the hosted API, and an entry saved with [`mirage vfs`, `cli`, `runtime` or `machine`](/home/access/cli#saved-connections). | Use these values in place of `from`, `ref` and `key` in the mount pointer above. Install source dependencies in the same environment that runs Mirage, using the tool or project installation method described for dotenv. AWS reads `SecretString`, not `SecretBinary`. A JSON object with string values exposes its field names as keys; other text is available under `key: value`. A 1Password field reference fetches that field. An item reference such as `op://Engineering/Slack` lets `key` select a field by its label. Source declarations accept `source` and optional `config`. Pointers inside a source's config can read only from `env` or `dotenv`. Custom sources must be registered in the same process that creates the workspace. # Workspace configuration Source: https://docs.mirage.strukto.ai/home/configuration Configure workspace.yaml mounts, commands, runtimes, profiles and credentials. A workspace config describes one virtual terminal. Python and TypeScript use `snake_case` YAML keys. TypeScript constructor options use camelCase, such as `commandLimits`; provider and runtime guides show their SDK equivalents. ## Start with RAM `mounts` is the only required top-level key. This config creates a writable, in-memory mount without credentials: ```yaml workspace.yaml theme={null} mounts: /data: vfs: ram ``` Create a workspace, check it, and remove it: ```bash theme={null} mirage workspace create workspace.yaml --id config-demo && mirage shell -w config-demo -c 'echo ready > /data/status && cat /data/status' && mirage workspace delete config-demo ``` The shell command prints `ready`. Replace RAM using a [VFS setup guide](/home/setup/vfs). YAML defaults `mode` to `write`; direct Python and TypeScript `Workspace` constructors default to `read`. ### From a template A config saved on the server as a template creates workspaces without the file. The template's `config` is the same document as `workspace.yaml`: ```bash theme={null} mirage api /v1/templates --name ram-only --config '{"mounts": {"/data": {"vfs": "ram"}}}' mirage workspace create --template ram-only -w config-demo ``` Each workspace gets a copy of the config, so editing the template later does not change it. See [From a template](/home/access/cli#from-a-template). ## Workspace settings | Key | Purpose | | - | - | | `mounts` | Map virtual prefixes to VFS configurations, described below. | | `mode` | Default mount access: `read`, `write` or `exec`. | | `read`, `write` | Default mount policies, described [below](#read-and-write-policies). Reads default to `bounded` with a 600-second bound; writes to `unconditional`. | | `clis` | Install [virtual CLIs](/home/setup/clis) by command name, described [below](#cli-entries). | | `runtimes` | Ordered [runtimes](/home/setup/runtime/overview) for programs. | | `route_policy` | Choose runtimes with a [routing policy](/home/policy/route-runtime). | | `profiles`, `profile` | Define [agent profiles](/home/profiles) and select the default. | | `processes` | Set whose processes a session lists and stops, and how many it holds at once; 128 by default. Each profile's block overrides it. See [profiles](/home/profiles). | | `command_limits` | Set [output and execution limits](/home/core/output-limits). | | `max_body_bytes` | Maximum decoded bytes in one buffered API reply, as a [size](#sizes); `64MB` by default (also when `null`). Per-call caps and the room left under `max_memory` also apply. Error replies retain only their first 64 KiB. | | `max_memory` | Bound what the workspace holds in memory, its RAM files and what a command builds, as a [size](#sizes); `96MB` by default, `null` for no cap. See [memory](/home/core/output-limits#limit-a-workspaces-memory). | | `max_env` | Bound what each session's variables, functions, aliases and positional parameters hold, as a [size](#sizes); `2MB` by default, `null` for no cap. A write past it ends the line with exit 2 and `bash: xmalloc: cannot allocate N bytes (past max_env of N bytes, a mirage workspace setting)`. | | `network` | Choose where the workspace's connections may go, described [below](#network). | | `system_time` | Start the workspace's clock at a set time, described [below](#system-time). | | `env` | Seed literal or managed environment variables, described below. | | `secrets` | Declare named [credential sources](/home/authentication). | | `cache`, `index` | Configure cached file content and directory/stat metadata, described [below](#cache-index-and-store). | | `store` | Configure workspace state, background jobs included, described [below](#cache-index-and-store). | | `io` | Set byte-queue capacity with `buffer_bytes`. | | `default_session_id`, `workspace_id` | Set explicit identifiers instead of generated ones. | Unknown keys are errors. Provider fields belong under `mounts..config`, CLI fields under `clis..config`, and runtime fields under `runtimes[].config`. ## Mount settings Each mount key is an absolute virtual prefix, such as `/data`. | Key | Purpose | | - | - | | `vfs` | Required registered VFS name, such as `ram` or `s3`. | | `config` | Provider-specific fields from its [setup guide](/home/setup/vfs). | | `mode` | Override the workspace's access mode. | | `read`, `ttl` | Override the read policy. An explicit `read: bounded` requires `ttl` in positive whole seconds. | | `write` | Override the write policy with one the backend supports. | | `command_limits` | Override limits for commands using this mount. | | `index` | Replace the workspace's index configuration for this mount. | | `backend`, `mountpoint` | Expose a local folder using [FUSE or FSKit](/home/setup/fuse), or `nfs`. The default backend is `workspace`. | `backend` takes one of these values: | Value | Exposes the mount | | - | - | | `workspace` | Inside Mirage only, through the shell and file APIs. | | `fuse` | As a local folder through FUSE. | | `fskit` | As a local folder through FSKit, on macOS 15.4 or later. | | `nfs` | As a local folder through the operating system's NFS client. Mirage serves NFSv3 on a local port and runs the system `mount`, so nothing extra is installed. Linux and macOS; Linux needs root. Read-only. A VFS that cannot size a file without reading it still mounts, with a warning, but those files read as empty; use `fuse` for it. | ## Capacity A RAM, disk, Redis or OPFS store takes `capacity` in its `config`, as a [size](#sizes): ```yaml theme={null} mounts: /data: vfs: ram mode: write config: capacity: 100MB ``` A write past it fails with `EDQUOT` ("Disk quota exceeded", the same message for every store). Through a [FUSE folder](/home/setup/fuse), a program gets it when it syncs or closes the file. Stored data stays readable and removable, and `df` shows the capacity as the store's size. Two workspaces on one disk folder, Redis key prefix or OPFS directory each count only their own writes. A RAM store's files also count against its workspace's `max_memory`, which refuses a write the same way. ## Network `network` decides where the workspace's connections may go: every connection a line or a file call opens, whichever command, CLI, runtime or mount opens it. A program on a [machine](/home/setup/machine/overview) connects from that machine, under its own network settings: `network`, `pre_network` and `routes` do not reach it. | Value | Behavior | | - | - | | `true` | Anywhere. The default. | | `false` | Nowhere: every connection is refused. | | `allowed_domains: [...]` | Only what the list names. | | `denied_domains: [...]` | Anywhere but what the list names. | ```yaml theme={null} network: allowed_domains: - api.github.com:443 - "*.slack.com" - 10.0.0.0/8 denied_domains: - "*:22" ``` An entry is `*` for every host, a host name, `*.` and a name for every host under it, an address, or a range in CIDR form. Any of them but a range may end in `:port`, which holds it to that port; an IPv6 address takes one in brackets, as in `[::1]:8080`. A name matches the host a connection was opened for, and an address or a range the address it reaches. A denied entry wins over an allowed one, and an empty `allowed_domains` lets nothing through. A mount connects under the same rule, so a list names the mount's endpoint too. A [profile](/home/profiles) can hold its sessions to a narrower `network` of its own. `routes` sends a connection to one `host:port` to another: see [Route Network](/home/policy/route-network). A refused connection fails as a closed port does: `curl` exits 7 with `Could not connect to server`. Write `false` rather than `off`, which only some YAML readers take as false. A workspace's policies can also judge each connection the lists let through, and cap how much it carries, at [`pre_network`](/home/policy/policies#pre_network-and-post_network). In a browser or on an edge runtime, `fetch` and `WebSocket` are judged by host name and the address a name reaches is never seen, so a workspace whose `denied_domains` names an address or a range is refused. On an edge runtime a limited workspace follows each redirect under the same rule; in a browser it follows none, since a page cannot see where one goes. A runtime that starts a process on this machine (`local`, Sandlock) opens its connections where Mirage cannot judge them, so while `network` limits anything, or a policy judges connections, it refuses to run: `Permission denied`, exit 126. ## System time `system_time` sets the time the workspace starts at, as an ISO 8601 time with a zone offset, from 1970 through 2261. From there it moves forward in real time: ```yaml theme={null} system_time: 2026-03-02T09:00:00Z env: TZ: America/New_York ``` Right after it starts, `date -u` prints `Mon Mar 2 09:00:00 UTC 2026`, a file written then is stamped 09:00 UTC, and Python's `datetime.date.today()` is `2026-03-02`. `date`, file times, `ls -l`, `find -mtime`, `jq`'s `now` and git commits all see this time, and so do the [Monty](/home/setup/runtime/monty#time-and-datetime), [WASI](/home/setup/runtime/wasi#time-and-datetime), [Pyodide](/home/setup/runtime/pyodide#time-and-datetime) and [QuickJS](/home/setup/runtime/quickjs#date) runtimes. `TZ` in `env` picks the zone `date` shows it in. With no `TZ` a workspace runs on UTC, whatever zone the server is in. Without `system_time`, the workspace uses the server's clock. Each workspace keeps its own time, so workspaces on one server can each start at a different date. Snapshots keep the setting, and `GET /v1/workspaces/{id}` returns it. Programs that `local` or Sandlock run on this machine see the time through [libfaketime](https://github.com/wolfcw/libfaketime) when it is installed, on Linux (`apt install libfaketime`). Without it, or on macOS, they run on the machine's clock. A statically linked program, as many Go tools are, also reads the machine's clock. Programs on a machine work the same way, with libfaketime in the [machine image](/home/setup/machine/overview#the-machine-image) and the machine's clock without it. ## Read and write policies `read` decides when Mirage serves cached file content: | Value | Behavior | | - | - | | `bounded` | Serve cached content without checking the backend, for up to `ttl` seconds. The default. | | `fresh` | Check the backend's content token before serving a cached copy. | `write` decides whether a write carries the version it was based on: | Value | Behavior | | - | - | | `unconditional` | Replacements use last-write-wins. The default. | | `conditional` | Send the version the live session last observed, such as `If-Match` on the S3 family, so a write based on a stale read is refused. | Conditional writes and deletes reject changes based on a stale read when the backend supports it. Read the file again before retrying. Protection lasts only for the live session and does not survive a workspace restart. If the session last saw no file at a path (a failed `cat` or `test -e`, or its own `rm`), a write there only creates the file and fails if someone else created it first. The S3 family sends `If-None-Match: *` for this; backends that cannot check it write as usual. A rejected write stays rejected until you read the file again, even if the file was deleted. A write to a path the session never read or checked overwrites it, as on a normal filesystem. The shared rewrite helpers and object-store truncate require a file observed missing to remain absent at commit, under either policy. These paths cover append-open and emulated append, positional write, and nonzero truncate. A competing creation is refused without replacing its bytes. A backend that cannot enforce create-only returns an unsupported-operation error. Ordinary replacement and zero-length truncate retain the selected write policy. Backend-specific native truncate implementations outside these shared paths retain their existing concurrency behavior. Conditional appends may refuse a competing update. Conflicts return an error without retrying the append or rerunning the command. Existing-file appends under `unconditional` remain last-write-wins. ### S3-compatible stores On AWS S3 and the provider VFSes built on it (R2, GCS, Wasabi and the rest), a conditional mount conditions writes, copies and deletes; a provider that ignores a copy or delete condition runs it unconditioned. MinIO, and the `s3` VFS pointed at a non-AWS endpoint, condition only writes, so they refuse what would copy or delete within the mount (`cp`, `mv`, `rm`, `find -delete`) with `ENOTSUP`. A TypeScript browser mount signed by presigned URLs cannot declare `write: conditional`. `read: pinned` and `write: staged` are reserved names. A mount that declares either is refused when it mounts. ## CLI entries Each `clis` key is the command name the CLI installs under. An entry takes exactly one of `cli` or `script`: | Key | Purpose | | - | - | | `cli` | A registered CLI, such as `slack`. | | `script` | A `.py`, `.js` or `.mjs` program file, read when the config loads. | | `runtime` | The runtime entry that runs `script`. Unset runs it on the runtime that would run `python3`, or `node` for JavaScript, on the same line, including a `route_policy` choice. Only valid with `script`. | | `config` | Fields the CLI validates at install time. | ```yaml theme={null} clis: slack: cli: slack config: token: ${SLACK_TOKEN} pager: script: pager.py runtime: monty ``` A `script` entry's `config` cannot hold a credential pointer. Read the credential from a managed `env` entry instead. ## Cache, index and store Each block takes a `type`, and the other keys depend on it. A `redis` type defaults `url` to `redis://localhost:6379/0`. `cache` holds file content. `type` is `ram` (default) or `redis`. | Key | Default | Purpose | | - | - | - | | `limit` | `32MB`, `512MB` on Redis | Cache size, as a [size](#sizes). | | `max_drain_bytes` | 8 MiB or `limit`, whichever is smaller | Largest file a streamed read copies into the cache. Cannot exceed `limit`. | | `url`, `key_prefix` | the workspace's own keys | Redis only. Name one `key_prefix` in several workspaces to share their cache. | `index` holds directory listings and file metadata. `type` is `ram` (default) or `redis`. A mount's own `index` replaces this block. | Key | Default | Purpose | | - | - | - | | `ttl` | `600` | Seconds a listing stays cached. | | `url`, `key_prefix` | the workspace's own keys | Redis only. Name one `key_prefix` in several workspaces to share their index. | `store` holds workspace state: symlinks and file attributes, command history, sessions, and background jobs with their output. `type` is `ram` (default), `disk` or `redis`, and sets the backend for all of them; each group key below moves one part to a backend of its own. | Key | Default | Purpose | | - | - | - | | `root` | `~/.mirage/state` | Disk only. The state directory. | | `url`, `key_prefix` | `mirage:` | Redis only. | | `namespace` | unset | A separate store block for symlinks and file attributes. | | `observer` | unset | A separate store block for command history. | | `workspace` | unset | A separate store block for sessions and workspace metadata. | | `execution` | unset | A separate store block for background jobs: each session's job list and each job's output, the processes the workspace runs and which instance runs them. | A group block takes the same keys with `type` `ram`, `disk` or `redis`. Only `workspace` also accepts `s3`, which takes the [S3 config fields](/home/setup/s3) with `key_prefix` defaulting to `mirage/`. `execution` takes `ram` or `redis` only, and a `disk` store keeps its jobs in memory. Redis keeps a job's output for a day after its last write. Processes that build one workspace on a shared store are instances of it, and one of them runs its lines at a time, as described in [Shell](/home/core/shell#jobs-across-instances). [Infrastructure](/home/infrastructure/overview) shows each block in YAML, Python and TypeScript. ```yaml theme={null} store: type: redis url: redis://localhost:6379/0 workspace: type: s3 bucket: my-mirage-state ``` ## Environment and credential pointers A string sets a literal exported variable. A pointer fetches a credential instead of storing its value in YAML: ```yaml theme={null} env: APP_ENV: production API_TOKEN: from: env readonly: true ``` Here `API_TOKEN` comes from the Mirage process environment. Managed entries default `key` to the variable's name and are always exported. `readonly` prevents shell assignment and `unset`. Fetching is lazy on first reference; `fetch: eager` requests it before execution even when the line does not name it. Pointers inside mount or registered CLI configs require an explicit `key` and are resolved before the provider is constructed. See [Service credentials](/home/authentication) for `from`, `ref` and `key` examples. ## Values and paths `${NAME}` placeholders are substituted from the host process environment when the config loads. `NAME` is uppercase letters, digits and underscores, not starting with a digit; any other `${...}` is left as written. A missing variable is an error. Use a credential pointer when the value should be fetched through a source instead. A config posted to a server is taken as written: `mirage workspace create` substitutes from your shell first, and the server never substitutes from its own environment. Relative script paths and file-based code references resolve from the config file's directory. Relative dotenv paths resolve from the Mirage process's working directory. ## Sizes A size is a number of bytes, optionally followed by `K`, `M` or `G` and an optional `B`, in any case: `4096`, `512K`, `100MB`, `1g`. The suffixes are binary (`K` is 1024 bytes). Anything else is refused. # Data & Network Source: https://docs.mirage.strukto.ai/home/core/data-network Process JSON, encode data, work with archives, and make HTTP requests. These commands extend [Core Tools](/home/core/tools) with structured data, compression, checksums, HTTP, and language runtimes. Tables list common supported flags. Use `man COMMAND` or `COMMAND --help` for the full reference; unlisted options are not necessarily supported. ## JSON and calculations | Command | Purpose | Common flags | | - | - | - | | `jq` | Query and transform a stream of JSON values | `-c`, `-r`, `-j`, `-n`, `-R`, `-s`, `-e`, `-S`, `-a`, `-f FILE`, `--arg`, `--argjson`, `--rawfile`, `--slurpfile`, `--args`, `--jsonargs`, `--stream`, `--seq`, `--raw-output0`, `--tab`, `--indent` | | `bc` | Evaluate numeric expressions | `-l`, `-q` | | `expr` | Evaluate integer and string expressions | Operators are operands; no command-specific flags | `jq` runs once per JSON value, whether input is JSONL, concatenated documents, or piped output. Use `-s` to collect the stream into an array, and `--arg` / `--argjson` to pass values safely. **Limits:** `jq -C`, `-L`, `--stream-errors`, and `--build-configuration` are unsupported. Input-consuming programs follow the common `input` / `inputs` patterns; partial drains or multiple conditional reads can differ from jq. Halts inside error handling can also differ. ## Encoding and checksums | Command | Purpose | Common flags | | - | - | - | | `base64` | Encode or decode Base64 | `-d`, `-D`, `-w WIDTH`, `-i` | | `iconv` | Convert character encodings | `-f FROM`, `-t TO`, `-c`, `-o FILE`, `-l`, `-s` | | `xxd` | Create or reverse a hex dump | `-r`, `-p`, `-l LENGTH`, `-c COLS`, `-s OFFSET`, `-g BYTES`, `-u` | | `od` | Dump bytes in a chosen format | `-A RADIX`, `-j BYTES`, `-N BYTES`, `-t TYPE`, `-c` | | `md5` | Print an MD5 digest | No command-specific flags | | `md5sum`, `sha1sum`, `sha224sum`, `sha256sum`, `sha384sum`, `sha512sum`, `b2sum` | Generate or verify checksums | `-c`, `-b`, `-t`, `--tag`, `-z`, `--status`, `--quiet`, `--strict`, `--ignore-missing`, `-l BITS` (`b2sum`) | ## Archives and compression | Command | Purpose | Common flags | | - | - | - | | `tar` | Create, extract, or list archives | `-c`, `-x`, `-t`, `-f FILE`, `-C DIR`, `-z`, `-j`, `-J`, `-v`, `-h`, `-O`, `--strip-components`, `--exclude`, `--one-file-system` | | `zip` | Create ZIP archives | `-r`, `-j`, `-q`, `-X`, `-y`, `-x PATTERN` | | `unzip` | Extract, inspect, or test ZIP archives | `-d DIR`, `-o`, `-n`, `-l`, `-p`, `-t`, `-v`, `-q`, `-x PATTERN`, `-Z` | | `gzip` | Compress or decompress gzip data | `-d`, `-k`, `-f`, `-c`, `-q`, `-S SUFFIX`, `-1` through `-9` | | `gunzip` | Decompress or test gzip data | `-k`, `-f`, `-c`, `-t`, `-q`, `-S SUFFIX` | | `zcat` | Read compressed content to stdout | `-f`, `-q`, `-S SUFFIX` | | `zcmp`, `zdiff` | Compare compressed files | The options of `cmp` and `diff` | | `xz`, `unxz` | Compress, decompress, or test `.xz` data | `-z`, `-d`, `-t`, `-k`, `-f`, `-c`, `-q`, `-S SUFFIX`, `-0` through `-9` | | `bzip2`, `bunzip2` | Compress, decompress, or test `.bz2` data | `-z`, `-d`, `-t`, `-k`, `-f`, `-c`, `-q`, `-v`, `-1` through `-9` | | `zgrep` | Search compressed content | `-E`, `-F`, `-P`, `-i`, `-n`, `-v`, `-c`, `-l`, `-o`, `-e`, `-f` | `zegrep` and `zfgrep` invoke `zgrep` with `-E` and `-F` respectively. `uncompress` is `gzip -d`. **Limits:** Archive creation does not traverse descendant mounts, and a mount root cannot be a source for `tar -c` or `zip`. Extracting or writing an archive requires a writable destination. ## HTTP | Command | Purpose | Supported flags | | - | - | - | | `curl` | Send an HTTP request | `-X`, `-H`, `-A`, `-u`, `-b`, `-c`, `-d`, `--data-binary`, `--data-raw`, `--data-urlencode`, `--json`, `-o`, `-D`, `-L`, `-f`, `-s`, `-S`, `-v`, `-i`, `-I`, `-w`, `-m`, `-k`, `-4`, `-6` | | `wget` | Download a URL or check its response | `-O FILE`, `-q`, `-T SECONDS` / `--timeout`, `--spider` | `curl` writes the body to stdout unless `-o` selects a virtual file. `wget` saves to a virtual file; use `-O -` for stdout. Both respect destination mount permissions. **Limits:** These are HTTP tools, with no full curl or Wget option set. Recursive Wget downloads (`-r`, `--mirror`) are unsupported. `curl -4/-6` are accepted, but the host transport chooses the address family. `wget -T` uses one request deadline rather than separate DNS, connect, and read timers; zero disables it. `curl -b` sends cookies from a virtual file, or `NAME=VALUE` as given; `curl -c FILE` saves them after the request, so a login carries across `curl` calls. In the browser no cookies are sent or received, but `-c` still writes its file, so it can replace a saved jar with an empty one. Public suffixes such as `co.uk` are not checked. `curl -F` sends one URL-encoded text field; repeated `-F` keeps only the last field, and `@FILE` is literal text. Multipart file uploads are unsupported. `curl -w` supports `http_code`, `response_code`, `url_effective`, `num_redirects`, `size_download`, `content_type`, `method`, `exitcode`, and `time_total`. Other variables produce a diagnostic. ## Language runtimes For `python`, `python3`, `js`, and `node`, see [Runtimes](/home/setup/runtime/overview) for available engines, configuration, and execution limits. # Command Output Limits Source: https://docs.mirage.strukto.ai/home/core/output-limits Cap command output, execution time, memory and walks at the workspace, mount, or profile level. Mirage keeps large results from flooding an agent. `cat`, `grep`, `rg`, `head`, and `tail` return at most 2,000 lines by default, a line stops after 600 seconds, a workspace holds at most 96 MB in memory, and a walk stops at its mount's `walk_limit`. ## Set Limits Set a workspace default for every session, a mount override for commands that run on that mount, or a profile override for sessions created with that profile. ```python Python theme={null} from mirage import MountMode, Workspace from mirage.types import Limit, OnExceed from mirage.vfs.ram import RAMVFS ws = Workspace( { "/data": (RAMVFS(), MountMode.WRITE, { "grep": Limit(max_lines=50, on_exceed=OnExceed.ERROR), }), }, mode=MountMode.WRITE, command_limits={ "head": Limit(max_lines=500), "@line": Limit(timeout_seconds=30), }, profiles={ "researcher": {"command_limits": {"head": Limit(max_lines=5000)}}, }, ) ws.create_session("research", profile="researcher") ``` ```ts TypeScript theme={null} import { Limit, MountMode, OnExceed, RAMVFS, Workspace } from '@struktoai/mirage-node' const ws = new Workspace( { '/data': [ new RAMVFS(), MountMode.WRITE, { grep: new Limit({ maxLines: 50, onExceed: OnExceed.ERROR }) }, ], }, { mode: MountMode.WRITE, commandLimits: { head: new Limit({ maxLines: 500 }), '@line': new Limit({ timeoutSeconds: 30 }), }, profiles: { researcher: { commandLimits: { head: new Limit({ maxLines: 5000 }) } } }, }, ) ws.createSession('research', { profile: 'researcher' }) ``` The workspace YAML uses the same fields in snake case under `command_limits`. A key is a command's name or one of two groups, spelled with the `@` runtime captures use for theirs: `@all`, every command, and `@line`, the whole line. A YAML key that starts with `@` is quoted (`"@all":`). Any other `@` key, or `*`, is refused when the table is built. ## Choose Which Limit Applies Each field comes from the most specific entry that sets it: the session profile, the mount, then the workspace (each looked up by the command's name, then under `"@all"`, the entry for every command), the command's own default, and Mirage's built-in default; a walk's `walk_limit` ends at the mount backend's default. An entry that sets one field inherits the rest. ## Limit a Line's Time A line has one time limit: the `@line` entry's `timeout_seconds`, on the workspace or a profile (the profile's over the workspace's). It bounds the whole top-level line, loops, pipelines and the lines it runs (`sh -c`, `eval`, `xargs`) included, and is 600 seconds unless an entry sets it; `0` or `None` lifts it. A line past it exits 124 with `line: timed out after Ns`. A program it runs gets `TERM` and a second to finish, then `KILL`, as with `timeout -k`. A background job (`cmd &`) runs under the same limit, counted from its own start. The line that started it can end or time out and leave it running; past its own limit the job ends with status 124 and the same message. `kill` stops it sooner. No other entry takes `timeout_seconds`, an `@line` entry takes nothing else, and a mount has no `@line` entry, since a line spans mounts; each is refused when the workspace, mount or profile is built. To bound one command inside a line, use `timeout`, as in bash: `timeout 5 grep -r TODO /data`. For commands spanning multiple mounts, Mirage applies the tightest resolved limit from those mounts. ## Limit a Workspace's Memory A workspace's `max_memory`, a [size](/home/configuration#sizes), bounds what it holds in memory: the files in its RAM mounts, and each object a command builds while it runs, such as a `$( )` capture, a `read` value, a file read whole, a `jq -s` input or a Monty, Pyodide or QuickJS program's memory. Such an object must fit in what the RAM files leave. It is 96 MB unless the workspace sets it, and `None` (`null` in TypeScript and YAML) lifts it. The read cache keeps its own [limit](/home/configuration#cache-index-and-store). Commands running at the same moment can each take close to what is left, so it bounds each object, not their sum. ```python Python theme={null} ws = Workspace({"/": RAMVFS()}, mode=MountMode.WRITE, max_memory="64MB") ``` ```ts TypeScript theme={null} const ws = new Workspace({ '/': new RAMVFS() }, { mode: MountMode.WRITE, maxMemory: '64MB' }) ``` ```yaml YAML theme={null} max_memory: 64MB ``` A write that would pass it fails with `Disk quota exceeded`. A command whose own object passes it fails with `: memory exhausted` and the line goes on; when a capture or a `read` passes it, the line ends with `line: memory exhausted` and exit 1. A `python3` run raises `MemoryError`, and a `node` run gets `InternalError: out of memory`. ## Handle a Reached Limit * `max_lines` and `max_bytes` cap output. Use `None` in Python or `null` in TypeScript for no cap. * `timeout_seconds`, on the `@line` entry only, sets the deadline of a line and of each background job. A line or job that passes it exits 124. * `walk_limit` caps the entries one walk lists on a mount, `-1` for no cap; see [walks](/home/integration/walks). * `on_exceed=TRUNCATE`, the default, returns the capped output, writes a notice to stderr, and preserves the command's exit code. * `on_exceed=ERROR` drops the output and exits 1, so `&&` and `||` see a failure. In TypeScript, use the camel-case forms `maxLines`, `maxBytes`, `timeoutSeconds`, `walkLimit`, and `onExceed`. Caps apply to each command's printed output. `cat big.txt; echo end` still prints `end`. Input to a pipe, redirect, or command substitution is not cut, so `cat big.txt | wc -l` counts every line. # Mirage shell Source: https://docs.mirage.strukto.ai/home/core/shell Run Bash-style commands, pipelines, and scripts across your mounted data. Mirage's shell combines commands from [Core Tools](/home/core/tools) and [Data & Network](/home/core/data-network) with variables, control flow, and persistent sessions. ## Syntax | Feature | Supported | | - | - | | Command lists | `;`, newlines, `&&`, `\|\|`, and `!` | | Pipelines | `\|` and `\|&`; `$?` and `${PIPESTATUS[@]}` report exit statuses | | Redirection | `>`, `>>`, `<`, `<>`, `>\|`, `2>`, `2>&1`, `&>`, `&>>`; descriptor duplication and closing | | Inline input | Here-documents `<(command)` as live `/dev/fd/N` pipes, streamed both ways | | Background work | `command &`, `jobs`, `wait`, `kill`, `disown`, and `ps` | | Timing | `time`, `time -p`, and `TIMEFORMAT`; CPU times are reported as zero | | Comments | `#` outside quotes | ## Shell commands These are common options, not an exhaustive flag reference. | Commands | Purpose and common options | | - | - | | `cd`, `pwd` | Change or print the working directory; `-L`, `-P` | | `export`, `unset` | Export variables or functions (`export -f`); remove variables or functions (`unset -v`, `-f`) | | `declare`, `typeset`, `local`, `readonly` | Set variable scope and attributes; arrays `-a` / `-A`, integers `-i`, readonly `-r`, export `-x` | | `set` | Set positional arguments and options such as `-e`, `-u`, `-x`, `-f`, `-C`, and `-o pipefail` | | `shopt` | Set, unset, print, or query options with `-s`, `-u`, `-p`, `-q`; `-o` selects `set` options | | `alias`, `unalias` | Define or remove aliases; enable expansion with `shopt -s expand_aliases` | | `read` | Read into variables; `-r`, `-a ARRAY`, `-d CHAR`, `-n N`, `-N N`, `-u FD` | | `mapfile`, `readarray` | Read into an array; `-t`, `-d CHAR`, `-n N`, `-s N`, `-O INDEX`, `-u FD`, `-C CALLBACK`, `-c N` | | `echo`, `printf` | Print text or formatted values; `echo -n/-e/-E`, `printf -v NAME` | | `source`, `.`, `eval` | Run a file or command string in the current session | | `bash`, `sh` | Run a script, `-c COMMAND`, or stdin with `-s` in a fresh shell environment | | `exec` | Replace the current shell command flow, or keep descriptor redirections; `-c` clears the command's environment | | `getopts`, `shift`, `let` | Parse script options, shift positional arguments, or evaluate integer expressions | | `trap` | Run actions on `EXIT`, `ERR`, and `RETURN` | | `umask` | Read or set the creation mask; `-S` prints symbolic form | | `command`, `type`, `which` | Run or locate a command; `command -v/-V`, `type -t/-a/-p/-P` | | `true`, `false`, `:` | Return success or failure; `:` is a no-op | | `exit` | End the current shell with an optional exit status | | `history` | Read or manage command history; `-c`, `-d`, `-s`, `-p`, `-a`, `-r`, `-w`, `-n` | | `help` | Show help for a shell builtin: `help`, `help cd` | | `man` | Show command help, including registered CLI subcommands: `man ls`, `man linear issue create` | ## Sessions and permissions `ws.shell(...)` keeps the session's working directory, variables, and functions between calls. Supplying `cwd` or `env` uses an isolated copy for that call. Calls on one session run in order; use separate sessions for concurrent command streams. Python accepts a cancellation event through `cancel`; TypeScript accepts an abort `signal`. ### Jobs across instances A workspace runs as several instances when more than one process builds it under the same `workspace_id` on one shared [store](/home/configuration#cache-index-and-store), as [Infrastructure](/home/infrastructure/jobs#several-instances-of-one-workspace) shows. One of them runs its lines at a time, the first to run one; a line on any other is refused with an error naming it until it closes the workspace. Process IDs continue from the highest the workspace has used, so an instance that takes over never reuses one. If the running instance goes away without closing the workspace, another can run its lines about 30 seconds later. It reports the jobs left behind as ended with status 129, as Bash reports a hangup, and stops what they ran outside Mirage: a sandbox program through a runtime on the same machine, or a host program on the same machine whose PID still matches. A program a runtime runs outside Mirage is a process of its own. `ps` shows its real pid and the machine it runs on, a host program's host PID or a [machine](/home/setup/machine/overview#processes-and-jobs)'s. Mirage's own commands show `mirage`: ``` PID MACHINE CMD 4194305 mirage ps 4194306 mirage sleep 300 19443 host:my-laptop python3 train.py ``` Mirage's pids start at 4194305, past any Linux pid, so `$!`, `kill`, `wait` and `ps -p` take either kind. ### Per-session mount modes Session mount modes can narrow access to `read`, `write`, or `exec` (`r`, `rw`, `rwx`). Unlisted mounts keep their configured modes. Interpreters such as `python3` and `js` require `exec`; shell scripts run with the permissions of each command they contain. Use an [agent profile](/home/profiles) to hide paths or restrict commands. ## Limits * Positive `read -t` values are accepted but do not enforce a timeout. * `bg`, `complete`, `compgen`, `ulimit`, `coproc`, and `exec -a/-l` are not implemented. * A process substitution lives as long as the command naming it, which waits for its output consumers; `exec` onto one (`exec 3> >(command)`) fails with exit status `2`. Its `/dev/fd/N` paths are Mirage pipes, not host descriptors. * There is no interactive terminal or OS process job control. The supported job commands manage Mirage jobs: `cmd &`, `jobs`, `wait` and `kill`. * `kill` takes every Linux signal `kill -l` lists, by name or number. `STOP` pauses a job, which `ps` shows as `T`, and `CONT` lets it go on; a `TERM` sent meanwhile waits for the `CONT`. A Mirage command pauses at its next file operation, pipe write, sleep or loop turn, and in a browser `STOP` of one is refused. A Monty or Pyodide program pauses where it is, and a QuickJS or WASI program at its next file operation or output. Any other signal whose default is to be ignored or to pause a process (`CHLD`, `URG`, `WINCH`, `TSTP`, `TTIN`, `TTOU`) succeeds and changes nothing. A Pyodide program gets the signal as sent too, as does a program a runtime started on a machine or on the host: one that handles it runs on, and the job ends when the program exits, with its status. `KILL` is sent only for `kill -9`, `timeout -k`, or when the workspace shuts down. Any other process stops, and `wait` reports 128 plus the signal, as in Bash. As in Bash, a background job ignores `INT` and `QUIT`. Unlike Bash, `kill` also stops the jobs a job started and theirs, even once the job between them has ended. * Every line of a session runs as one shell process, `$$`, which leads the session's process group; its jobs, pipeline stages, subshells, command substitutions and nested shells are in it. A negative operand signals a whole group (`kill -TERM -- -$$`). A signal that stops `$$` ends the line with 128 plus the signal and leaves its jobs running. As in Bash, a shell ignores `QUIT`, which stops only the program it is running. A nested `bash -c` is a process of its own, with its own `$$`. * The shell's own errors start as a non-interactive Bash's do, `bash: line N: `, with `environment` in place of `bash` inside a function and the file's path inside a sourced file or a script. `$LINENO` is the running command's line and `$BASHPID` the process running it. When a signal ends a command, the shell prints Bash's report line after it, such as `bash: line 1: 12 Killed sleep 3`; for a background job, after the next program, subshell or pipeline it runs, or at `wait`. `TERM` prints `Terminated` for a command and nothing for a job, and `INT` and `PIPE` print nothing. A program a runtime runs in the foreground is not a process of its own, so no report line follows when a signal ends it; its status is still 128 plus the signal. A command substitution reports nothing. * A program a sandbox runs, or one the `local` runtime captures besides its own `python3`, writes its output and its stderr into a redirect's file as it prints them. So do most of Mirage's commands, such as `cat`, `grep`, `awk`, `sed`, `tee`, `sort` and `jq`, and the commands in a group, a loop or a function (`{ echo a; sleep 9; } > f`). A command that reads or changes that file meanwhile finds what was written before it, and `cat` and `grep` refuse to read the file their own output goes to, as GNU's do. The output follows the file through a rename the line makes, and the rest is lost once the line removes it or renames another file over it, as in Bash; a rename made from another session or through FUSE is not followed. What a stopped command wrote stays in the file, whether `kill`, `timeout` or a cancelled call stopped it. Others, such as `tar`, `gzip` and the `local` runtime's `python3`, write theirs when they end, as do a program a Daytona sandbox runs and a microsandbox program given piped input. A file on a RAM mount shows a streaming write within a tenth of a second; an object store such as S3 publishes it when the write ends. * `set` and `shopt` recognize more option names than they implement; accepting or displaying an option does not mean every Bash behavior is available. * Enable `extglob` before the call that uses its syntax, or use `eval` after enabling it. A whole `shell()` call is parsed before it runs. * Command substitutions and background jobs do not inherit stdin. Writes through an already open output descriptor append rather than track a write offset. * Syntax errors return exit status `2`. Compatibility is a supported subset of Bash, not a full Bash installation. # Core Tools Source: https://docs.mirage.strukto.ai/home/core/tools Inspect, edit, search, and transform files with familiar command-line tools. Mirage provides familiar Unix-style commands over virtual paths, with availability determined by the mount's capabilities and your session's permissions. Tables list common supported flags; use `man COMMAND` or `COMMAND --help` for the full command reference. Compatibility varies by command, so a familiar name does not imply every option from the original program. ## Files and directories | Command | Purpose | Common flags | | - | - | - | | `ls` | List entries | `-l`, `-a`, `-A`, `-h`, `-R`, `-d`, `-t`, `-S`, `-r`, `-F`, `-L`, `--sort`, `--zero`, `--author`, `-D` | | `dir`, `vdir` | `ls` in columns or in long format, with names escaped | The options of `ls` | | `stat` | Show metadata | `-c FORMAT`, `-f`, `-L` | | `tree` | Show a directory tree | `-a`, `-d`, `-l`, `-L DEPTH`, `-I PATTERN`, `-P PATTERN`, `-x`, `-Q`, `-N`, `-q`, `-A`, `-u`, `-g`, `-c`, `-o FILE`, `--si`, `--timefmt`, `--filesfirst`, `--ignore-case`, `--matchdirs`, `--inodes` | | `du` | Count file and directory bytes | `-h`, `-s`, `-a`, `-d DEPTH`, `-c`, `-L`, `-S`, `-x`, `--files0-from FILE` | | `df` | Show mount capacity, when available | `-h`, `-H`, `-k`, `-i`, `-a`, `-T`, `-P`, `-B SIZE` | | `mount` | List configured mounts | `-l`, `-t TYPES` | | `file` | Identify content type | `-b`, `-i`, `-L`, `-h` | | `mkdir` | Create directories | `-p`, `-v`, `-m MODE` | | `touch` | Create files or update timestamps | `-a`, `-m`, `-c`, `-d DATE`, `-r FILE`, `-t TIME`, `-h` | | `cp` | Copy files or directories, including across mounts | `-r`, `-R`, `-a`, `-L`, `-P`, `-n`, `-u`, `-v`, `-t DIR`, `-T`, `-b`, `-x`, `--debug` | | `mv` | Move or rename entries | `-f`, `-n`, `-u`, `-v`, `-t DIR`, `-T`, `-b`, `--no-copy`, `--exchange` | | `rm` | Remove entries | `-r`, `-R`, `-f`, `-v`, `-d`, `--one-file-system` | | `rmdir` | Remove empty directories | `-p`, `-v`, `--ignore-fail-on-non-empty` | | `unlink` | Remove one entry | No command-specific flags | | `truncate` | Resize a file | `-s SIZE`, `-c`, `-o` | | `mktemp` | Create a temporary file or directory | `-d`, `-p DIR`, `--tmpdir`, `--suffix`, `-u`, `-q` | | `ln` | Create a symbolic link or copy a file's bytes | `-s`, `-r`, `-f`, `-n`, `-t DIR`, `-T`, `-b` | | `link` | Copy a file's bytes to a new name | No command-specific flags | | `pathchk` | Check that names are valid or portable | `-p`, `-P`, `--portability` | | `readlink` | Read a link or resolve its target | `-f`, `-e`, `-m`, `-n`, `-z` | | `realpath` | Resolve a path | `-e`, `-m`, `-L`, `-P`, `-s`, `--relative-to`, `--relative-base`, `-z` | | `basename` | Remove a directory prefix or suffix | `-a`, `-s SUFFIX`, `-z` | | `dirname` | Print the parent path | `-z` | | `chmod` | Set permission metadata | `-R`, `-c`, `-f`, `-v` | | `chown`, `chgrp` | Set owner or group metadata | `-R`, `-c`, `-f`, `-v`, `-h`, `--dereference` | | `getfattr` | Read extended attributes | `-n NAME`, `-d`, `-m PATTERN`, `-e ENCODING`, `--only-values`, `-R` | | `setfattr` | Set or remove an extended attribute | `-n NAME`, `-v VALUE`, `-x NAME`, `-h` | ## Search and compare | Command | Purpose | Common flags | | - | - | - | | `find` | Select paths and run actions | `-name`, `-iname`, `-path`, `-type`, `-size`, `-mtime`, `-newer`, `-anewer`, `-cnewer`, `-newermt`, `-used`, `-inum`, `-fstype`, `-fls`, `-empty`, `-mindepth`, `-maxdepth`, `-print0`, `-printf`, `-delete`, `-exec`, `-prune`, `-ls`, `-L`, `-xdev` | | `grep` | Search lines | `-E`, `-F`, `-G`, `-P`, `-i`, `-v`, `-n`, `-r`, `-R`, `-l`, `-c`, `-o`, `-q`, `-e`, `-f`, `-A`, `-B`, `-C`, `--include`, `--exclude` | | `rg` | Search recursively with path filters | `-i`, `-S`, `-F`, `-n`, `-l`, `-c`, `-g`, `-t`, `-T`, `--hidden`, `--files`, `--json`, `-U`, `-P`, `-z`, `--pre` | | `search` | Search through a backend's search capability | `--method`, `--top-k`, `--threshold` | | `diff` | Compare text files or directory trees | `-u`, `-U N`, `-q`, `-r`, `-N`, `-i`, `-w`, `-b`, `-x`, `-X` | | `cmp` | Compare bytes | `-s`, `-l`, `-b`, `-n N`, `-i SKIP` | | `patch` | Apply a patch | `-p N`, `-R`, `-i FILE`, `-N` | | `look` | Find lines with a prefix | `-f` | `egrep`, `fgrep` and `rgrep` invoke `grep` with `-E`, `-F` and `-r` respectively. `zcmp` and `zdiff` compare gzip files with `cmp` and `diff`. Compressed-file search is covered under [Data & Network](/home/core/data-network#archives-and-compression). ## Text processing | Command | Purpose | Common flags | | - | - | - | | `cat` | Read and concatenate files | `-n`, `-b`, `-s`, `-v`, `-E`, `-T`, `-A` | | `head` | Read the beginning | `-n N`, `-c N`, `-q`, `-v`, `-z` | | `tail` | Read the end or follow changes | `-n N`, `-c N`, `-q`, `-v`, `-f`, `-F`, `--retry`, `-s SECONDS` | | `wc` | Count lines, words, bytes, or characters | `-l`, `-w`, `-c`, `-m`, `-L`, `--total` | | `sort` | Order lines | `-n`, `-r`, `-u`, `-k KEY`, `-t CHAR`, `-h`, `-V`, `-s`, `-f`, `-c`, `-m`, `-o FILE`, `-z` | | `uniq` | Filter adjacent repeated lines | `-c`, `-d`, `-u`, `-i`, `-f N`, `-s N`, `-w N`, `-z` | | `cut` | Select fields, bytes, or characters | `-f LIST`, `-d CHAR`, `-b LIST`, `-c LIST`, `--complement`, `--output-delimiter`, `-s`, `-z` | | `tr` | Translate, delete, or squeeze characters | `-d`, `-s`, `-c`, `-C`, `-t` | | `sed` | Edit a text stream | `-e SCRIPT`, `-f FILE`, `-n`, `-E`, `-r`, `-i`, `-s`, `-l WIDTH` | | `awk` | Process records and fields | `-F SEPARATOR`, `-v NAME=VALUE`, `-f FILE` | | `tee` | Copy stdin to stdout and files | `-a`, `-i`, `-p`, `--output-error` | | `paste` | Combine lines into columns | `-d DELIMITERS`, `-s`, `-z` | | `join` | Join sorted files on a field | `-1 FIELD`, `-2 FIELD`, `-t CHAR`, `-a`, `-v`, `-e`, `-o`, `-i`, `--header`, `-z` | | `comm` | Compare sorted lines | `-1`, `-2`, `-3`, `--check-order`, `--total`, `-z` | | `split` | Split input into files | `-l N`, `-b SIZE`, `-n CHUNKS`, `-d`, `-x`, `-a N`, `--additional-suffix` | | `csplit` | Split at line numbers or patterns | `-f PREFIX`, `-n DIGITS`, `-b FORMAT`, `-k`, `-s`, `-z` | | `nl` | Number lines | `-b STYLE`, `-n FORMAT`, `-s STRING`, `-w WIDTH`, `-v START`, `-i STEP` | | `tac` | Reverse record order | `-b`, `-r`, `-s SEPARATOR` | | `rev` | Reverse characters in each line | No command-specific flags | | `column` | Arrange text into columns | `-t`, `-s SEPARATORS`, `-o SEPARATOR` | | `fold` | Wrap long lines | `-w WIDTH`, `-s`, `-b`, `-c` | | `fmt` | Reflow paragraphs | `-w WIDTH`, `-g GOAL`, `-c`, `-p PREFIX`, `-s`, `-t`, `-u` | | `expand`, `unexpand` | Convert tabs and spaces | `-t TABS`; `expand -i`; `unexpand -a`, `--first-only` | | `strings` | Extract printable strings | `-n LENGTH` | | `seq` | Generate a number sequence | `-s SEPARATOR`, `-w`, `-f FORMAT` | | `shuf` | Shuffle or sample lines | `-n N`, `-e`, `-r`, `-i RANGE`, `-o FILE`, `-z` | | `tsort` | Sort dependency pairs | No command-specific flags | | `colrm` | Remove columns from each line | `START`, `STOP` | | `envsubst` | Fill environment variables into text | `-v`, `SHELL-FORMAT` | | `yes` | Repeat a line until the reader stops | `STRING` | | `numfmt` | Convert numeric units | `--from`, `--to`, `--suffix`, `--grouping` | ## Running commands and inspecting the environment | Command | Purpose | Common options | | - | - | - | | `xargs` | Build commands from input | `-0`, `-d CHAR`, `-I STRING`, `-n N`, `-L N`, `-s BYTES`, `-P N`, `-r`, `-a FILE`, `-t`, `--process-slot-var` | | `timeout` | Limit a command's running time | `-s SIGNAL`, `-k DURATION`, `-p`, `-f`, `-v` | | `nohup`, `nice`, `stdbuf`, `setsid` | Run a command with no change to how it runs here | `nice -n N`, `stdbuf -i/-o/-e MODE`, `setsid -w/-f` | | `sleep` | Wait for a duration | Numbers with `s`, `m`, `h`, or `d` suffixes | | `env`, `printenv` | Run with environment changes or print exported variables | `env -i`, `-u NAME`, `NAME=VALUE`; `printenv NAME` | | `date` | Format a date or time | `-d DATE`, `-u`, `-I`, `-R`, `--rfc-3339`, `+FORMAT` | | `uname`, `hostname`, `arch`, `hostid`, `nproc` | Report system or host information | `uname -a/-s/-r/-m`; `hostname -s/-f/-d/-i`; `nproc --all`, `--ignore=N` | | `id`, `whoami`, `groups`, `logname`, `users`, `who` | Report identity: the session's profile is its user and group, and nobody logs in | `id -u/-g/-G/-n/-r/-z`; `whoami`; `who -q`, `-H` | | `tty`, `sync` | Report that there is no terminal, or check that files exist | `tty -s`; `sync -d`, `-f` | | `getconf` | Query configuration values | `-a`, `-v SPECIFICATION` | ## Limits * `rm -i` and `-I` are accepted but ignored; deletion does not prompt for confirmation. * File operations depend on the backend; a read-only mount cannot accept writes. Permission and owner metadata may live in Mirage's overlay rather than the remote service. * Mount roots are protected from removal, renaming, and use as copy sources. `mount` lists configured mounts; it does not attach new backends. * `ln -s` creates a virtual symlink. Without `-s`, a regular file is copied; there is no shared hard-link inode. * `find` supports `-a`, `-o`, `!`, parentheses, and both `-exec ... \;` and `-exec ... {} +`. Tests must precede actions in each AND chain, and OR branches must use the same action. `-newer` and `-newermt` must be in a top-level AND chain. `-execdir` and `-ok` are unsupported. * `rg` cannot sort by creation time. `ls --color` and `grep --color` are accepted without colored output. * Under a UTF-8 locale, `sed`, `grep`, `expr`, `nl`, `[[ =~ ]]` and `git`'s filters match whole characters. A pattern byte that is only part of one, such as `\xa9` against `é` (bytes `C3 A9`), matches nothing there, where Linux's `sed` can match it inside the character. * In rare patterns, `sed`, `expr` and `[[ =~ ]]` capture different text in a group than Linux does, or find a match where Linux finds none. Such a pattern repeats a group that holds an anchor (`^`, `$`, `\b`, `\<`, `\>`) or can match nothing, or refers back to one. For example, `[[ ab =~ (a|b|$){1,3} ]]` leaves `BASH_REMATCH[1]` empty where Linux sets it to `b`, and `echo babc | sed 's/\(\<[a-][ab]\|[a-c]\)\{2\}/<&>/'` prints `bc` where Linux prints `babc`. * `getconf -a` lists the same variables and values as Linux, in the order of POSIX's tables rather than the C library's. * `xargs -p` and `-o` fail because there is no terminal. `timeout` signals its command as `kill` does, so a program can handle the signal; a Mirage command cannot trap one. # Embedded Terminal Source: https://docs.mirage.strukto.ai/home/examples/embedded-terminal A lightweight terminal inside a FastAPI or Express server, with Python on Monty and no container. Most of the time an agent does not need a sandbox, only a terminal-like interface. An embedded terminal runs inside an application server. Each terminal is a Mirage session with its own working directory, environment and history, and [Monty](/home/setup/runtime/monty) runs Python in-process, so a terminal starts with no container or VM. Mirage is async native, so one server process runs many terminals at once on its event loop. ## Installation > [tab] FastAPI > > ```bash theme={null} > pip install 'mirage-ai[monty]' fastapi uvicorn > ``` > [tab] Express > > ```bash theme={null} > npm install @struktoai/mirage-node @pydantic/monty express > ``` ## Server One endpoint creates a session, another runs a command line in it. > [tab] FastAPI > > ```python app.py theme={null} > from contextlib import asynccontextmanager > > from fastapi import FastAPI > from pydantic import BaseModel > > from mirage import RAMVFS, MountMode, Workspace > from mirage.runtime.python.monty import MontyRuntime > > ws = Workspace( > {"/work": (RAMVFS(), MountMode.EXEC)}, > runtimes=[MontyRuntime(captures=["python", "python3"])], > ) > > > @asynccontextmanager > async def lifespan(app: FastAPI): > yield > await ws.close() > > > app = FastAPI(lifespan=lifespan) > > > class Run(BaseModel): > command: str > > > @app.post("/sessions/{session_id}") > async def create(session_id: str) -> None: > ws.create_session(session_id) > > > @app.post("/sessions/{session_id}/run") > async def run(session_id: str, body: Run) -> dict: > r = await ws.shell(body.command, session_id=session_id) > return {"stdout": await r.stdout_str(), "stderr": await r.stderr_str(), "exit_code": r.exit_code} > ``` > > ```bash theme={null} > uvicorn app:app --port 3000 > ``` > [tab] Express > > ```typescript app.mjs theme={null} > import express from 'express' > import { MontyRuntime, MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node' > > const ws = new Workspace( > { '/work': new RAMVFS() }, > { mode: MountMode.EXEC, runtimes: [new MontyRuntime({ captures: ['python', 'python3'] })] }, > ) > const app = express() > app.use(express.json()) > > app.post('/sessions/:id', (req, res) => { > ws.createSession(req.params.id) > res.sendStatus(201) > }) > > app.post('/sessions/:id/run', async (req, res) => { > const r = await ws.shell(req.body.command, { sessionId: req.params.id }) > res.json({ stdout: r.stdoutText, stderr: r.stderrText, exitCode: r.exitCode }) > }) > > app.listen(3000, '127.0.0.1') > ``` > > ```bash theme={null} > node app.mjs > ``` ## Usage ```bash theme={null} curl -X POST localhost:3000/sessions/a curl -X POST localhost:3000/sessions/a/run -H 'content-type: application/json' \ -d '{"command": "cd /work && echo \"print(sum(range(10)))\" > s.py && python3 s.py"}' ``` The run prints `45`. A later call to session `a` starts in `/work`, where the `cd` left it. * Sessions share the workspace's mounts, so a file one writes under `/work` is visible to the others. Give each session its own directory, or its own workspace, to keep files apart. * Monty supports a subset of Python and has no network or host access. For more, see [Hybrid Terminal](#hybrid-terminal). * The server runs any line for any caller that names a session. Put authentication and a check that the caller owns the session in front of it before it listens beyond localhost. ## Async `ws.shell` is a coroutine in Python and a promise in TypeScript, and it never blocks the event loop. The handlers above are `async`, so while one terminal waits on a file read, a runtime or a slow command, the server keeps serving every other terminal, with no thread or process per terminal. > [tab] Python > > ```python theme={null} > import asyncio > > for sid in ["a", "b", "c"]: > ws.create_session(sid) > await asyncio.gather(*(ws.shell("sleep 1", session_id=sid) for sid in ["a", "b", "c"])) > ``` > [tab] TypeScript > > ```typescript theme={null} > for (const sid of ['a', 'b', 'c']) ws.createSession(sid) > await Promise.all(['a', 'b', 'c'].map((sid) => ws.shell('sleep 1', { sessionId: sid }))) > ``` The three lines finish together in about a second; 20 sessions take the same. Within one session, lines run one after another in order, as in a real terminal, so three `sleep 1` lines on session `a` take three seconds. ## Hybrid Terminal A hybrid terminal keeps light Python on Monty and sends the rest to a Docker container: lines that use `numpy` or `pandas` by route policy, and every program Mirage does not have itself, such as `ffmpeg`, by `@external`. Redis holds the files, sessions, jobs and processes, so a terminal outlives the server process that runs it. | Line | Runs on | | - | - | | `cat`, `grep`, pipes, redirects | Mirage | | `python3 s.py` | Monty | | `python3 -c 'import numpy; ...'` | Docker, by the route policy | | `ffmpeg -i in.mp4 out.gif` | Docker, by `@external` | Build the container's image with `sshfs`, which serves the workspace into it, and the programs the lines need, and start Redis: ```dockerfile Dockerfile theme={null} FROM python:3.12-slim RUN apt-get update \ && apt-get install -y --no-install-recommends sshfs ffmpeg \ && rm -rf /var/lib/apt/lists/* \ && pip install --no-cache-dir numpy pandas ``` ```bash theme={null} docker build -t mirage-box . docker run -d --name redis -p 6379:6379 redis ``` A container serves one session, so each terminal gets a workspace and a container of its own. The server starts the container when it creates the terminal: > [tab] FastAPI > > ```bash theme={null} > pip install 'mirage-ai[monty,redis,ssh]' fastapi uvicorn > ``` > > ```python app.py theme={null} > import asyncio > import re > from contextlib import asynccontextmanager > > from fastapi import FastAPI, HTTPException > from pydantic import BaseModel > > from mirage import MountMode, Workspace > from mirage.runtime.machine import RemoteRuntime > from mirage.runtime.python.monty import MontyRuntime > from mirage.vfs.redis import RedisVFS > from mirage.workspace.store import RedisWorkspaceStateStore > > REDIS_URL = "redis://localhost:6379/0" > terminals: dict[str, Workspace] = {} > > > def terminal(terminal_id: str) -> Workspace: > if terminal_id not in terminals: > terminals[terminal_id] = Workspace( > {"/work": RedisVFS(url=REDIS_URL)}, > mode=MountMode.EXEC, > workspace_id=terminal_id, > store=RedisWorkspaceStateStore(url=REDIS_URL), > owns_store=True, > machines={ > "box": { > "provider": "docker", > "container": f"box-{terminal_id}", > "mount_type": "ssh", > } > }, > runtimes=[ > MontyRuntime(captures=["python", "python3"]), > RemoteRuntime(["@python", "@external"], machine="box"), > ], > route_policy=lambda ctx: "remote" if re.search(r"\b(numpy|pandas)\b", ctx.line) else None, > ) > return terminals[terminal_id] > > > @asynccontextmanager > async def lifespan(app: FastAPI): > yield > for ws in terminals.values(): > await ws.close() > > > app = FastAPI(lifespan=lifespan) > > > class Run(BaseModel): > command: str > > > @app.post("/sessions/{session_id}") > async def create(session_id: str) -> None: > docker = await asyncio.create_subprocess_exec( > "docker", "run", "-d", "--cap-add", "SYS_ADMIN", "--device", "/dev/fuse", > "--name", f"box-{session_id}", "mirage-box", "sleep", "infinity", > ) > if await docker.wait() != 0: > raise HTTPException(500, "could not start the terminal's container") > terminal(session_id).create_session(session_id) > > > @app.post("/sessions/{session_id}/run") > async def run(session_id: str, body: Run) -> dict: > r = await terminal(session_id).shell(body.command, session_id=session_id) > return {"stdout": await r.stdout_str(), "stderr": await r.stderr_str(), "exit_code": r.exit_code} > ``` > [tab] Express > > ```bash theme={null} > npm install @struktoai/mirage-node @pydantic/monty redis ssh2 express > ``` > > ```typescript app.mjs theme={null} > import { execFile } from 'node:child_process' > import { promisify } from 'node:util' > import express from 'express' > import { > MontyRuntime, > MountMode, > RemoteRuntime, > RedisVFS, > RedisWorkspaceStateStore, > Workspace, > } from '@struktoai/mirage-node' > > const redisUrl = 'redis://localhost:6379/0' > const terminals = new Map() > > function terminal(id) { > if (!terminals.has(id)) { > terminals.set( > id, > new Workspace( > { '/work': new RedisVFS({ url: redisUrl }) }, > { > mode: MountMode.EXEC, > workspaceId: id, > store: new RedisWorkspaceStateStore({ url: redisUrl }), > ownsStore: true, > machines: { > box: { provider: 'docker', container: `box-${id}`, mountType: 'ssh' }, > }, > runtimes: [ > new MontyRuntime({ captures: ['python', 'python3'] }), > new RemoteRuntime({ captures: ['@python', '@external'], machine: 'box' }), > ], > routePolicy: (ctx) => (/\b(numpy|pandas)\b/.test(ctx.line) ? 'remote' : null), > }, > ), > ) > } > return terminals.get(id) > } > > const app = express() > app.use(express.json()) > > app.post('/sessions/:id', async (req, res) => { > const id = req.params.id > await promisify(execFile)('docker', [ > 'run', '-d', '--cap-add', 'SYS_ADMIN', '--device', '/dev/fuse', > '--name', `box-${id}`, 'mirage-box', 'sleep', 'infinity', > ]) > terminal(id).createSession(id) > res.sendStatus(201) > }) > > app.post('/sessions/:id/run', async (req, res) => { > const r = await terminal(req.params.id).shell(req.body.command, { sessionId: req.params.id }) > res.json({ stdout: r.stdoutText, stderr: r.stderrText, exitCode: r.exitCode }) > }) > > app.listen(3000, '127.0.0.1') > ``` * Send each terminal's requests to one replica, for example by hashing the terminal id at the load balancer. A replica keeps a session in memory once it has loaded it, so two replicas serving one terminal would each keep their own working directory. After a restart, the replica reads the terminal back from Redis, in the directory it left. * Every terminal's `/work` is the same Redis keys, so terminals share files. Give each `RedisVFS` its own `key_prefix` to keep them apart. * Remove a terminal's container with `docker rm -f box-` when the terminal ends. * `ws.explain(line)` shows which runtime serves each command. # Policy & Security Source: https://docs.mirage.strukto.ai/home/examples/policy-security One agent profile that hides files, denies and asks about commands, hides variables and runs a policy script, beside a coded policy on file writes. Mirage judges every action an agent takes before it reaches a service: each command, each file call, including those a Python program makes, and each variable write. This example gives an analyst agent one profile and the workspace one coded policy, and walks through what the agent sees. | Layer | Controls | Here | | - | - | - | | Profile `paths` | Which files the agent can see | Hides `/data/secrets` and every `*.pem`, shows `/data/secrets/README.md` back | | Profile `commands` | Which commands run | Denies `curl` and `slack send-message`, asks before `rm` under `/data/out` | | Profile `vars` | Which variables it can read | Hides `AWS_*` | | Profile `policy` | What the rules cannot express | A script refuses Python that deletes files | | Coded policy | Any action, in code | Writes only under `/data/out`, from a command or from Python | | `on_ask` | Who answers an ask | The host approves | ## The policy script The script's `pre_command` takes the command, opens the files it names through the workspace, and refuses a Python script whose code deletes files: ```python guard.py theme={null} def deletes(path): try: code = open(path).read() except OSError: return False return any(call in code for call in ("os.remove", "os.unlink", "shutil.rmtree")) def pre_command(ctx): if ctx["command"].startswith("python") and any(deletes(p) for p in ctx["paths"]): return {"kind": "deny", "reason": "deleting files is disabled"} ``` The script reads the code as text, so it stops the usual calls, not every way Python can delete a file. A rule that must always hold belongs in a coded policy, which judges each file call itself, as `WritesOnlyToOut` below does for writes. ## The workspace > [tab] Python > > ```python theme={null} > import dataclasses > from pathlib import Path > > from mirage import Decision, MountMode, Outcome, Scope, Workspace > from mirage.commands.cli.builtin.slack import SLACK > from mirage.policy import Deny, Policy, VfsContext > from mirage.runtime.types import ScriptSource > from mirage.vfs.s3 import S3Config, S3VFS > > > class WritesOnlyToOut(Policy): > async def pre_vfs(self, ctx: VfsContext) -> Deny | None: > if ctx.write and not ctx.path.virtual.startswith("/data/out/"): > return Deny("the analyst writes only under /data/out") > return None > > > async def approve(record: Decision) -> Decision: > return dataclasses.replace(record, outcome=Outcome.ALLOW, scope=Scope.ONCE) > > > ws = Workspace( > {"/data": (S3VFS(S3Config(bucket="analytics")), MountMode.EXEC)}, > clis={"slack": (SLACK, {"token": slack_bot_token})}, > env={"AWS_SECRET_ACCESS_KEY": aws_secret_access_key, "TEAM": "growth"}, > profiles={ > "analyst": { > "cwd": "/data", > "paths": {"hide": ["/data/secrets", "*.pem"], "show": ["/data/secrets/README.md"]}, > "commands": { > "deny": ["curl", "slack send-message"], > "ask": [{"commands": {"rm": ["/data/out/*"]}, "reason": "deletes need review"}], > }, > "vars": {"hide": ["AWS_*"]}, > "policy": { > "pre_command": [{"script": ScriptSource(Path("guard.py").read_text()), "runtime": "monty"}], > }, > }, > }, > policies=[WritesOnlyToOut()], > on_ask=approve, > ) > agent = await ws.session("agent", profile="analyst") > await agent.shell("ls") > ``` > [tab] TypeScript > > ```typescript theme={null} > import { readFileSync } from 'node:fs' > import { > MountMode, > Outcome, > S3VFS, > SLACK, > Scope, > ScriptSource, > Workspace, > SessionProfile, > type Policy, > } from '@struktoai/mirage-node' > > const writesOnlyToOut: Policy = { > preVfs(ctx) { > if (ctx.write && !ctx.path.virtual.startsWith('/data/out/')) { > return { kind: 'deny', reason: 'the analyst writes only under /data/out' } > } > return null > }, > } > > const analyst = SessionProfile( > { > cwd: '/data', > paths: { hide: ['/data/secrets', '*.pem'], show: ['/data/secrets/README.md'] }, > commands: { > deny: ['curl', 'slack send-message'], > ask: [{ commands: { rm: ['/data/out/*'] }, reason: 'deletes need review' }], > }, > vars: { hide: ['AWS_*'] }, > policy: { > pre_command: [{ script: new ScriptSource(readFileSync('guard.py', 'utf8'), 'python'), runtime: 'monty' }], > }, > }, > 'profile `analyst`', > ) > > const ws = new Workspace( > { '/data': [new S3VFS({ bucket: 'analytics' }), MountMode.EXEC] }, > { > clis: { slack: [SLACK, { token: slackBotToken }] }, > env: { AWS_SECRET_ACCESS_KEY: awsSecretAccessKey, TEAM: 'growth' }, > profiles: { analyst }, > policies: [writesOnlyToOut], > onAsk: (record) => Promise.resolve({ ...record, outcome: Outcome.ALLOW, scope: Scope.ONCE }), > }, > ) > ws.createSession('agent', { profile: 'analyst' }) > await ws.shell('ls', { sessionId: 'agent' }) > ``` ## What the agent sees ```console theme={null} $ ls clean.py out reports secrets $ cat /data/secrets/aws.txt cat: /data/secrets/aws.txt: No such file or directory $ cat /data/secrets/README.md see #ops for credentials $ cat server.pem cat: server.pem: No such file or directory $ echo $AWS_SECRET_ACCESS_KEY $TEAM growth $ curl -s https://example.com curl: Permission denied $ slack send-message --channel general --text hi slack: Permission denied $ cat clean.py import os os.remove("/data/reports/q3.csv") $ python3 clean.py python3: Permission denied $ echo x > notes.txt notes.txt: Permission denied $ python3 -c "open('/data/notes.txt', 'w').write('x')" Traceback (most recent call last): File "", line 1, in open('/data/notes.txt', 'w').write('x') ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PermissionError: [Errno 13] Permission denied: '/data/notes.txt' $ echo x > out/notes.txt $ rm out/notes.txt ``` * **Hidden files are absent, not refused.** `aws.txt` and `server.pem` read as missing, and `ls` leaves `server.pem` out. `secrets` stays listed only because `README.md` is shown back inside it. * **Hidden variables read as unset.** `$AWS_SECRET_ACCESS_KEY` expands to nothing; `$TEAM` is untouched. * **Denied commands exit 126** with `Permission denied`, the same wording a shell gives. The reason stays with the host. * **The script reads the file before it runs.** `python3 clean.py` is refused because `clean.py` calls `os.remove`. A script that only reads runs. * **The coded policy sees every file call.** The write from `echo` and the write from Python's `open()` both reach `pre_vfs`, and both are refused outside `/data/out`. * **An ask goes to the host.** `rm out/notes.txt` matches the ask rule, so `approve` answers it before the line runs. Without `on_ask`, the line returns pending until the host answers. The profile applies only to sessions under `analyst`. The coded policy applies to every session of the workspace, so the host's own writes outside `/data/out` are refused as well. ## Learn more * [Agent profiles](/home/profiles): every profile key and how rules match. * [Policies](/home/policy/policies): the eight methods and their answers. * [Scripts](/home/policy/scripts): what a policy script reads and returns. * [Explain](/home/policy/explain): check a line against the rules before it runs. # Runtime Routing Source: https://docs.mirage.strukto.ai/home/examples/runtime-routing Route each line with a policy script, first a fixed one and then one that asks an LLM, so plain Python stays in-process and only GPU work reaches a Daytona GPU sandbox. Mirage picks a runtime for every command line. Most Python an agent writes runs on [Monty](/home/setup/runtime/monty), in-process and at no infrastructure cost. A line that needs a GPU has to run on one, and a GPU is billed while it runs. A [route policy](/home/policy/route-runtime) makes that choice per line. This example sends GPU work to a [Daytona](/home/setup/machine/daytona) GPU sandbox and keeps everything else on Monty: first with a fixed script, then with one that asks an LLM. The LLM step builds on the LLM routing example in [Python](https://github.com/strukto-ai/mirage/tree/main/examples/python/policy/llm_routing) and [TypeScript](https://github.com/strukto-ai/mirage/tree/main/examples/typescript/policy/llm_routing), which routes between Monty and the host's Python. ## The GPU sandbox Create a GPU sandbox in Daytona from a snapshot with PyTorch and CUDA, and note its id. Daytona sets the GPU type on the snapshot, and a GPU sandbox is ephemeral. Mirage runs programs in it and leaves its lifecycle to Daytona. ## The workspace Two runtimes capture `python3`: `monty` first, then `machine`, which runs it on the `gpu` machine, the Daytona sandbox. The route policy is a script that runs on Monty, read from `route.py`: ```yaml workspace.yaml theme={null} mode: exec mounts: /data: vfs: ram machines: gpu: provider: daytona sandbox_id: ${DAYTONA_GPU_SANDBOX_ID} runtimes: - monty - name: remote captures: ["python3"] machine: gpu - workspace route_policy: script: route.py runtime: monty ``` ## Route by a fixed script A policy script reads the line and returns where it runs. This one sends any line that names PyTorch or CUDA to the GPU: ```python route.py theme={null} def pre_execute(ctx): if any(word in ctx["line"] for word in ("torch", "cuda")): return {"kind": "route", "runtime": "remote", "reason": "the line uses PyTorch or CUDA"} ``` A line the script stays silent on runs on the first runtime that captures it, so `python3 -c "print(sum(range(1, 101)))"` runs on Monty. The script costs microseconds, and it misses what it does not name: a script file that imports `torch`, or a GPU library under another name. ## Route by an LLM An LLM reads the line the way an engineer would. This `route.py` describes each runtime and asks which one the line needs. A program on Monty has no network, so the LLM call is a [host function](/home/policy/scripts#host-functions), `parse_runtime`, that the workspace hands it: ```python route.py theme={null} TASK = ( "Pick the runtime that can run the Python code in this line, monty " "when it can." ) RUNTIMES = { "monty": ( "Mirage's sandboxed Python, in-process and free: a subset of the " "language and part of the standard library, with no packages, GPU, " "network or subprocesses" ), "remote": ( "a cloud sandbox with an NVIDIA GPU, CUDA, PyTorch and the full " "standard library, billed while it runs" ), } async def pre_execute(ctx): if any(c["command"] == "python3" for c in ctx["commands"]): choice = await parse_runtime(TASK, RUNTIMES, ctx["line"]) return {"kind": "route", **choice} ``` A line with no `python3` gets no answer, and runs where its commands' captures put it. `parse_runtime` asks the LLM for a runtime and a one-sentence reason. Both `explain` and the run ask the policy, so it keeps each line's answer and the preview and the run agree: > [tab] Python > > ```python theme={null} > from typing import Literal > > from openai import AsyncOpenAI > from pydantic import BaseModel > > from mirage import Workspace > from mirage.config import load_config > > > class RuntimeChoice(BaseModel): > runtime: Literal["monty", "machine"] > reason: str > > > CHOICES: dict[str, dict[str, str]] = {} > > > async def parse_runtime(task: str, runtimes: dict[str, str], line: str) -> dict[str, str]: > if line not in CHOICES: > prompt = f"{task} Say why in one sentence.\n" + "\n".join( > f"{name}: {about}" for name, about in runtimes.items() > ) > done = await AsyncOpenAI(timeout=10).responses.parse( > model="gpt-6-luna", instructions=prompt, input=line, text_format=RuntimeChoice > ) > CHOICES[line] = done.output_parsed.model_dump() > return CHOICES[line] > > > ws = Workspace( > **load_config("workspace.yaml").to_workspace_kwargs(), > policy_functions={"parse_runtime": parse_runtime}, > ) > ``` > [tab] TypeScript > > ```typescript theme={null} > import OpenAI from 'openai' > import { zodTextFormat } from 'openai/helpers/zod' > import { z } from 'zod' > import { Workspace, configToWorkspaceArgs, loadWorkspaceConfigFile } from '@struktoai/mirage-node' > > const RuntimeChoice = z.object({ runtime: z.enum(['monty', 'machine']), reason: z.string() }) > type Choice = z.infer > > const choices = new Map() > > async function parseRuntime(task: string, runtimes: Record, line: string): Promise { > const known = choices.get(line) > if (known !== undefined) return known > const prompt = [ > `${task} Say why in one sentence.`, > ...Object.entries(runtimes).map(([name, about]) => `${name}: ${about}`), > ].join('\n') > const done = await new OpenAI({ timeout: 10_000 }).responses.parse({ > model: 'gpt-6-luna', > instructions: prompt, > input: line, > text: { format: zodTextFormat(RuntimeChoice, 'runtime_choice') }, > }) > if (done.output_parsed === null) throw new Error('the model chose no runtime') > choices.set(line, done.output_parsed) > return done.output_parsed > } > > const { mounts, options } = await configToWorkspaceArgs(loadWorkspaceConfigFile('workspace.yaml')) > const ws = new Workspace(mounts, { ...options, policyFunctions: { parse_runtime: parseRuntime } }) > ``` ## Run it `ws.explain(line)` shows where a line will run and why, before it runs, so no GPU starts for a line that does not need one: > [tab] Python > > ```python theme={null} > for line in ( > 'python3 -c "print(sum(range(1, 101)))"', > 'python3 -c "import torch; print(torch.cuda.get_device_name(0))"', > ): > plan = await ws.explain(line) > for answer in plan.answers: > if answer.kind == "route": > print(line, "->", answer.runtime, answer.reason) > await ws.shell(line) > ``` > [tab] TypeScript > > ```typescript theme={null} > for (const line of [ > 'python3 -c "print(sum(range(1, 101)))"', > 'python3 -c "import torch; print(torch.cuda.get_device_name(0))"', > ]) { > const plan = await ws.explain(line) > for (const answer of plan.answers) { > if (answer.kind === 'route') console.log(line, '->', answer.runtime, answer.reason) > } > await ws.shell(line) > } > ``` The sum stays on Monty and prints `5050` in-process; only the `torch` line reaches the GPU. ## Notes * Daytona GPU sandboxes cannot mount FUSE, so a Mirage inside one cannot serve the workspace's files. Lines routed there should carry their code (`python3 -c`, or a script piped on stdin) and fetch their data, such as model weights from Hugging Face, themselves. * The script has 10 seconds, the LLM call included. A script that fails or runs past them fails the line with a routing error rather than guessing. * [Hybrid Terminal](/home/examples/embedded-terminal#hybrid-terminal) routes with a fixed rule written as a function in code instead of a script. # File cache Source: https://docs.mirage.strukto.ai/home/infrastructure/file-cache Where a workspace caches the file content it reads, in memory or on Redis. The file cache keeps file content Mirage has read, so a second read is served without asking the backend again. | `type` | Keeps it | Keys | | - | - | - | | `ram` | In the process's memory, up to `limit` | `limit`, default `32MB`; `max_drain_bytes` | | `redis` | On Redis, under the workspace's own keys | `url`, `key_prefix`, `limit`, default `512MB`; `max_drain_bytes` | `limit` is in bytes or a size string. `max_drain_bytes` is the largest file a streamed read copies into the cache: 8 MiB or `limit`, whichever is smaller, and never more than `limit`. The key is `cache`, beside `store` rather than inside it. ## In memory > [tab] YAML > > ```yaml theme={null} > cache: > type: ram > limit: 2GB > ``` > [tab] Python > > ```python theme={null} > from mirage import Workspace > from mirage.cache.file.config import CacheConfig > > ws = Workspace(mounts, cache=CacheConfig(limit="2GB")) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { Workspace } from '@struktoai/mirage-node' > > const ws = new Workspace(mounts, { cache: { type: 'ram', limit: '2GB' } }) > ``` ## On Redis With the cache on Redis, a file one instance of the workspace read is served to the others without asking the backend again. > [tab] YAML > > ```yaml theme={null} > workspace_id: agent > cache: > type: redis > url: redis://redis.internal:6379/0 > ``` > [tab] Python > > ```python theme={null} > from mirage import Workspace > from mirage.cache.file.config import RedisCacheConfig > > ws = Workspace( > mounts, > workspace_id="agent", > cache=RedisCacheConfig(url="redis://redis.internal:6379/0"), > ) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { Workspace } from '@struktoai/mirage-node' > > const ws = new Workspace(mounts, { > workspaceId: 'agent', > cache: { type: 'redis', url: 'redis://redis.internal:6379/0' }, > }) > ``` The keys belong to the workspace, so two workspaces on one Redis never read each other's files. Naming the same `key_prefix` in several workspaces shares one cache between them, which is safe only when they mount the same backends at the same paths. On Redis, `limit` does not evict anything; cap the server's memory with `maxmemory` instead. # Index Source: https://docs.mirage.strukto.ai/home/infrastructure/file-index Where a workspace caches directory listings and file metadata, for the whole workspace or one mount. The index keeps directory listings and file metadata, so `ls`, `find` and `stat` answer from one listing instead of asking the backend each time. | `type` | Keeps it | Keys | | - | - | - | | `ram` | In the process's memory | `ttl`, default `600` seconds | | `redis` | On Redis, under the workspace's own keys | `url`, `key_prefix`, `ttl` | The key is `index`, beside `store`. A mount's own `index` replaces it for that mount. ## For the whole workspace > [tab] YAML > > ```yaml theme={null} > workspace_id: agent > index: > type: redis > url: redis://redis.internal:6379/0 > ttl: 300 > ``` > [tab] Python > > ```python theme={null} > from mirage import Workspace > from mirage.cache.index import RedisIndexConfig > > ws = Workspace( > mounts, > workspace_id="agent", > index=RedisIndexConfig(url="redis://redis.internal:6379/0", ttl=300), > ) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { Workspace } from '@struktoai/mirage-node' > > const ws = new Workspace(mounts, { > workspaceId: 'agent', > index: { type: 'redis', url: 'redis://redis.internal:6379/0', ttl: 300 }, > }) > ``` With the index on Redis, one listing answers every instance of the workspace. The keys belong to the workspace, and naming the same `key_prefix` in several workspaces shares one index, as for the [file cache](/home/infrastructure/file-cache). ## For one mount A mount whose listings change rarely can keep them longer than the rest: > [tab] YAML > > ```yaml theme={null} > mounts: > /archive: > vfs: s3 > config: > bucket: agent-archive > index: > type: ram > ttl: 3600 > ``` > [tab] Python > > ```python theme={null} > from mirage import Mount, Workspace > from mirage.cache.index import IndexConfig > from mirage.vfs.s3 import S3VFS, S3Config > > ws = Workspace({ > "/archive": Mount( > S3VFS(S3Config(bucket="agent-archive")), > index=IndexConfig(ttl=3600), > ), > }) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { Mount, S3VFS, Workspace } from '@struktoai/mirage-node' > > const ws = new Workspace({ > '/archive': new Mount(new S3VFS({ bucket: 'agent-archive' }), { > index: { type: 'ram', ttl: 3600 }, > }), > }) > ``` # History Source: https://docs.mirage.strukto.ai/home/infrastructure/history Where a workspace records the commands it runs, in memory or on disk. The history store records every command a session runs at the top level. The `history` builtin and `/.bash_history` are two views of that one record, and a [policy](/home/policy/policies) reads it as `/.bash_history`. [`GET /v1/workspaces/{id}/logs`](/api/operations/workspaces/list-workspace-logs) and `mirage workspace logs` expose completed commands as pages with their mount calls. The library's `ws.history()` reads every session's record: each command as a `command` entry when it starts and a `result` entry (exit code, stdout, stderr) when it ends, and with `vfs`, each call it made to a mount between them. A read returns the newest 10,000 entries at most, and `/.bash_history` the newest 10,000 commands, as bash's `HISTFILESIZE` bounds its history file; `history` lists the newest 500, as `HISTSIZE` does. A line of several commands is recorded as bash's history adds it when it reads the line interactively: one entry per command read, with what that command wrote. A command spanning lines is one entry, its lines joined as `cmdhist` joins them (`for i in 1 2; do echo $i; done`), and a heredoc keeps its body. A line that stops at an `exit` or a `set -e` failure records no command after it, as bash never reads one. A line a `post_execute` policy judges is recorded whole once the policy has answered, so no output it drops reaches the history. History is kept per session. A workspace built again shows a session's history once it has that session again: keep the [sessions](/home/infrastructure/sessions) where they survive too, or give the session a fixed id with `default_session_id`. History grows with every command, so it can go to a backend of its own while the rest of the state stays where it is. | `type` | Keeps it | Keys | | - | - | - | | `ram` | In the process's memory, until it exits | | | `disk` | In files under `root` | `root`, default `~/.mirage/state` | The group key is `store.observer`. History is never kept on Redis: a Redis store keeps it on the machine's disk, under the store's `root`, unless `observer` says otherwise. To see it across machines, send it to [OpenTelemetry](#send-it-to-opentelemetry). ## On disk > [tab] YAML > > ```yaml theme={null} > workspace_id: agent > store: > type: redis > url: redis://redis.internal:6379/0 > observer: > type: disk > root: /var/lib/mirage > ``` > [tab] Python > > ```python theme={null} > from mirage import Workspace > from mirage.workspace.store import DiskWorkspaceStateStore, RedisWorkspaceStateStore > > store = RedisWorkspaceStateStore( > url="redis://redis.internal:6379/0", > observer=DiskWorkspaceStateStore(root="/var/lib/mirage"), > ) > ws = Workspace(mounts, workspace_id="agent", store=store, owns_store=True) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { DiskWorkspaceStateStore, RedisWorkspaceStateStore, Workspace } from '@struktoai/mirage-node' > > const store = new RedisWorkspaceStateStore({ > url: 'redis://redis.internal:6379/0', > observer: new DiskWorkspaceStateStore({ root: '/var/lib/mirage' }), > }) > const ws = new Workspace(mounts, { workspaceId: 'agent', store, ownsStore: true }) > ``` Here the rest of the state is on Redis and only the history stays on the machine's disk. ## Send it to OpenTelemetry Every line that ends is also a trace span: `command`, from its start to its end, and under it a `vfs.` span for each call it made to a mount. Each `&` job and each process the line started is a `job` or `process` span under it once it ends, so one trace shows a line with everything it ran. Nothing is sent until the process sets up an OpenTelemetry SDK, whose exporter picks the backend: OTLP to Datadog, Honeycomb, Grafana, Langfuse and others. | Span | Attributes | | - | - | | `command` | `mirage.line.id`, `mirage.workspace.id`, `mirage.session.id`, `host.id`, `mirage.machine.ids`, `mirage.command`, `mirage.cwd`, `mirage.exit_code`, `mirage.timestamp`, `mirage.duration_ms`, `mirage.stdout`, `mirage.stderr`, `mirage.vfs.dropped` | | `vfs.` | `mirage.vfs.path`, `mirage.vfs.source`, `mirage.vfs.bytes`, `mirage.vfs.timestamp`, `mirage.vfs.duration_ms` | | `job` | `mirage.job.id`, `mirage.job.number`, `mirage.line.id`, `mirage.workspace.id`, `mirage.session.id`, `host.id`, `mirage.machine.id`, `process.pid`, `mirage.command`, `mirage.cwd`, `mirage.exit_code`, `mirage.signal` | | `process` | `process.pid`, `process.parent_pid`, `process.group_leader.pid`, `mirage.line.id`, `mirage.workspace.id`, `mirage.session.id`, `host.id`, `mirage.machine.id`, `process.command_line`, `mirage.cwd`, `mirage.runtime`, `mirage.machine.pid`, `process.exit.code`, `mirage.signal`, `mirage.error` | `host.id` is the host running Mirage, such as `host:my-laptop`. `mirage.machine.id` is the machine a job or process ran on, such as `docker:tools`. `mirage.machine.ids` lists the machines a line's processes ran on by the time the line ended, while the workspace keeps their records; a background job that starts a program later names its machine on that program's own `process` span. Traces cover what runs on the workspace's machine and the runtimes it reaches; a program a runtime runs elsewhere starts no spans of its own there. `mirage.cwd` is where the line started. `mirage.stdout` and `mirage.stderr` are the start of its output, as UTF-8 text of at most 16 KiB each by default, or as many bytes as `MIRAGE_TRACE_CONTENT_MAX_BYTES` says. At that size both fit the 64 KB a Cloudflare Workers span holds for all its attributes, and any backend's field. A line sends at most 1000 `vfs.` spans, or as many as `MIRAGE_TRACE_MAX_SPANS` says, so a walk over a large tree cannot flood the exporter. `mirage.vfs.dropped` on its `command` span counts the calls past that; the history still records every call. `mirage.timestamp` and `mirage.duration_ms` repeat the span's own start and length in milliseconds, as the history's `command` and `result` entries have them; on a `vfs.` span, `mirage.vfs.timestamp` is when the call ended, as its `vfs` entry has it. They are for a tracer that can't be given a span's times, such as a Cloudflare Workers custom span. To keep what lines touch out of the traces, set `MIRAGE_TRACE_CAPTURE_CONTENT=false`: `command` spans then carry no output and no `vfs.` spans are sent. The history keeps the first 4096 characters of each output either way. > [tab] Python > > ```bash theme={null} > OTEL_TRACES_EXPORTER=otlp OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.example.com \ > opentelemetry-instrument python agent.py > ``` > [tab] TypeScript > > ```typescript theme={null} > import { trace } from '@opentelemetry/api' > import { BasicTracerProvider, BatchSpanProcessor } from '@opentelemetry/sdk-trace-base' > import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http' > > trace.setGlobalTracerProvider( > new BasicTracerProvider({ > spanProcessors: [new BatchSpanProcessor(new OTLPTraceExporter({ url: 'https://otlp.example.com/v1/traces' }))], > }), > ) > ``` # Jobs Source: https://docs.mirage.strukto.ai/home/infrastructure/jobs Where a workspace keeps background jobs and processes, and which instance of it runs them. The execution store keeps: * Each session's background jobs, the ones `cmd &` starts, and each job's output. * The processes the workspace runs, which `ps` lists. * Which instance of the workspace runs them, and when it was last seen. | `type` | Keeps them | Keys | | - | - | - | | `ram` | In the process's memory. Jobs end with the process. | | | `redis` | On Redis, under `key_prefix` and the workspace id. A job's output stays a day after its last write. | `url`, `key_prefix`, default `mirage:` | The group key is `store.execution`. A job's output is a stream other processes follow, so `disk` is refused here, and a `disk` store keeps its jobs in memory. In code, `SqlWorkspaceStateStore` keeps them in a SQL database, SQLite or Postgres, in two tables it makes on first use, so every process on the database lists the same jobs, lines and processes, and a restart on it keeps them. A reader following a job on another process there sees new output within a quarter of a second. ## On Redis > [tab] YAML > > ```yaml theme={null} > workspace_id: agent > store: > type: disk > root: /var/lib/mirage > execution: > type: redis > url: redis://redis.internal:6379/0 > ``` > [tab] Python > > ```python theme={null} > from mirage import Workspace > from mirage.workspace.store import DiskWorkspaceStateStore, RedisWorkspaceStateStore > > store = DiskWorkspaceStateStore( > root="/var/lib/mirage", > execution=RedisWorkspaceStateStore(url="redis://redis.internal:6379/0"), > ) > ws = Workspace(mounts, workspace_id="agent", store=store, owns_store=True) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { DiskWorkspaceStateStore, RedisWorkspaceStateStore, Workspace } from '@struktoai/mirage-node' > > const store = new DiskWorkspaceStateStore({ > root: '/var/lib/mirage', > execution: new RedisWorkspaceStateStore({ url: 'redis://redis.internal:6379/0' }), > }) > const ws = new Workspace(mounts, { workspaceId: 'agent', store, ownsStore: true }) > ``` Here the rest of the state stays on the machine's disk, and every process on the machine that builds the workspace sees the same jobs. ## Several instances of one workspace Every process that builds the workspace under the same id on one Redis is an instance of it, on one machine or several, behind a load balancer or as replicas of one agent. > [tab] YAML > > ```yaml workspace.yaml theme={null} > workspace_id: agent > store: > type: redis > url: redis://redis.internal:6379/0 > mounts: > /data: > vfs: s3 > config: > bucket: agent-data > ``` > [tab] Python > > ```python theme={null} > from mirage import MountMode, Workspace > from mirage.vfs.s3 import S3VFS, S3Config > from mirage.workspace.store import RedisWorkspaceStateStore > > ws = Workspace( > {"/data": S3VFS(S3Config(bucket="agent-data"))}, > mode=MountMode.WRITE, > workspace_id="agent", > store=RedisWorkspaceStateStore(url="redis://redis.internal:6379/0"), > owns_store=True, > ) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { MountMode, RedisWorkspaceStateStore, S3VFS, Workspace } from '@struktoai/mirage-node' > > const ws = new Workspace( > { '/data': new S3VFS({ bucket: 'agent-data' }) }, > { > mode: MountMode.WRITE, > workspaceId: 'agent', > store: new RedisWorkspaceStateStore({ url: 'redis://redis.internal:6379/0' }), > ownsStore: true, > }, > ) > ``` > [tab] Servers > > ```bash theme={null} > for server in http://mirage-a:8765 http://mirage-b:8765; do > curl "$server/v1/workspaces" \ > -H "Authorization: Bearer $MIRAGE_AUTH_TOKEN" \ > -H 'Content-Type: application/json' \ > --data-binary @workspace.json > done > ``` On the servers, `workspace.json` holds `{"id": "agent", "config": {...}}` with the same config on each. Then: * One instance runs the workspace's lines at a time: the first to run one. Any other is refused with an error naming that instance, which a server answers with `409`, until it stops, deletes or closes the workspace. * If it goes away without doing so, the workspace is free 30 seconds after it was last seen. The next instance to run a line reports the jobs it left as ended with status 129 and stops the programs they left running. * A server keeps its id under its state root, so a restarted server runs its workspaces again at once. * Sessions and symlinks are shared, since the whole store is on Redis. A session sees only its own processes; a profile with [`processes: workspace`](/home/profiles) widens that to every session's. [Shell](/home/core/shell#jobs-across-instances) describes the details. # Namespace Source: https://docs.mirage.strukto.ai/home/infrastructure/namespace Where a workspace keeps symlinks and file attributes, in memory, on disk or on Redis. The namespace store keeps what a backend has no place for: * Symlinks made with `ln -s`. * Modes, owners and times that `chmod`, `chown` and `touch` set on a backend that cannot store them. * Extended attributes set with `setfattr`. Every instance of the workspace on the same store sees the same links and attributes. | `type` | Keeps them | Keys | | - | - | - | | `ram` | In the process's memory, until it exits | | | `disk` | In files under `root` | `root`, default `~/.mirage/state` | | `redis` | On Redis, under `key_prefix` and the workspace id | `url`, `key_prefix`, default `mirage:` | `store.namespace` moves only this store. `store.type` moves it together with the others, as the [overview](/home/infrastructure/overview#one-store-or-several) shows. ## On disk > [tab] YAML > > ```yaml theme={null} > workspace_id: agent > store: > namespace: > type: disk > root: /var/lib/mirage > ``` > [tab] Python > > ```python theme={null} > from mirage import Workspace > from mirage.workspace.store import DiskWorkspaceStateStore, RAMWorkspaceStateStore > > store = RAMWorkspaceStateStore( > namespace=DiskWorkspaceStateStore(root="/var/lib/mirage"), > ) > ws = Workspace(mounts, workspace_id="agent", store=store, owns_store=True) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { DiskWorkspaceStateStore, RAMWorkspaceStateStore, Workspace } from '@struktoai/mirage-node' > > const store = new RAMWorkspaceStateStore({ > namespace: new DiskWorkspaceStateStore({ root: '/var/lib/mirage' }), > }) > const ws = new Workspace(mounts, { workspaceId: 'agent', store, ownsStore: true }) > ``` ## On Redis > [tab] YAML > > ```yaml theme={null} > workspace_id: agent > store: > namespace: > type: redis > url: redis://redis.internal:6379/0 > ``` > [tab] Python > > ```python theme={null} > from mirage import Workspace > from mirage.workspace.store import RAMWorkspaceStateStore, RedisWorkspaceStateStore > > store = RAMWorkspaceStateStore( > namespace=RedisWorkspaceStateStore(url="redis://redis.internal:6379/0"), > ) > ws = Workspace(mounts, workspace_id="agent", store=store, owns_store=True) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { RAMWorkspaceStateStore, RedisWorkspaceStateStore, Workspace } from '@struktoai/mirage-node' > > const store = new RAMWorkspaceStateStore({ > namespace: new RedisWorkspaceStateStore({ url: 'redis://redis.internal:6379/0' }), > }) > const ws = new Workspace(mounts, { workspaceId: 'agent', store, ownsStore: true }) > ``` # Overview Source: https://docs.mirage.strukto.ai/home/infrastructure/overview The stores a workspace keeps, the infrastructure each one can live on, and where you set it. A workspace needs no services. Out of the box it keeps everything in memory. Each store below can move onto infrastructure you run, on its own or together with the others. | Store | Holds | Backends | Key | | - | - | - | - | | [Namespace](/home/infrastructure/namespace) | Symlinks and file attributes | `ram`, `disk`, `redis` | `store.namespace` | | [Sessions](/home/infrastructure/sessions) | Each session's working directory, variables and functions | `ram`, `disk`, `redis`, `s3` | `store.workspace` | | [History](/home/infrastructure/history) | Command history | `ram`, `disk` | `store.observer` | | [Jobs](/home/infrastructure/jobs) | Background jobs, their output and the processes the workspace runs | `ram`, `redis` | `store.execution` | | [File cache](/home/infrastructure/file-cache) | File content Mirage has read | `ram`, `redis` | `cache` | | [Index](/home/infrastructure/file-index) | Directory listings and file metadata | `ram`, `redis` | `index`, or a mount's `index` | The rest has pages of its own: [runtimes](/home/setup/runtime/overview) run programs inside Mirage, on the host or on a [machine](/home/setup/machine/overview); [host folders](/home/setup/fuse) show a mount through FUSE, FSKit or NFS; and [credentials](/home/authentication) come from the environment, a dotenv file, AWS Secrets Manager or 1Password. ## One store or several `store.type` places the namespace, sessions, history and jobs together. A group key (`namespace`, `workspace`, `observer`, `execution`) moves one of them to a backend of its own. Here symlinks and jobs live on Redis, history on disk and sessions in a bucket: > [tab] YAML > > ```yaml workspace.yaml theme={null} > workspace_id: agent > store: > type: redis > url: redis://redis.internal:6379/0 > observer: > type: disk > root: /var/lib/mirage > workspace: > type: s3 > bucket: agent-state > mounts: > /data: > vfs: ram > ``` > [tab] Python > > ```python theme={null} > from mirage import RAMVFS, MountMode, Workspace > from mirage.vfs.s3 import S3Config > from mirage.workspace.store import ( > DiskWorkspaceStateStore, > RedisWorkspaceStateStore, > S3WorkspaceStateStore, > ) > > store = RedisWorkspaceStateStore( > url="redis://redis.internal:6379/0", > observer=DiskWorkspaceStateStore(root="/var/lib/mirage"), > workspace=S3WorkspaceStateStore(S3Config(bucket="agent-state")), > ) > ws = Workspace( > {"/data": RAMVFS()}, > mode=MountMode.WRITE, > workspace_id="agent", > store=store, > owns_store=True, > ) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { > DiskWorkspaceStateStore, > MountMode, > RAMVFS, > RedisWorkspaceStateStore, > S3WorkspaceStateStore, > Workspace, > } from '@struktoai/mirage-node' > > const store = new RedisWorkspaceStateStore({ > url: 'redis://redis.internal:6379/0', > observer: new DiskWorkspaceStateStore({ root: '/var/lib/mirage' }), > workspace: new S3WorkspaceStateStore({ bucket: 'agent-state' }), > }) > const ws = new Workspace( > { '/data': new RAMVFS() }, > { mode: MountMode.WRITE, workspaceId: 'agent', store, ownsStore: true }, > ) > ``` Every store keeps its state by `workspace_id`. Give the workspace a fixed id whenever its state should be found again, after a restart or by another process. Closing the workspace closes a store it owns, group stores included. | `type` | Survives a restart | Shared with | | - | - | - | | `ram` | No | Workspaces in the same process given the same store object | | `disk` | Yes | Processes on the same machine. Jobs stay in each process's memory. | | `redis` | Yes | Every process on that Redis, on any machine | | `s3` | Yes | Every process that reaches the bucket. Sessions only. | [stores.py](https://github.com/strukto-ai/mirage/blob/main/examples/python/configuration/stores.py) and [stores.ts](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/configuration/stores.ts) place one store at a time on disk, build the workspace again and print what came back. A workspace built in code keeps its state in memory. One the server builds, through `mirage workspace create` or `POST /v1/workspaces`, keeps it on disk under `~/.mirage/state`. A `store` block replaces either default. ## Where you set it One config describes a workspace, the same [YAML](/home/configuration) on every surface. Python and TypeScript also take each store as a constructor argument, as each store's page shows. | Surface | Takes the config as | | - | - | | [CLI](/home/access/cli) | A YAML or JSON file: `mirage workspace create workspace.yaml` | | [HTTP](/home/access/http) | JSON under `config` in `POST /v1/workspaces` | | Python | `load_config("workspace.yaml")` | | TypeScript | `loadWorkspaceConfigFile("workspace.yaml")` | > [tab] CLI > > ```bash theme={null} > mirage workspace create workspace.yaml --id agent > ``` > [tab] HTTP > > ```bash theme={null} > curl http://127.0.0.1:8765/v1/workspaces \ > -H "Authorization: Bearer $MIRAGE_AUTH_TOKEN" \ > -H 'Content-Type: application/json' \ > -d '{"id":"agent","config":{"store":{"type":"redis","url":"redis://redis.internal:6379/0"},"mounts":{"/data":{"vfs":"ram"}}}}' > ``` > [tab] Python > > ```python theme={null} > from mirage import Workspace > from mirage.config import load_config > > ws = Workspace(**load_config("workspace.yaml").to_workspace_kwargs()) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { Workspace, configToWorkspaceArgs, loadWorkspaceConfigFile } from '@struktoai/mirage-node' > > const { mounts, options } = await configToWorkspaceArgs(loadWorkspaceConfigFile('workspace.yaml')) > const ws = new Workspace(mounts, options) > ``` Every key is listed in [Workspace configuration](/home/configuration#cache-index-and-store). # Sessions Source: https://docs.mirage.strukto.ai/home/infrastructure/sessions Where a workspace keeps its sessions, in memory, on disk, on Redis or in an S3 bucket. The sessions store keeps each session's shell state and the workspace's own record: * Each session's working directory, variables, functions, mount modes and [profile](/home/profiles) rules. Shell options and the last exit status stay with the running instance. * Which sessions the workspace has, and which one is the default. A workspace built again under the same id finds its sessions where it left them, and every instance of the workspace on the same store shares them. | `type` | Keeps them | Keys | | - | - | - | | `ram` | In the process's memory, until it exits | | | `disk` | In files under `root` | `root`, default `~/.mirage/state` | | `redis` | On Redis, under `key_prefix` and the workspace id | `url`, `key_prefix`, default `mirage:` | | `s3` | In a bucket, under `key_prefix` and the workspace id | The [S3 config fields](/home/setup/s3), `key_prefix`, default `mirage/` | The group key is `store.workspace`. It is the only store that takes `s3`, so `s3` goes on this key, never on `store.type`. ## On disk > [tab] YAML > > ```yaml theme={null} > workspace_id: agent > store: > workspace: > type: disk > root: /var/lib/mirage > ``` > [tab] Python > > ```python theme={null} > from mirage import Workspace > from mirage.workspace.store import DiskWorkspaceStateStore, RAMWorkspaceStateStore > > store = RAMWorkspaceStateStore( > workspace=DiskWorkspaceStateStore(root="/var/lib/mirage"), > ) > ws = Workspace(mounts, workspace_id="agent", store=store, owns_store=True) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { DiskWorkspaceStateStore, RAMWorkspaceStateStore, Workspace } from '@struktoai/mirage-node' > > const store = new RAMWorkspaceStateStore({ > workspace: new DiskWorkspaceStateStore({ root: '/var/lib/mirage' }), > }) > const ws = new Workspace(mounts, { workspaceId: 'agent', store, ownsStore: true }) > ``` ## On Redis > [tab] YAML > > ```yaml theme={null} > workspace_id: agent > store: > workspace: > type: redis > url: redis://redis.internal:6379/0 > ``` > [tab] Python > > ```python theme={null} > from mirage import Workspace > from mirage.workspace.store import RAMWorkspaceStateStore, RedisWorkspaceStateStore > > store = RAMWorkspaceStateStore( > workspace=RedisWorkspaceStateStore(url="redis://redis.internal:6379/0"), > ) > ws = Workspace(mounts, workspace_id="agent", store=store, owns_store=True) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { RAMWorkspaceStateStore, RedisWorkspaceStateStore, Workspace } from '@struktoai/mirage-node' > > const store = new RAMWorkspaceStateStore({ > workspace: new RedisWorkspaceStateStore({ url: 'redis://redis.internal:6379/0' }), > }) > const ws = new Workspace(mounts, { workspaceId: 'agent', store, ownsStore: true }) > ``` ## In an S3 bucket The block takes the same fields as an [S3 mount](/home/setup/s3), so credentials and an `endpoint_url` for an S3-compatible store go here too. > [tab] YAML > > ```yaml theme={null} > workspace_id: agent > store: > workspace: > type: s3 > bucket: agent-state > region: us-east-1 > ``` > [tab] Python > > ```python theme={null} > from mirage import Workspace > from mirage.vfs.s3 import S3Config > from mirage.workspace.store import RAMWorkspaceStateStore, S3WorkspaceStateStore > > store = RAMWorkspaceStateStore( > workspace=S3WorkspaceStateStore(S3Config(bucket="agent-state", region="us-east-1")), > ) > ws = Workspace(mounts, workspace_id="agent", store=store, owns_store=True) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { RAMWorkspaceStateStore, S3WorkspaceStateStore, Workspace } from '@struktoai/mirage-node' > > const store = new RAMWorkspaceStateStore({ > workspace: new S3WorkspaceStateStore({ bucket: 'agent-state', region: 'us-east-1' }), > }) > const ws = new Workspace(mounts, { workspaceId: 'agent', store, ownsStore: true }) > ``` # Installation Source: https://docs.mirage.strukto.ai/home/install Install Mirage with the Python package mirage-ai or the TypeScript packages @struktoai/mirage-node and @struktoai/mirage-browser. ## Prerequisites * **Python** 3.12 or newer for `mirage-ai` and its `mirage` CLI * **Node.js** 22.20+ on Node 22, 24.12+ on Node 24, or 25+ for `@struktoai/mirage-node` and `@struktoai/mirage-cli` * **Browser builds** can use `@struktoai/mirage-browser` with Node 20.18.1+ on Node 20, or Node 22+ * **macOS** or **Linux** (FUSE-based mounts require platform support) ## Python ```bash theme={null} uv add mirage-ai ``` This installs both the `mirage` library and the `mirage` CLI binary. Each agent framework adapter is an extra, such as `uv add 'mirage-ai[openai]'`. The runtimes that run `python3`, `node` and `js` inside Mirage are extras too, and a workspace names the one it uses in `runtimes`: ```bash theme={null} uv add 'mirage-ai[monty,quickjs]' ``` QuickJS also needs a `qjs-wasi.wasm` module; see [QuickJS installation](/home/setup/runtime/quickjs#installation). ## TypeScript Pick the package that matches your runtime — `@struktoai/mirage-core` is auto-pulled by both Node and browser entrypoints. ```bash theme={null} npm install @struktoai/mirage-node # Node.js servers and CLIs npm install @struktoai/mirage-browser # browser / edge runtimes npm install @struktoai/mirage-vercel # Vercel AI adapter; each agent framework has its own package ``` ## CLI ```bash theme={null} curl -fsSL https://strukto.ai/mirage/install.sh | sh # or npm install -g @struktoai/mirage-cli # or uvx --from mirage-ai mirage # or npx @struktoai/mirage-cli ``` Continue with the [Python](/python/quickstart), [Node](/typescript/quickstart), [browser](/typescript/browser-quickstart), or [CLI](/home/access/cli#quickstart) quickstart. ## More Details > [card] [Python](/python/install) > > VFS extras, virtualenv setup, and `uv` workflow. > [card] [TypeScript](/typescript/install) > > Native peers (FUSE, Redis) and per-runtime notes for Node, browser, and edge. # Checksums Source: https://docs.mirage.strukto.ai/home/integration/checksums Answer md5sum and sha256sum from a stored hash. `md5sum`, `sha256sum` and the other hash commands can ask your VFS for a hash it already stores, instead of reading and hashing the file. Return `None` (TypeScript: `null`) and Mirage hashes the file. For example, [Google Drive](/python/vfs/gdrive) answers `md5sum`, `sha1sum` and `sha256sum` from the hashes Drive stores. ## `checksum` The hash of one file. > [tab] Python > > ```python theme={null} > async def checksum(self, path: PathSpec, algorithm: str) -> str | None: ... > ``` > [tab] TypeScript > > ```typescript theme={null} > checksum(path: PathSpec, algorithm: string): Promise > ``` | Argument | Meaning | | - | - | | `path` | The file. | | `algorithm` | `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, or `blake2b-N` for BLAKE2b at N bits. | | Return | Mirage then | | - | - | | The lowercase hex hash of exactly the bytes a read returns | Prints it. The file is not read. | | `None` | Reads the file and hashes it. | These commands call `checksum`, with this `algorithm`: * `md5sum`, `md5`: `md5` * `sha1sum`: `sha1` * `sha224sum`: `sha224` * `sha256sum`: `sha256` * `sha384sum`: `sha384` * `sha512sum`: `sha512` * `b2sum`: `blake2b`, or `blake2b-N` with `-l N` This reads the file instead: * `-c`: check hashes listed in a file ## Example This example extends `NotesVFS` from [Custom VFS](/home/setup/custom-vfs#example-a-read-only-vfs). A real service returns the hash it stores; this one computes MD5 and leaves the others to Mirage: > [tab] Python > > ```python theme={null} > import hashlib > > from mirage import PathSpec > > from notes import NotesVFS > > > class HashedNotesVFS(NotesVFS): > async def checksum(self, path: PathSpec, algorithm: str) -> str | None: > if algorithm != "md5": > return None > return hashlib.md5(self.page(path).encode()).hexdigest() > ``` > [tab] TypeScript > > ```typescript theme={null} > import { createHash } from 'node:crypto' > import type { PathSpec } from '@struktoai/mirage-node' > import { NotesVFS } from './notes.ts' > > export class HashedNotesVFS extends NotesVFS { > override async checksum(path: PathSpec, algorithm: string): Promise { > if (algorithm !== 'md5') return null > return createHash('md5').update(this.page(path)).digest('hex') > } > } > ``` `md5sum /notes/hello.txt` then reads nothing. `sha256sum` still reads the page. # Lines Source: https://docs.mirage.strukto.ai/home/integration/lines Answer head, tail and wc -l from your service. `head`, `tail`, `wc -l` and `tail -f` can ask your VFS for lines or a count, instead of reading the file. Return exactly what a read would hold, or `None` (TypeScript: `null`) and Mirage reads the file. For example, [PostgreSQL](/python/vfs/postgres) answers `head -n 20 rows.jsonl` with `LIMIT 20` and `wc -l rows.jsonl` with `COUNT(*)`. ## `first_lines` The first lines of one file. > [tab] Python > > ```python theme={null} > async def first_lines(self, path: PathSpec, n: int) -> bytes | None: ... > ``` > [tab] TypeScript > > ```typescript theme={null} > firstLines(path: PathSpec, n: number): Promise > ``` | Argument | Meaning | | - | - | | `path` | The file. | | `n` | How many lines, 1 or more. | | Return | Mirage then | | - | - | | The first `n` lines, or all of them if the file is shorter | Prints them. The file is not read. | | `None` | Reads the file. | These commands call `first_lines`: * `head`: the first 10 lines * `head -n N`, `head -N`: the first N lines These read the file instead: * `head -c N`: the first N bytes * `head -n -N`: all but the last N lines * `head -z`: lines end with NUL * standard input ## `last_lines` The last lines of one file. > [tab] Python > > ```python theme={null} > async def last_lines(self, path: PathSpec, n: int) -> bytes | None: ... > ``` > [tab] TypeScript > > ```typescript theme={null} > lastLines(path: PathSpec, n: number): Promise > ``` | Argument | Meaning | | - | - | | `path` | The file. | | `n` | How many lines, 1 or more. | | Return | Mirage then | | - | - | | The last `n` lines, or all of them if the file is shorter | Prints them. The file is not read. | | `None` | Reads the file. | These commands call `last_lines`: * `tail`: the last 10 lines * `tail -n N`, `tail -N`: the last N lines These read the file instead: * `tail -c N`: the last N bytes * `tail -n +N`: from line N on * standard input ## `line_count` The number of lines in one file. > [tab] Python > > ```python theme={null} > async def line_count(self, path: PathSpec) -> int | None: ... > ``` > [tab] TypeScript > > ```typescript theme={null} > lineCount(path: PathSpec): Promise > ``` | Argument | Meaning | | - | - | | `path` | The file. | | Return | Mirage then | | - | - | | The number of newline characters | Prints it. The file is not read. | | `None` | Reads the file. | This command calls `line_count`: * `wc -l` These read the file instead: * `wc` with another count: `-c`, `-w`, `-m` or `-L` * standard input ## Example: head, tail and wc -l This example extends `NotesVFS` from [Custom VFS](/home/setup/custom-vfs#example-a-read-only-vfs): > [tab] Python > > ```python theme={null} > import io > > from mirage import PathSpec > > from notes import NotesVFS > > > class LinesNotesVFS(NotesVFS): > async def first_lines(self, path: PathSpec, n: int) -> bytes | None: > lines = io.StringIO(self.page(path), newline="\n").readlines() > return "".join(lines[:n]).encode() > > async def last_lines(self, path: PathSpec, n: int) -> bytes | None: > lines = io.StringIO(self.page(path), newline="\n").readlines() > return "".join(lines[max(len(lines) - n, 0) :]).encode() > > async def line_count(self, path: PathSpec) -> int | None: > return self.page(path).count("\n") > ``` > [tab] TypeScript > > ```typescript theme={null} > import type { PathSpec } from '@struktoai/mirage-node' > import { NotesVFS } from './notes.ts' > > export class LinesNotesVFS extends NotesVFS { > override async firstLines(path: PathSpec, n: number): Promise { > const lines = this.page(path).split(/(?<=\n)/) > return new TextEncoder().encode(lines.slice(0, n).join('')) > } > > override async lastLines(path: PathSpec, n: number): Promise { > const lines = this.page(path).split(/(?<=\n)/) > return new TextEncoder().encode(lines.slice(Math.max(lines.length - n, 0)).join('')) > } > > override async lineCount(path: PathSpec): Promise { > return this.page(path).split('\n').length - 1 > } > } > ``` `head -n 1`, `tail -n 1` and `wc -l` on a page then read nothing. `head -c 3` still reads it. ## `follow` The last lines of one file, then each new line as it arrives. > [tab] Python > > ```python theme={null} > async def follow( > self, path: PathSpec, n: int, interval: float > ) -> AsyncIterator[bytes] | None: ... > ``` > [tab] TypeScript > > ```typescript theme={null} > follow( > path: PathSpec, > n: number, > interval: number, > ): Promise | null> > ``` | Argument | Meaning | | - | - | | `path` | The file. | | `n` | How many of its last lines come first, 0 for none. | | `interval` | Seconds between two checks for new lines (`tail -s`, 1 by default). A service that pushes new lines can ignore it. | | Return | Mirage then | | - | - | | A stream that yields the last `n` lines, then each new whole line in order, and never ends on its own | Prints it until the caller stops `tail -f`. If the stream ends, `tail -f` exits 1 with `tail: no files remaining`. | | `None` | Reads the file every `interval` seconds. | These commands call `follow`: * `tail -f`, `tail -f -n N` on one file These read the file every `interval` seconds instead: * `tail -F`, `tail --follow=name`: follow the name, not the file * `tail -f -c N` * `tail -f -n +N` * `tail -f` on more than one file This example extends the same `NotesVFS`. A real service would push new lines over a stream; this one checks the dictionary every `interval` seconds. It yields on every check, an empty chunk when nothing is new, so a stopped `tail -f` closes it within one interval, and it starts over when the page shrinks: > [tab] Python > > ```python theme={null} > import asyncio > import io > from collections.abc import AsyncIterator > > from mirage import PathSpec > > from notes import NotesVFS > > > class FollowNotesVFS(NotesVFS): > async def follow( > self, path: PathSpec, n: int, interval: float > ) -> AsyncIterator[bytes] | None: > async def lines() -> AsyncIterator[bytes]: > seen = self.page(path) > old = io.StringIO(seen, newline="\n").readlines() > yield "".join(old[max(len(old) - n, 0) :]).encode() > while True: > await asyncio.sleep(interval) > page = self.page(path) > if len(page) < len(seen): > seen = "" > yield page[len(seen) :].encode() > seen = page > > return lines() > ``` > [tab] TypeScript > > ```typescript theme={null} > import type { PathSpec } from '@struktoai/mirage-node' > import { NotesVFS } from './notes.ts' > > export class FollowNotesVFS extends NotesVFS { > override async follow( > path: PathSpec, > n: number, > interval: number, > ): Promise | null> { > const page = (): string => this.page(path) > async function* lines(): AsyncGenerator { > let seen = page() > const old = seen.split(/(?<=\n)/) > yield new TextEncoder().encode(old.slice(Math.max(old.length - n, 0)).join('')) > for (;;) { > await new Promise((resolve) => setTimeout(resolve, interval * 1000)) > const now = page() > if (now.length < seen.length) seen = '' > yield new TextEncoder().encode(now.slice(seen.length)) > seen = now > } > } > return lines() > } > } > ``` # Integration Source: https://docs.mirage.strukto.ai/home/integration/overview Connect your backend's search and query APIs to familiar shell commands. Mirage can use your backend's search, queries and metadata to answer shell commands with fewer requests and downloads. For example, `grep` can use a RAG index to find candidate documents, and `head` can fetch a few database rows without reading the whole table. | Capability | Commands | Your backend provides | | - | - | - | | [Search](/home/integration/search) | `grep`, `rg` | Candidate files or lines from a search index. | | [Lines](/home/integration/lines) | `head`, `tail`, `wc -l` | First or last rows, line counts and live updates. | | [Checksums](/home/integration/checksums) | `md5sum`, `sha256sum` and other hash commands | A stored hash or a hash computed remotely. | | [Walks](/home/integration/walks) | `find`, `du`, `ls -R`, `tree` | A directory tree returned in bulk. | Supported VFS types already connect these capabilities where available. For a [custom VFS](/home/setup/custom-vfs), implement the methods in each guide. Mirage handles command options and formatting, and uses ordinary file reads or directory listings when a capability cannot answer. # Search Source: https://docs.mirage.strukto.ai/home/integration/search Answer grep and rg from your service's search. `grep` and `rg` can ask your VFS which files or lines may hold the text, instead of reading every file. Mirage still matches each line itself, so the output is the same. Return `None` (TypeScript: `null`) when your search cannot answer, and Mirage reads the file. For example, with [Chroma](/python/vfs/chroma) at `/knowledge/`, `grep -r refund /knowledge/` asks Chroma which documents contain `refund` and reads only those. ## When grep and rg call these methods Only when every match contains a plain text of 3 or more characters, such as `refund` in `grep 'refund.*2026'`, or a `-w` or `-x` word of any length. They never call them with these flags, and read every file instead: `grep` and `rg`: * `-v`: print lines that do not match * `-f FILE`: read patterns from a file `grep` only: * `-i`, when the text has a non-ASCII letter, or in a UTF-8 locale an `i`, `k` or `s` `rg` only: * `-i`, or `-S` with a lowercase pattern, when the text has a `k`, an `s` or a non-ASCII letter and more than 16 ways to write its case * `--passthru`: print every line * `--files-without-match`: list files with no match * `--json`: print JSON * `--stats`: print statistics * `-z`: search compressed files * `-L`: follow symlinks * `--pre COMMAND`: preprocess each file * `-E ENCODING`: read files in an encoding * `-c` or `--count-matches`, with `--include-zero` ## `files_containing` Which files under a folder may contain a text. > [tab] Python > > ```python theme={null} > async def files_containing( > self, path: PathSpec, text: str, *, whole_word: bool, ignore_case: bool > ) -> list[PathSpec] | None: ... > ``` > [tab] TypeScript > > ```typescript theme={null} > filesContaining( > path: PathSpec, > text: string, > opts: { wholeWord: boolean; ignoreCase: boolean }, > ): Promise > ``` | Argument | Meaning | | - | - | | `path` | The folder `grep -r` or `rg` walks. | | `text` | A text every match contains. Asked once per text, so `grep -r -e refund -e order` asks twice. | | `whole_word` | `True` for `-w` or `-x`: `text` must match as a whole word. | | `ignore_case` | `True` for `-i`, and for `rg -S` with a lowercase pattern. | Under `rg -i`, a text with a `k`, an `s` or a non-ASCII letter is asked once per way to write its case, with `ignore_case` `False`, since rg also matches `k` to the Kelvin sign `K` and `s` to `ſ`: `rg -i café` asks for `café`, `CAFÉ` and 14 other spellings. | Return | Mirage then | | - | - | | The files that may contain `text` | Reads only these files; the others have no match. Include every file that could match. | | An empty list | Reads no file under `path`. | | `None` | Reads every file. | These commands call `files_containing`: * `grep -r`, `grep -R`, `grep -d recurse` * `rg` on a folder A file named on the line is always read. This example extends `NotesVFS` from [Custom VFS](/home/setup/custom-vfs#example-a-read-only-vfs): > [tab] Python > > ```python theme={null} > from mirage import PathSpec > from mirage.utils.key_prefix import mounted_path > > from notes import NotesVFS > > > class SearchableNotesVFS(NotesVFS): > async def files_containing( > self, path: PathSpec, text: str, *, whole_word: bool, ignore_case: bool > ) -> list[PathSpec] | None: > if ignore_case: > return None > return [ > mounted_path(path, "/" + name) > for name, page in self.pages.items() > if text in page > ] > ``` > [tab] TypeScript > > ```typescript theme={null} > import type { PathSpec } from '@struktoai/mirage-node' > import { mountedPath } from '@struktoai/mirage-core/utils/key_prefix' > import { NotesVFS } from './notes.ts' > > export class SearchableNotesVFS extends NotesVFS { > override async filesContaining( > path: PathSpec, > text: string, > opts: { wholeWord: boolean; ignoreCase: boolean }, > ): Promise { > if (opts.ignoreCase) return null > return Object.entries(this.pages) > .filter(([, page]) => page.includes(text)) > .map(([name]) => mountedPath(path, `/${name}`)) > } > } > ``` `grep -rn mirage /notes` then reads only the pages that contain `mirage`. `mounted_path` turns a name below the mount into a path. ## `lines_containing` Which lines of one file may contain a text. > [tab] Python > > ```python theme={null} > async def lines_containing( > self, path: PathSpec, text: str, *, ignore_case: bool > ) -> bytes | AsyncIterator[bytes] | None: ... > ``` > [tab] TypeScript > > ```typescript theme={null} > linesContaining( > path: PathSpec, > text: string, > opts: { ignoreCase: boolean }, > ): Promise | null> > ``` | Argument | Meaning | | - | - | | `path` | The file `grep` or `rg` would read. | | `text` | A text every match contains. Asked once per text. | | `ignore_case` | `True` for `-i`, and for `rg -S` with a lowercase pattern. | | Return | Mirage then | | - | - | | The lines that may contain `text`, in their order, as bytes or as a stream of byte chunks | Matches them instead of reading the file, or reads the file if they hold a match. See the lists below. | | Empty bytes | The file has no match. It is not read. | | `None` | Reads the file. Return it for a file that may hold a NUL byte. | Mirage matches your lines instead of reading the file for `grep` and `rg` with no flag, or with: * `-c`: count matching lines * `-l`: list files with a match * `-q`: print nothing, exit 0 on a match * `-o`: print only the matched text * `-m N`: stop after N matches * `-i`: ignore case * `-w`: match whole words * `-x`: match whole lines * `-F`: match the text literally * `-r`: search folders * `-L`: list files with no match (`grep` only) Mirage reads the file only if your lines hold a match, and skips it if not, for `grep` and `rg` with: * `-n`: print line numbers * `-b`: print byte offsets * `-A N`, `-B N`, `-C N`: print lines around each match * more than one pattern, such as `-e a -e b` or `'a|b'` * `-z`: lines end with NUL (`grep` only; `--null-data` in `rg`) * `--column`: print column numbers (`rg` only) * `--vimgrep`: print every match with its position (`rg` only) * `-U`: match across lines (`rg` only) This example extends the same `NotesVFS`: > [tab] Python > > ```python theme={null} > import io > > from mirage import PathSpec > > from notes import NotesVFS > > > class LineSearchNotesVFS(NotesVFS): > async def lines_containing( > self, path: PathSpec, text: str, *, ignore_case: bool > ) -> bytes | None: > page = self.page(path) > if ignore_case or "\0" in page: > return None > lines = io.StringIO(page, newline="\n").readlines() > return "".join(line for line in lines if text in line).encode() > ``` > [tab] TypeScript > > ```typescript theme={null} > import type { PathSpec } from '@struktoai/mirage-node' > import { NotesVFS } from './notes.ts' > > export class LineSearchNotesVFS extends NotesVFS { > override async linesContaining( > path: PathSpec, > text: string, > opts: { ignoreCase: boolean }, > ): Promise { > const page = this.page(path) > if (opts.ignoreCase || page.includes('\0')) return null > const lines = page.split(/(?<=\n)/).filter((line) => line.includes(text)) > return new TextEncoder().encode(lines.join('')) > } > } > ``` `grep mirage /notes/todo.txt` and `grep -c mirage /notes/todo.txt` then read nothing. `grep -n mirage /notes/todo.txt` reads the page, since it holds a match. ## `before_full_walk` Whether a command may copy, compare, change or remove every file under a folder. > [tab] Python > > ```python theme={null} > async def before_full_walk( > self, path: PathSpec, *, files: int | None = None > ) -> None: ... > ``` > [tab] TypeScript > > ```typescript theme={null} > beforeFullWalk(path: PathSpec, files: number | null): Promise > ``` | Argument | Meaning | | - | - | | `path` | The folder a command is about to read, change or remove in full. | | `files` | How many files the session sees under `path`; `None` when Mirage could not count them. | | Return | Mirage then | | - | - | | Nothing | Runs the command. | | Raises `ValueError` (TypeScript: rejects) | Refuses the command before it touches anything. It prints `: ` and exits 1. | These commands call `before_full_walk`: `tar -c`, `zip -r`, `cp -r`, `rm -r`, `chmod -R`, `chown -R`, `chgrp -R`, `mv` to another mount and `diff -r`. Mirage refuses more than the command's `walk_limit` files before it asks, so the default lets the walk run. ## `walk_limit` The most files one command walks under a folder (TypeScript: `walkLimit`), a field of [`command_limits`](/home/core/output-limits). | Command | Past the limit | | - | - | | `grep -r`, `rg` | Stops. It keeps what it printed, prints `grep: : stopped after files (walk_limit); narrow the path` and exits 2. | | `git grep` | Stops. It keeps what it printed, prints `fatal: stopped after files (walk_limit); narrow the pathspec` and exits 128. | | `find`, `ls -R`, `du`, `tree`, `getfattr -R` | Stops listing. It keeps what it printed, prints the same `stopped after` line and exits 1 (`tree`: 2). | | `git status`, `git add`, `git commit -a`, `git diff`, `git checkout`, `git reset`, `git rm` | Refused before it changes anything. It prints `fatal: more than files in the work tree (walk_limit)` and exits 128. `git add`, `git diff` and `git rm` given paths walk only those, and a file named outright costs nothing. | | A glob, such as `cat /notes/*` | Refused, so the command does not run. It prints `cat: Argument list too long` and `cat: /notes/*: matches more than files (walk_limit); narrow the path`, and exits 126. | | `tar -c`, `zip -r`, `cp -r`, `rm -r`, `chmod -R`, `chown -R`, `chgrp -R`, `mv` to another mount, `diff -r`, `gzip -r` | Refused before it touches anything (`before_full_walk`). It prints `tar: more than files in scope (walk_limit); narrow the path` and exits 1. | A search counts only the files it reads, so a file `files_containing` rules out costs nothing. A listing counts every entry it lists, folders included. Each command exits as it does when some files could not be read, so a script treats a walk cut short as one with an error. A glob, a copy and a removal are refused instead of cut short, since running on part of what they name would look complete later. A glob in a `for` list stops the line with `bash: /notes/*: matches more than files (walk_limit); narrow the path`. A walk that crosses into another mount counts that mount's files against its own limit, and names that mount's folder where it stops. Codex's `fs/walk` ([exec-server](/home/agents/codex#exec-server-forward)) lists the same way and returns `truncated: true` where it stops. | Value | Searches and listings | Globs, copies and removals | | - | - | - | | `-1` | Walk every file | Never refused | | `0` | Read or list nothing under a folder | Always refused | | A positive number | Stop after that many files | Refused above that many files | It is 1000 unless your VFS starts at another value or a `command_limits` entry sets it: > [tab] Python > > ```python theme={null} > class SearchableNotesVFS(NotesVFS): > walk_limit = 500 > ``` > [tab] TypeScript > > ```typescript theme={null} > export class SearchableNotesVFS extends NotesVFS { > override walkLimit = 500 > } > ``` `grep -r mirage /notes` on a folder of 600 pages that `files_containing` cannot narrow then prints the matches in the first 500 pages, and: ```text theme={null} grep: /notes: stopped after 500 files (walk_limit); narrow the path ``` ## Built-in VFSs These VFSs answer `grep -r` and `rg` with their service's search. A pattern outside **Searches**, or a VFS not listed, reads every file. A search that can miss a match leaves out a file that holds the text, so `grep` does not print it. | VFS | Searches | Can miss a match | | - | - | - | | [Google Drive](/python/vfs/gdrive#integration) | Whole words (`-w`, `-x`) | Docs, Sheets and Slides JSON, office files, PDFs, archives, the end of large files, recent writes | | [Google Docs](/python/vfs/gdocs#integration), [Sheets](/python/vfs/gsheets#integration), [Slides](/python/vfs/gslides#integration) | Whole words | Words only in non-text values (fonts, links, formulas) or split by styling | | Google Calendar | Whole words | No | | [Dropbox](/python/vfs/dropbox#integration) | Whole words | Office files, PDFs, archives, the end of large files, recent writes; file contents below the Professional plan | | [Box](/python/vfs/box#integration) | Whole words | Office files, PDFs, archives, the end of large files, recent writes | | [OneDrive](/python/vfs/onedrive#integration), [SharePoint](/python/vfs/sharepoint#integration) | Whole words; SharePoint within one document library | Office files, PDFs, archives, the end of large files, recent writes | | [Slack](/python/vfs/slack#integration) | Whole words, with a user token | Recent messages, words only in other fields (bot names, link previews) | | [Trello](/python/vfs/trello#integration) | Whole words | Recent writes | | [Linear](/python/vfs/linear#integration) | Issues: whole words. Other files: any text | Recent issue writes | | [Gmail](/python/vfs/gmail#integration) | Any ASCII text | No | | [Email (IMAP)](/python/vfs/email#integration) | Any text | On a server that searches words, not substrings | | [GitHub](/python/vfs/github#integration) | Whole words, default branch, more than 100 files | Recent pushes | | [Chroma](/python/vfs/chroma#integration) | Any text; `-i` reads every page | No | | [Qdrant](/python/vfs/qdrant#integration) | Any ASCII text | No | | [LanceDB](/python/vfs/lancedb#integration) | Any text; not tables with list, struct or bytes columns | No | | [SSH](/python/vfs/ssh#integration) | Any text, on servers that run commands | No | | [PostgreSQL](/python/vfs/postgres#integration), [MongoDB](/python/vfs/mongodb#integration), [Airtable](/python/vfs/airtable#integration) | Any text, as lines of one file | No | Every built-in VFS starts at 1000, or 5000 on GitHub, where each file is one request, and 10000 on disk, RAM and OPFS. A mount's `command_limits` change it: the `"@all"` entry, for every command, else the workspace's, sets the mount's own `walk_limit`, and an entry named for one command, such as `find`, changes only how far that command walks. On the VFSs above from Google Drive to GitHub, the mount's own `-1` also turns the service's search off, so every file is read and no match is missed: > [tab] Python > > ```python theme={null} > import os > > from mirage import Limit, MountMode, Workspace > from mirage.vfs.slack import SlackConfig, SlackVFS > > slack = SlackVFS( > config=SlackConfig( > token=os.environ["SLACK_BOT_TOKEN"], > search_token=os.environ["SLACK_USER_TOKEN"], > ) > ) > ws = Workspace( > {"/slack": (slack, MountMode.READ, {"@all": Limit(walk_limit=5000)})}, > mode=MountMode.READ, > ) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { Limit, MountMode, SlackVFS, Workspace } from '@struktoai/mirage-node' > > const slack = new SlackVFS({ > token: process.env.SLACK_BOT_TOKEN!, > searchToken: process.env.SLACK_USER_TOKEN, > }) > const ws = new Workspace( > { '/slack': [slack, MountMode.READ, { '@all': new Limit({ walkLimit: 5000 }) }] }, > { mode: MountMode.READ }, > ) > ``` > [tab] YAML > > ```yaml theme={null} > mounts: > /slack: > vfs: slack > mode: read > config: > token: ${SLACK_BOT_TOKEN} > search_token: ${SLACK_USER_TOKEN} > command_limits: > "@all": > walk_limit: 5000 > ``` `grep -rw refund /slack/channels/` then asks Slack's search which days mention `refund` and reads only those. `grep -r refund /slack/channels/`, which Slack cannot narrow, reads the first 5000 days and stops there. # Walks Source: https://docs.mirage.strukto.ai/home/integration/walks Answer find, du, ls -R and tree from one listing. `find`, `du`, `ls -R`, `tree`, `grep -r` and `rg` can ask your VFS for a whole folder tree in one call, instead of listing each folder. Return `None` (TypeScript: `null`) and Mirage lists each folder. For example, [S3](/python/vfs/s3) answers `find /data/` from one recursive listing of the prefix. ## `read_tree` Every file and folder below one folder. > [tab] Python > > ```python theme={null} > async def read_tree(self, path: PathSpec) -> dict[str, FileStat] | None: ... > ``` > [tab] TypeScript > > ```typescript theme={null} > readTree(path: PathSpec): Promise | null> > ``` | Argument | Meaning | | - | - | | `path` | The folder. | | Return | Mirage then | | - | - | | Every file and folder below `path`, keyed by its path below it (`guides`, `guides/start.md`), each with the `FileStat` that `stat` gives | Walks it without listing any folder. | | `None` | Lists each folder with `readdir`. | For a path that is not a folder, raise what `readdir` raises. These commands call `read_tree`: * `find` * `du` * `ls -R` * `tree` * `grep -r`, `rg` * `cp -r` inside the mount, when your VFS overrides `copy` These list each folder instead: * `find -maxdepth N` * `tree -L N` * `rg --max-depth N` * `ls` without `-R` * `cp -r` to another mount ## `walk_limit` Every walk stops at its command's [`walk_limit`](/home/integration/search#walk_limit) on your mount, whether `read_tree` answered or Mirage listed each folder. It is a field of [`command_limits`](/home/core/output-limits): the `"@all"` entry sets it for every command, and an entry named for one command, such as `find`, changes only how far that command walks. The mount's `"@all"` entry, else the workspace's, also sets your VFS's own `walk_limit`, which decides how it searches: with the service's search under a cap, by reading every file at `-1`. Return `None` for a folder too large to send in one call: Mirage then stops calling `readdir` once the limit is spent. To stop paging early, take `limit` (TypeScript: `handed.limit`), how many entries the walk can still use: > [tab] Python > > ```python theme={null} > async def read_tree(self, path: PathSpec, limit: int | None = None) -> dict[str, FileStat] | None: ... > async def readdir(self, path: PathSpec, limit: int | None = None) -> list[FileStat] | DirListing: ... > ``` > [tab] TypeScript > > ```typescript theme={null} > readTree(path: PathSpec, handed?: Handed): Promise | null> > readdir(path: PathSpec, handed?: Handed): Promise > ``` | Function | Past `limit` entries | | - | - | | `read_tree` | Return `None`; Mirage lists each folder instead. | | `readdir` | Return what you hold as a `DirListing` with `partial=True`; Mirage does not keep it as the whole folder. | `limit` is `None` (TypeScript: `undefined`) when nothing caps the walk. Without it, `read_tree` returns the whole tree and the command keeps what fits. ## Example This example extends `NotesVFS` from [Custom VFS](/home/setup/custom-vfs#example-a-read-only-vfs). Its pages sit in one folder, so one `readdir` is the whole tree; a service with nested folders would return them all from one recursive call: > [tab] Python > > ```python theme={null} > from mirage import FileStat, PathSpec > > from notes import NotesVFS > > > class TreeNotesVFS(NotesVFS): > async def read_tree(self, path: PathSpec) -> dict[str, FileStat] | None: > return {entry.name: entry for entry in await self.readdir(path)} > ``` > [tab] TypeScript > > ```typescript theme={null} > import type { FileStat, PathSpec } from '@struktoai/mirage-node' > import { NotesVFS } from './notes.ts' > > export class TreeNotesVFS extends NotesVFS { > override async readTree(path: PathSpec): Promise | null> { > return new Map((await this.readdir(path)).map((entry) => [entry.name, entry])) > } > } > ``` `find /notes`, `du -a /notes`, `ls -R /notes` and `tree /notes` then call `read_tree` once. `find /notes -maxdepth 1` lists the folder instead. # Introduction Source: https://docs.mirage.strukto.ai/home/introduction A composable, scriptable and durable virtual terminal for AI agents. Mirage is a virtual terminal for AI agents, with a unified virtual filesystem, virtual CLIs and a router that picks where each command runs. * **Composable.** The filesystem, CLIs, shell and compute are separate parts you put together. Run the terminal in your app or a FastAPI or Fastify server, and send programs to a microVM or sandbox. * **Scriptable.** A scriptable policy engine, written in code or as scripts, hides files per agent profile, refuses commands, asks for approval, caps output and routes commands to machines. * **Durable.** Each part can live in your own storage: sessions in RAM, each shell job's output in Redis, and the history of every command on disk. ## Architecture ![Mirage connects agents to files, tools, machines and runtimes, with access controls and notifications](https://mintcdn.com/struktoai/DFcmqNyceJW-5m2z/images/mirage-overview-light.svg?fit=max\&auto=format\&n=DFcmqNyceJW-5m2z\&q=85\&s=924ce92bc557439868d62e838557ca0e) * **[Virtual filesystem](/home/setup/vfs).** Virtualize S3, Drive, Slack, databases and more under one root, accessible with `ls`, `cat`, `grep` and `find`. * **[Virtual CLIs](/home/setup/clis).** Give agents commands such as `git`, `slack` and `ntn`, with credentials configured per tool. * **[Mirage shell](/home/core/shell).** Compose files, CLIs and machines with pipes, redirects, variables and jobs. * **[Agent profiles](/home/profiles).** Choose what each agent can run and which files and folders it can see. * **[Policy engine](/home/policy/policies).** Apply rules to commands, file operations and connections before they run. * **[Machines](/home/setup/machine/overview).** Run programs on a container, microVM, cloud sandbox or SSH host. * **[Runtimes](/home/setup/runtime/overview).** Run code in the workspace or on your host. * **[Service credentials](/home/authentication).** Connect credentials from environment variables, dotenv, AWS Secrets Manager or 1Password. * **[Notifications](/home/notifications).** Notify agents about external file or directory changes in the virtual filesystem. ## Benefits * **Fewer tokens.** One shell interface replaces a tool per service. Across 200 tasks, it used 52% fewer tokens per task than MCP tools ([AgentVFS](https://agentvfs.org/blogs/agentvfs-1)). * **Cloud search through shell commands.** With Chroma at `/knowledge/`, `grep -r refund /knowledge/` asks Chroma which documents match, then reads only those. A backend without search reads its files. See [Search](/home/integration/search). * **Full control.** Choose which files each agent can see and which commands it can run with [agent profiles](/home/profiles) and [policies](/home/policy/overview). ## Try Mirage [Install Mirage](/home/install), then create a workspace with an in-memory filesystem, write a file with a POSIX-style call, and search it with the shell. No credentials or services are needed. > [tab] Python > > ```python theme={null} > import asyncio > > from mirage import MountMode, RAMVFS, Workspace > > > async def main() -> None: > ws = Workspace({"/data": RAMVFS()}, mode=MountMode.WRITE) > await ws.vfs.write("/data/hello.txt", b"hello mirage\n") > result = await ws.shell("grep -n hello /data/hello.txt") > print(await result.stdout_str(), end="") > await ws.close() > > > asyncio.run(main()) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node' > > const ws = new Workspace({ '/data': new RAMVFS() }, { mode: MountMode.WRITE }) > await ws.vfs.write('/data/hello.txt', new TextEncoder().encode('hello mirage\n')) > const result = await ws.shell('grep -n hello /data/hello.txt') > process.stdout.write(result.stdoutText) > await ws.close() > ``` > [tab] CLI > > [Install the CLI](/home/install#cli), then run: > > ```bash theme={null} > cat > workspace.yaml <<'EOF' > mounts: > /data: > vfs: ram > mode: write > EOF > > mirage workspace create workspace.yaml --id hello > echo "hello mirage" | mirage workspace vfs write /data/hello.txt -w hello > mirage shell -w hello -c 'grep -n hello /data/hello.txt' > ``` The search prints: ```text theme={null} 1:hello mirage ``` `/data` is a path inside Mirage. Replace RAM with a [supported VFS](/home/setup/vfs) to use the same commands on your own data. Continue with the [Python](/python/quickstart) or [TypeScript](/typescript/quickstart) quickstart. ## Example Use Cases * **Respond to changes.** React to Slack replies or GitHub pushes through file notifications. * **Search connected data.** Use `grep` for text search and `search` for semantic matches in vector stores. * **Investigate traces.** Query Langfuse and Jaeger traces with `grep` and `jq`. ## FAQ > [accordion] Do I need FUSE? > > No. Agents can use workspace files through Mirage directly. Use [FUSE](/home/setup/fuse) when host tools, such as editors or language servers, need to open those files. > [accordion] Where does the shell run? Is it really bash? > > Mirage provides a Bash-compatible shell in your application. It supports common commands, pipes, redirects, variables and jobs. See the [shell guide](/home/core/shell) for supported behavior and differences from Bash. > [accordion] Is it sandboxed? > > The shell sees the files you mount. The Monty and QuickJS runtimes cannot access host files or the network. Other runtimes have different access; see [runtime file and network access](/home/setup/runtime/overview#files) before choosing one. > [accordion] What about latency and cost? > > Operations use the APIs of the services you connect, so their latency and usage charges apply. > [accordion] Hosted or self-hosted? > > Self-hosted. Run Mirage in your own application, server or sandbox, and connect the services you need. > [accordion] Which agent frameworks are supported? > > Any agent that can call a shell tool can use Mirage. See the [agent integrations](/home/agents) for setup guides. > [accordion] Python or TypeScript? > > Both SDKs provide workspaces, shell commands and service integrations. Runtime availability differs; see the [runtime comparison](/home/setup/runtime/overview). Start with the [Python](/python/quickstart) or [TypeScript](/typescript/quickstart) quickstart. > [accordion] What if a VFS I want isn't supported yet? > > You can add a custom filesystem. See [Add a VFS](/python/vfs/new) for the required API and examples. ## Explore Mirage > [card] [Python Quickstart](/python/quickstart) > > Create a workspace, mount your sources, and run shell commands in minutes. > [card] [TypeScript Quickstart](/typescript/quickstart) > > Same Workspace API in Node, browser, and edge runtimes. > [card] [CLI](/home/access/cli) > > Drive workspaces from the shell: create, run shell lines, snapshot, and restore. > [card] [Supported VFS](/home/setup/vfs) > > Compare supported VFS types and connect S3, Drive, Slack and more. ## Community & Support To let your coding agent search these docs, connect it to the docs MCP server at `https://docs.mirage.strukto.ai/mcp`. > [card] [Need Help?](/home/troubleshooting) > > Setup failures, credential issues, and FUSE gotchas. > [card] [Book a Call](https://cal.com/strukto/30min) > > Talk to the team directly if you are blocked. > [card] [Join our Discord](https://discord.gg/u8BPQ65KsS) > > Chat with the community and get help from the team. > [card] [GitHub Issues](https://github.com/strukto-ai/mirage/issues) > > Report bugs, request features, or ask questions. # Overview Source: https://docs.mirage.strukto.ai/home/notifications Notify agents when files or directories change in the virtual filesystem. Notifications tell an agent when files or directories change in the virtual filesystem. For example, a teammate edits a report in connected storage, and your agent receives the report's virtual path and what happened to it. ## How it works 1. Your application receives a service notification or checks for changes. 2. It reports each change to Mirage with `ws.notify()`. 3. The agent receives it through `ws.events()`. Your application connects the service's notifications to Mirage. Subscribing with `ws.events()` alone does not start a file watcher or check the service. ## Listen for changes Here, `ws` is your workspace with a VFS connected at `/data`. This listens for changes anywhere under that path: ```python Python theme={null} async for change in ws.events("/data"): print(f"Event: {change.kind.value}") print(f"Virtual path: {change.path.virtual}") ``` ```typescript TypeScript theme={null} for await (const change of ws.events('/data')) { console.log(`Event: ${change.kind}`) console.log(`Virtual path: ${change.path.virtual}`) } ``` For example, after your application reports an edit to `report.csv`, the listener prints: ```text Output theme={null} Event: update Virtual path: /data/report.csv ``` `update` means the existing file's contents or metadata changed. To listen to fewer files, change the path: | Path | Notifications received | | - | - | | `/data/reports` | Changes anywhere inside the reports directory | | `/data/*.csv` | Changes to CSV files directly inside `/data` | | `["/data/reports", "/data/config.json"]` | Changes under reports or to the config file | ## Notification types Each notification includes the virtual path and what happened: | Event | Meaning | | - | - | | `create` | A file or directory was added | | `update` | Its contents or metadata changed | | `delete` | It was removed | | `move` | It was renamed or moved; the notification also includes its previous path | | `unknown` | Something changed, but the details are unavailable; check the path again | ## Connect your VFS * **Push:** Receive changes from a webhook, stream or external file watcher. See the [Disk, S3 and GitHub examples](/home/notifications/support#push-examples). * **Poll:** Fetch changes from a service. See the [Dropbox, Box and Google Drive examples](/home/notifications/support#poll-examples). [VFS Notifications](/home/notifications/support) lists the supported services, Python and TypeScript functions, and how to report a change with `ws.notify()`. # VFS Notifications Source: https://docs.mirage.strukto.ai/home/notifications/support Notification services and Python and TypeScript functions for reporting file and directory changes in the virtual filesystem. Connect your VFS to a notification service using Push or Poll. See the [overview](/home/notifications) for listening to changes and event types. ## Push Receive file changes through webhooks, streams or external file watchers. Convert them with the functions below, then call `ws.notify()` for each change. See the [Python and TypeScript examples](#push-examples). | VFS | Notification service | Python method | TypeScript method | | - | - | - | - | | Disk | External tools: [watchdog](https://github.com/gorakhargosh/watchdog) / [chokidar](https://github.com/paulmillr/chokidar) | `DiskEventHook.to_events` | `DiskEventHook.toEvents` | | S3 | [S3 Event Notifications](https://docs.aws.amazon.com/AmazonS3/latest/userguide/EventNotifications.html) | `S3EventHook.to_events` | `S3EventHook.toEvents` | | GitHub | [Push webhooks](https://docs.github.com/en/webhooks/webhook-events-and-payloads#push) | `GitHubEventHook.to_events` | `GitHubEventHook.toEvents` | | Nextcloud | [Webhook Listeners](https://docs.nextcloud.com/server/latest/admin_manual/webhook_listeners/index.html) | `NextcloudEventHook.to_events` | `NextcloudEventHook.toEvents` | | MongoDB | [Change streams](https://www.mongodb.com/docs/manual/changestreams/) | `MongoDBEventHook.to_events` | `MongoDBEventHook.toEvents` | | GridFS | [Change streams](https://www.mongodb.com/docs/manual/changestreams/) on `.files` | `GridFSEventHook.to_events` | `GridFSEventHook.toEvents` | | Slack | [Events API](https://docs.slack.dev/apis/events-api/) | `SlackEventHook.to_events` | `SlackEventHook.toEvents` | | Redis | [Keyspace notifications](https://redis.io/docs/latest/develop/pubsub/keyspace-notifications/) | `RedisEventHook.to_events` | `RedisEventHook.toEvents` | | Discord | [Gateway events](https://docs.discord.com/developers/events/gateway-events) | `DiscordEventHook.to_events` | `DiscordEventHook.toEvents` | | Linear | [Webhooks](https://linear.app/developers/webhooks) | `LinearEventHook.to_events` | `LinearEventHook.toEvents` | | Trello | [Webhooks](https://developer.atlassian.com/cloud/trello/guides/rest-api/webhooks/) | `TrelloEventHook.to_events` | `TrelloEventHook.toEvents` | | Notion | [Webhooks](https://developers.notion.com/reference/webhooks) | `NotionEventHook.to_events` | `NotionEventHook.toEvents` | | Email | [IMAP IDLE](https://datatracker.ietf.org/doc/html/rfc2177) | `EmailEventHook.to_events` | `EmailEventHook.toEvents` | | Box | [Events API](https://developer.box.com/guides/events/user-events/polling), read by your own long poll | `BoxEventHook.to_events` | `BoxEventHook.toEvents` | ### Push examples | Backend | Python | TypeScript | What to provide | | - | - | - | - | | Disk | [disk.py](https://github.com/strukto-ai/mirage/blob/main/examples/python/notifications/push/disk.py) | [disk.ts](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/notifications/push/disk.ts) | Nothing; changes temporary files locally | | S3 | [s3.py](https://github.com/strukto-ai/mirage/blob/main/examples/python/notifications/push/s3.py) | [s3.ts](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/notifications/push/s3.ts) | `S3_BUCKET` and a saved S3 notification JSON file | | GitHub | [github.py](https://github.com/strukto-ai/mirage/blob/main/examples/python/notifications/push/github.py) | [github.ts](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/notifications/push/github.ts) | `GITHUB_TOKEN`, `GITHUB_REPOSITORY` (`owner/repo`), and a saved push webhook JSON file; `GITHUB_REF` accepts a short name or full ref and defaults to `main` | The S3 and GitHub examples process a saved payload; they do not start a webhook server. Run from the repository root after installing the language's dependencies: ```bash Python theme={null} ./python/.venv/bin/python examples/python/notifications/push/disk.py ./python/.venv/bin/python examples/python/notifications/push/s3.py notification.json ``` ```bash TypeScript theme={null} pnpm -C examples/typescript exec tsx notifications/push/disk.ts pnpm -C examples/typescript exec tsx notifications/push/s3.ts /absolute/path/to/notification.json ``` The Disk example creates, updates and deletes temporary local files, then reports those changes directly to Mirage. It prints: ```text Disk output theme={null} read before: 'first quarter' file changes: create /data/reports/q3.txt update /data/reports/q1.txt delete /data/reports/q2.txt read after notify: 'first quarter, revised' listing: q1.txt q3.txt ``` For S3, a saved `ObjectCreated:Put` notification for `report.csv` in your configured bucket produces: ```text S3 output theme={null} create: /s3/report.csv ``` ## Poll Fetch changed files from the service, on a schedule or after a notification. Create `hook` with `vfs.delta_hook()` (Python) or `vfs.deltaHook()` (TypeScript). Call `await hook.pull(root, checkpoint)`, send each item in `result.changes` to `ws.notify()`, and save `result.checkpoint` for the next call. The first call, with `None` (`null` in TypeScript) as the checkpoint, only records a baseline: it returns no changes and the checkpoint to start from. See the [Python and TypeScript examples](#poll-examples). | VFS | Notification service | Python | TypeScript | | - | - | - | - | | Airtable | [Webhooks API](https://airtable.com/developers/web/api/webhooks-overview) | `vfs.delta_hook()` | `vfs.deltaHook()` | | Box | [Long-poll events](https://developer.box.com/guides/events/user-events/polling) | `vfs.delta_hook()` | `vfs.deltaHook()` | | Dropbox | [Webhooks or long polling](https://docs.dropboxapi.com/dropbox-api/docs/detecting-changes) | `vfs.delta_hook()` | `vfs.deltaHook()` | | Gmail | [Pub/Sub notifications](https://developers.google.com/workspace/gmail/api/guides/push) | `vfs.delta_hook()` | `vfs.deltaHook()` | | Google Calendar | [Push notifications](https://developers.google.com/workspace/calendar/api/guides/push) | `vfs.delta_hook()` | `vfs.deltaHook()` | | Google Drive, Docs, Sheets, Slides | [Drive notifications](https://developers.google.com/workspace/drive/api/guides/push) | `vfs.delta_hook()` | `vfs.deltaHook()` | | OneDrive / SharePoint | [Microsoft Graph notifications](https://learn.microsoft.com/en-us/graph/change-notifications-overview) | `vfs.delta_hook()` | `vfs.deltaHook()` | For other VFS types, your application can detect changes and report them directly with `ws.notify()`. ### Poll examples | Backend | Python | TypeScript | Environment variables | | - | - | - | - | | Dropbox | [dropbox.py](https://github.com/strukto-ai/mirage/blob/main/examples/python/notifications/poll/dropbox.py) | [dropbox.ts](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/notifications/poll/dropbox.ts) | `DROPBOX_APP_KEY`, `DROPBOX_APP_SECRET`, `DROPBOX_REFRESH_TOKEN` | | Box | [box.py](https://github.com/strukto-ai/mirage/blob/main/examples/python/notifications/poll/box.py) | [box.ts](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/notifications/poll/box.ts) | `BOX_ACCESS_TOKEN` | | Google Drive | [gdrive.py](https://github.com/strukto-ai/mirage/blob/main/examples/python/notifications/poll/gdrive.py) | [gdrive.ts](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/notifications/poll/gdrive.ts) | `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, `GOOGLE_REFRESH_TOKEN` | Dropbox waits for a long-poll notification. Box and Google Drive check every five seconds. Start an example, then edit files in that service to see their virtual paths. Press Ctrl-C to stop. Each run starts from the current state. ```bash Python theme={null} ./python/.venv/bin/python examples/python/notifications/poll/box.py ``` ```bash TypeScript theme={null} pnpm -C examples/typescript exec tsx notifications/poll/box.ts ``` For example, start the Box example, then upload a new `report.csv` to the root folder in Box: ```text Example output theme={null} Watching /box; edit files in the service (Ctrl-C to stop) create: /box/report.csv ``` # Explain Source: https://docs.mirage.strukto.ai/home/policy/explain What the agent sees of policy, and how it asks what a line or a VFS call would do before running it. The agent meets policy two ways: the answer it reads when an action is refused, and explain, which says what a line or a VFS call would do without running it. ## What the agent reads A refusal reads as a real terminal's. The reason travels beside it. | Refused | The agent reads | | - | - | | a line or a command | `rm: Permission denied`, exit 126 | | one path | the command's own error: `cat: /data/k: Permission denied`, exit 1 | | a write to a read-only mount | the command's own error: `rm: cannot remove '/data/a': Read-only file system`, exit 1 | | a VFS call | `EACCES` | | a variable write | `KEY: permission denied`, exit 1 | | an ask | the same as a deny, until a host approves; then the retry runs | | a hidden path, or a link that leads to one | `No such file or directory`, as if it did not exist | The reason is on the result's `decision`, never in stderr: ```python theme={null} r = await ws.shell("git push --force origin main") r.decision # PolicyDecision(kind='deny', reason='force pushes go through an operator', policy='NoForcePush', ask_id=None) ``` The [agent tools](/python/access/in-app#session-tools), which MCP and the agent adapters serve, add one line to their text: `policy denied: `, or `requires approval: (ask )`. A hidden path adds nothing, here or in explain: the agent never learns it exists. ### Which tools the agent gets `session.tools.names()` lists only the tools the session's profile leaves it: `shell` needs a command the allow list allows, `ls` and `grep` those commands, `write` and `edit` a mount the session may write. MCP, RPC and the agent adapters offer exactly those, so an agent is never offered a tool every call of which would be refused. ## Explain Explain asks every policy about a line or a VFS call and returns their answer. Nothing runs, nothing is written and no ask is spent. ```python theme={null} explain = (await ws.session("agent")).explain line = await explain.shell("cat /data/keys/k") call = await explain.vfs.read("/data/keys/k") ``` ```typescript theme={null} const explain = (await ws.session('agent')).explain const line = await explain.shell('cat /data/keys/k') const call = await explain.vfs.read('/data/keys/k') ``` `explain.vfs` has the same 23 calls as `session.vfs`. An agent can ask too, through MCP, HTTP, RPC or the CLI: | Entry point | A line | A VFS call | | - | - | - | | In-app | `session.explain.shell(line)` | `session.explain.vfs.(...)` | | [MCP](/home/access/mcp#vfs-calls), with `?calls=all` | `shell` with `explain: true` | `vfs_` with `explain: true` | | [HTTP](/api/operations/shell/run-shell-command) | `POST /shell?explain=true` | `POST /vfs/?explain=true` | | [RPC](/home/access/rpc) | `shell` with `explain: true` | `vfs/` with `explain: true` | | [CLI](/home/access/cli#run-lines-vfs-calls-and-tools) | `mirage shell -w ID -s SESSION -c LINE --explain` | `mirage workspace vfs CALL ARGS -w ID -s SESSION --explain` | Every entry point returns the same JSON schema. Explain reads the line only, so stdin, `cwd`, `runtime` and a background job are refused with it. ### What it evaluates Explain stops before anything runs, evaluating only pre-execution checks: | Explained | Evaluates | Never evaluates | | - | - | - | | A line | the profile's rules, `pre_execute`, `pre_command` | `pre_vfs`, every `post_` method | | A VFS call | the profile's rules, `pre_vfs` | every `post_` method | The `post_` methods need a result. A line's file calls reach `pre_vfs` only when the line runs; explain a specific VFS call to see its admission result without executing the line. ### What comes back With a profile that denies `/data/keys/*`: ```json theme={null} { "call": "read", "paths": ["/data/keys/k"], "outcome": "deny", "reason": "keys stay sealed", "source": "top", "decision": {"kind": "deny", "reason": "keys stay sealed", "policy": "PermissionsPolicy", "ask_id": null}, "answers": [{"kind": "deny", "reason": "keys stay sealed", "policy": "PermissionsPolicy"}], "error": "EACCES" } ``` | Field | Meaning | | - | - | | `outcome` | `allow`, `deny` or `ask` | | `reason` | the deciding answer's reason, or empty | | `source` | where the profile writes the rule (`top`, `mounts./runbook`, `commands.allow`); empty for a coded policy | | `answers` | every policy that answered, in order; a route names its `runtime` and its `reason`, empty when it gave none | | `decision` | the record the agent would get, or `null` | | `error` | a VFS call only: the error it would raise (`EACCES`, `EROFS`), or empty | A line adds `exit_code` and `stderr`, what the agent would read, and `node`, the line as a tree of commands. Each command in the tree has its own `outcome`, `answers`, `exit_code`, `stderr`, `runtime` and `words`, the command line word by word as policies read it (see [Context](/home/policy/policies#context)). Under an `@line` runtime, every command's `runtime` names it. A program only `@external` takes (`make`, `gcc`) names the runtime that takes it. ### A line `mirage shell --explain` prints the tree: ```text theme={null} cat /data/a | wc -l && echo $(cat /data/keys/k) [deny, exit 1: keys stay sealed] list: cat /data/a | wc -l && echo $(cat /data/keys/k) pipeline: cat /data/a | wc -l cat /data/a [allow] wc -l [allow] echo $(cat /data/keys/k) [allow] substitution: cat /data/keys/k cat /data/keys/k [deny, exit 1: keys stay sealed] top ``` The line's `outcome`, `exit_code` and `stderr` are what holds the whole line before any of it runs: a `pre_execute` answer, or a profile rule on any command, the first such command giving the line its answer. A refusal met only when its command runs shows on that command alone, and the line stays `allow`: a word missing from the allow list, and a policy's `pre_command` answer. ```text theme={null} rm /data/a; echo done [allow, exit 0] rm /data/a [deny, exit 126] commands.allow echo done [allow] ``` ### Limits * A hidden path explains like any path no rule names. * A policy that reads a file to decide still reads it. # Policy Source: https://docs.mirage.strukto.ai/home/policy/overview Decide what an agent may run, read, write and connect to in the virtual terminal. Policy decides what an agent may do in the virtual terminal: the commands it runs, the files it reads and writes, and the connections it opens. A policy is a class with a pair of methods for each thing an agent does, or [programs](/home/policy/scripts) a profile names for those methods: | The agent | Methods | | - | - | | runs a line | `pre_execute`, `post_execute` | | runs a command or CLI | `pre_command`, `post_command` | | uses files: commands, file CLIs, runtime file APIs, file tools, `session.vfs`, FUSE, SFTP | `pre_vfs`, `post_vfs`; see [Lifecycle](/home/policy/policies#lifecycle) | | opens a connection: `curl`, a CLI's API call, a mount's read, an SDK | `pre_network`, `post_network` | A `pre_` method runs before the action executes; a `post_` method runs afterward with the execution result. A policy decision can permit, refuse, [request host approval](/home/policy/policies#asks), bound the output, or select the target runtime. No policy can permit what another refuses. Policies evaluate in sequence: built-in checks first (mount modes, path restrictions, [runtime routing](/home/policy/route-runtime)), followed by the session profile, and finally the workspace policies in the order they were added. ## Why not a tool-call check A harness's tool-call check, such as Claude Code's `PreToolUse` or an SDK's `can_use_tool`, sees one tool call: a tool name and a string such as `cat $(ls /data | head -1)`. A Mirage policy runs inside the shell and the filesystem, so it sees what that string only implies. | | Tool-call check | Mirage policy | | - | - | - | | Commands | the raw string; `$( )`, `xargs`, `find -exec`, `eval` and variables hide what runs | every command after expansion, nested ones included | | Files | the paths written in the string | profile rules and file hooks check paths a command reaches, such as each one `grep -r`, `tar` or `cp -r` reaches | | Ways in | that harness's own tools | every session and entry point: the SDK, MCP, HTTP, RPC, SSH, FUSE | ## In this section * [Policies](/home/policy/policies): write one: its methods, what each can answer, and asks. * [Scripts](/home/policy/scripts): write one as a program that runs sandboxed on monty or Python on wasm, with the same context as JSON. * [Explain](/home/policy/explain): what the agent sees of policy, and how it asks what a line would do before running it. * [Route Runtime](/home/policy/route-runtime): choose the runtime for a line, from a script. * [Route Network](/home/policy/route-network): send a connection to one address to another, per workspace and per session. # Policies Source: https://docs.mirage.strukto.ai/home/policy/policies Mirage provides a powerful, scriptable policy layer that controls every command, CLI and POSIX call in the virtual terminal, and can even choose the underlying runtime. A policy is a Python or TypeScript class that controls what the agent does. Before an action runs, and again once it returns, the policy gets the full context: the line, each command with its expanded arguments, the paths it touches, the session, and what came back. It then lets the action through (`None`), refuses it, asks a host, caps its output, or chooses the underlying runtime. ```python Python theme={null} from mirage import RAMVFS, Workspace from mirage.policy import CommandContext, Deny, Policy class NoForcePush(Policy): async def pre_command(self, ctx: CommandContext) -> Deny | None: texts = [w.text for w in ctx.words] if texts[:2] == ["git", "push"] and "--force" in texts: return Deny("force pushes go through an operator") return None no_force_push = NoForcePush() ws = Workspace({"/": RAMVFS()}, policies=[no_force_push]) r = await ws.shell("git push --force origin main") # b'git: Permission denied\n' 126 print(r.stderr, r.exit_code) # ws.policies.add(no_force_push) puts it back ws.policies.remove(no_force_push) ``` ```typescript TypeScript theme={null} import { RAMVFS, Workspace, type Policy } from '@struktoai/mirage-node' const noForcePush: Policy = { preCommand(ctx) { const texts = (ctx.words ?? []).map((w) => w.text) const force = texts[0] === 'git' && texts[1] === 'push' && texts.includes('--force') return force ? { kind: 'deny', reason: 'force pushes go through an operator' } : null }, } const ws = new Workspace({ '/': new RAMVFS() }, { policies: [noForcePush] }) const r = await ws.shell('git push --force origin main') // git: Permission denied 126 console.log(r.stderrText, r.exitCode) // ws.policies.add(noForcePush) puts it back ws.policies.remove(noForcePush) ``` ## Lifecycle A policy implements any of eight methods, in pairs. The `pre_` method runs before an action, while the `post_` method runs after it with the same context and the execution result. A `post_` hook cannot undo executed actions. It can inspect results and return `Deny` or `Ask`; only `post_execute` can also return `Limit` to cap output. These responses do not replace returned output or suppress existing error text. ```mermaid theme={null} flowchart LR subgraph line["A line"] direction LR PE["pre_execute"] --> PC["pre_command"] --> Run["command runs"] --> PoC["post_command"] --> PoE["post_execute"] PoC -- "next command" --> PC end subgraph call["A VFS call"] direction LR PV["pre_vfs"] --> Op["call runs or cache serves"] --> PoV["post_vfs"] end Run -. file operations .-> PV subgraph connection["A connection"] direction LR PN["pre_network"] --> Send["bytes flow"] --> PoN["post_network"] end Run -. any client in the line .-> PN ``` | Python | TypeScript | Runs | Can return | | - | - | - | - | | `pre_execute` | `preExecute` | once per line, before any of it runs | Deny, Ask, Route | | `pre_command` | `preCommand` | before each command or CLI, once the line is parsed and expanded | Deny, Ask, Route | | `post_command` | `postCommand` | after each command, once its output drained | Deny, Ask | | `post_execute` | `postExecute` | once per line, after it ends | Deny, Ask, Limit | | `pre_vfs` | `preVfs` | before each VFS call, including command and runtime file operations | Deny, Ask | | `post_vfs` | `postVfs` | after each VFS call | Deny, Ask | | `pre_network` | `preNetwork` | before a connection the workspace opens carries any byte | Deny, Ask, Limit | | `post_network` | `postNetwork` | once that connection is over, however it ended | nothing; it observes | | `pre_workspace` | `preWorkspace` | on a server, before a create, clone or load builds anything | Deny | | What | Example | Covered by | | - | - | - | | A line | `cat /data/a.txt && rm /data/b` | `pre_execute`, `post_execute` | | A command or CLI | `rm /data/b` | `pre_command`, `post_command` | | A VFS call | `session.vfs.read("/data/a.txt")` | `pre_vfs`, `post_vfs` | | A connection | `curl https://api.example.com/x`, a CLI's API call, a mount's read | `pre_network`, `post_network` | | Entry point | Sends | | - | - | | `ws.shell`, `session.shell` | a line, with its commands and file operations | | the `shell`, `ls` and `grep` tools | a line, with its commands and file operations | | `mirage shell`, HTTP `/shell`, RPC `shell`, SSH | a line, with its commands and file operations | | `session.vfs` | a VFS call | | the `read`, `write`, `edit` and `glob` tools | a VFS call | | `mirage workspace vfs`, HTTP `/vfs/`, RPC `vfs/` | a VFS call | | FUSE, FSKit, SFTP | a VFS call | File policies also apply when a command or file-based CLI uses `ctx.vfs`. An account CLI calls its service directly, so command policy authorizes that API operation; it has no VFS path to check. Its writes invalidate caches for the mounts reached by that account. A policy's own file reads remain exempt from coded file hooks to avoid recursion. ## Context Each method gets one argument, `ctx`. Every `ctx` carries the session, plus what its method is about, and a `post_` method adds what came back. TypeScript spells the fields in camelCase (`ctx.sessionId`, `ctx.exitCode`). | Methods | What it is about | `post_` adds | | - | - | - | | `pre_execute`, `post_execute` | `line` and `commands`: every command of the line | `exit_code`, `output`, `results` | | `pre_command`, `post_command` | `line` and the command: `command`, `words`, `paths`, `walks` | `exit_code`, `stderr`, `records` | | `pre_vfs`, `post_vfs` | `call`, `path`, `write` | `result` | | `pre_network`, `post_network` | `host`, `address`, `port`, and who opened it: `command`, `program`, `words`, `line`, `mount` | `bytes_sent`, `bytes_received`, `seconds`, `ended` | | `pre_workspace` | `config`: the config as the caller wrote it, secrets still pointers | | `pre_command` is `pre_execute` narrowed to one command: each entry of `ctx.commands` is the context `pre_command` gets for that command, read before the line runs, so a word only the run can expand (`$X`) is not resolved there yet. Every `ctx` also carries: | Field | What it is | | - | - | | `session_id` | the session the action runs as | | `session` | the session, read only: `get(name)`, `snapshot()`, `cwd()`, `is_readonly(name)`, `profile()` | | `vfs` | the session's files, read only: `read`, `stat`, `readdir`, `exists`, and where the mounts are (`mount_of`, `is_mount`, `submounts`), hides applied | | `caller` | who makes the call (a `PolicyCaller`), a frozen copy: `caller.session` is the session above, with its `session_id` and `cwd` when the method was asked, and `caller.account` the account a server holds the workspace for (the one its requests sign in as), null outside a server or without accounts | `words` is the command line word by word, after expansion. Each word has a `text`, a `kind` (`name`, `subcommand`, `option`, `value`, `operand` or `redirect`), the `option` a value belongs to, and the `path` it names. For `tar -cf a.tar -C /mnt /data`: | `text` | `kind` | `option` | `path` | | - | - | - | - | | `tar` | `name` | | | | `-cf` | `option` | | | | `a.tar` | `value` | `-cf` | `/a.tar` | | `-C` | `option` | | | | `/mnt` | `value` | `-C` | `/mnt` | | `/data` | `operand` | | `/data` | * `paths` is every path the command reaches, flat: its words' paths, the targets of links it names, and the working directory a bare `ls` reads. * `line` is the line the command was parsed from: the line the agent typed, or for `eval`, `$( )` and a function body, that text. * `results` is the line's execution tree: a node per command with its exit code, stderr and records. * `records` are the calls a command made, one dict each: `op`, `path`, `source`, `bytes` and timing. * `call` is the function called: its `name`, `effect` (read, write, metadata), `target`, and whether it `creates` or reaches the `subtree`. Every function a VFS marks reaches `pre_vfs` and `post_vfs`: `read_tree`, `search` and `copy` too. A method only reads. A write it makes through Mirage is refused (`EROFS` for a file, `EACCES` for a variable), and its reads are not judged again. The session's history is `/.bash_history`, which a method reads through `ctx.vfs` like any file. ### What the agent controls Most of a `ctx` comes from what the agent did, so a policy reads it as a claim to check, not as a credential: | The agent sets | Through | | - | - | | `line`, `command`, `words`, `argv`, `paths`, `walks` | the line it types, after expansion | | `cwd`, `session.cwd()`, `caller.session.cwd` | `cd` | | `env`, `session.get()`, `session.snapshot()` | `export`, assignments and `readonly` | | `call`, `path`, `write` at `pre_vfs` | the file call it made | | `exit_code`, `stderr`, `output`, `records`, `result` | what its own command or call produced | The host sets `session_id` (`caller.session.session_id` too), `profile`, `mounts`, `prefix` and `mode`, and what `vfs` shows: the agent cannot change them from inside the session. Decide who may do what from those, and from a variable only when the workspace's or the profile's `env` sets it with `readonly: true`. `session.is_readonly()` is also true for a name the agent marked with `readonly NAME` itself. A policy written as a program, on monty or Python on wasm, gets the same `ctx` as JSON: see [Scripts](/home/policy/scripts). ## Examples ### pre\_execute ```python Python theme={null} from mirage.policy import Policy, Route, RouteContext class JobsOnTheBox(Policy): async def pre_execute(self, ctx: RouteContext) -> Route | None: paths = [p.virtual for c in ctx.commands for p in c.paths] if any(p.startswith("/jobs/") for p in paths): return Route(machine="box") return None ``` ```typescript TypeScript theme={null} const jobsOnTheBox: Policy = { preExecute(ctx) { const jobs = ctx.commands.some((c) => c.paths.some((p) => p.virtual.startsWith('/jobs/'))) return jobs ? { kind: 'route', machine: 'box' } : null }, } ``` `python3 /jobs/train.py` runs on the workspace's `box` [machine](/home/setup/machine/overview). See [Route Runtime](/home/policy/route-runtime) for runtimes and machines. ### post\_execute ```python Python theme={null} from mirage import Limit from mirage.policy import ExecuteResultContext, Policy class FirstHundredLines(Policy): async def post_execute(self, ctx: ExecuteResultContext) -> Limit: return Limit(max_lines=100) ``` ```typescript TypeScript theme={null} const firstHundredLines: Policy = { postExecute() { return new Limit({ maxLines: 100 }) }, } ``` A longer output stops at 100 lines, and stderr says `output truncated at limit (100 lines); ...`. A Deny here drops the output: exit 126 and a decision record. ### pre\_command `NoForcePush`, at the top of this page. ### post\_command ```python Python theme={null} from mirage.policy import CommandResultContext, Deny, Policy class NoSecretsShown(Policy): async def post_command(self, ctx: CommandResultContext) -> Deny | None: if any(r.get("path", "").startswith("/vault/") for r in ctx.records): return Deny("vault reads need an operator") return None ``` ```typescript TypeScript theme={null} const noSecretsShown: Policy = { postCommand(ctx) { const vault = ctx.records.some((r) => typeof r.path === 'string' && r.path.startsWith('/vault/')) return vault ? { kind: 'deny', reason: 'vault reads need an operator' } : null }, } ``` `cat /vault/k && echo next` exits 126 with `cat: Permission denied`, and `echo` does not run. Output already sent stays sent. A runtime that takes a line whole runs its commands itself, so no result comes back to judge: while a `post_command` method is installed, such a line is refused. ### pre\_vfs ```python Python theme={null} from mirage.policy import Deny, Policy, VfsContext class ReadOnlyReports(Policy): async def pre_vfs(self, ctx: VfsContext) -> Deny | None: if ctx.write and ctx.path.virtual.startswith("/reports/"): return Deny("reports are read-only") return None ``` ```typescript TypeScript theme={null} const readOnlyReports: Policy = { preVfs(ctx) { return ctx.write && ctx.path.virtual.startsWith('/reports/') ? { kind: 'deny', reason: 'reports are read-only' } : null }, } ``` `session.vfs.write("/reports/q3.md", ...)` raises `EACCES`. The same policy refuses a command redirect (`echo x > /reports/q3.md`) and writes through runtime file APIs, FUSE, FSKit and SFTP. ### post\_vfs ```python Python theme={null} from mirage.policy import Deny, Policy, VfsResultContext class NoKeysOut(Policy): async def post_vfs(self, ctx: VfsResultContext) -> Deny | None: if isinstance(ctx.result, bytes) and b"PRIVATE KEY" in ctx.result: return Deny("holds a private key") return None ``` ```typescript TypeScript theme={null} const noKeysOut: Policy = { postVfs(ctx) { const text = ctx.result instanceof Uint8Array ? new TextDecoder().decode(ctx.result) : '' return text.includes('PRIVATE KEY') ? { kind: 'deny', reason: 'holds a private key' } : null }, } ``` Reading a file that holds a private key with `session.vfs.read` raises `EACCES`; commands and runtime file reads meet the same check. Cached reads and retained handles are checked against current policy before returning their bytes or metadata. These checks do not fetch the retained value again. Bytes already delivered to a program remain in its memory. `post_vfs` can refuse a read but not shorten it: the file comes back whole or not at all. To cap how much a command prints, use `post_execute`. ### Variables A variable write reaches no method: a variable does nothing until a command, a file call or a connection uses it, and each of those methods reads the session (`ctx.session`, and a command's `env`), so a rule about a value goes in the method that uses it. ### pre\_network and post\_network `pre_network` runs once for each connection the workspace opens, before it carries any byte, whoever opens it: `curl`, `wget` or `git`, a builtin or installed CLI, a mount's VFS, a runtime or an SDK in the process. The workspace's [`network`](/home/configuration#network) lists judge it first, and a connection they refuse reaches no policy. The context says where it goes (`host`, empty for a bare address; `address`; `port`) and who opened it: `command`, `program` and `words` as `pre_command` reads them, `line`, and `mount`, the prefix of the mount whose VFS opened it. URL, method and status are not in it: under https only the program and the server see them. A `pre_network` answer refuses the connection (Deny, or Ask, since a running command cannot wait on a question) or caps it: a `Limit` cuts it once it carries `max_bytes`, sent and received together, or stays open `timeout_seconds`. The tightest Limit among the policies wins. A refused or cut connection is reset, so the program reads a broken connection, never a clean end: `curl` exits 7 for a refusal. `post_network` runs once the connection is over, once for each policy whose `pre_network` let it through, however it ended: `ended` is `closed`, `refused` (by a later policy), `limit` or `error`, with `bytes_sent`, `bytes_received` and `seconds`. It observes only. A client that keeps a connection open and sends on it again is judged once, as it opens. When the address a program asked for does not answer, each other address its lookup gave is a connection of its own, judged before it is tried. A socket the program bound itself before connecting cannot pass the gateway, so while a policy listens it is refused. Together the two hold a workspace to a byte budget: ```python Python theme={null} from mirage.policy import ( Deny, Limit, NetworkContext, NetworkResultContext, Policy, ) class Budget(Policy): def __init__(self, total: int) -> None: self.left = total async def pre_network(self, ctx: NetworkContext) -> Deny | Limit: if self.left <= 0: return Deny("the egress budget is spent") return Limit(max_bytes=self.left, timeout_seconds=300) async def post_network(self, ctx: NetworkResultContext) -> None: self.left -= ctx.bytes_sent + ctx.bytes_received ``` ```typescript TypeScript theme={null} let left = 500_000_000 const budget: Policy = { preNetwork() { if (left <= 0) return { kind: 'deny', reason: 'the egress budget is spent' } return new Limit({ maxBytes: left, timeoutSeconds: 300 }) }, postNetwork(ctx) { left -= ctx.bytesSent + ctx.bytesReceived return null }, } ``` A runtime that starts a process on this machine (`local`, Sandlock) would connect around the gateway, so while a policy judges connections it refuses to run. A program on a [machine](/home/setup/machine/overview) connects from that machine, and no policy sees its connections. In a browser a page sees no socket: `fetch` is judged by host name with an empty `address`, and the counts are the bodies' bytes. While a policy listens for connections, a request whose upload passes the Limit, or whose size a page cannot know (a form, a stream), is refused before it is sent; a redirect the page would follow is refused, since it goes where no policy saw; and a `WebSocket` is refused, since its handshake cannot wait for an answer. ### pre\_workspace Only a server asks `pre_workspace`, with the policies it was started with (see [Server policies](/home/access/http#server-policies)). It sees the config before any mount is built or any secret is read: a create's whole config, a clone's or a load's `override`. `ctx` carries `config` and `caller` only. ```python Python theme={null} from mirage.policy import Deny, Policy, WorkspaceContext class NoHostFiles(Policy): async def pre_workspace(self, ctx: WorkspaceContext) -> Deny | None: mounts = ctx.config.get("mounts") or {} if any(block.get("vfs") == "disk" for block in mounts.values()): return Deny("disk mounts are not offered here") if "runtimes" in ctx.config: return Deny("runtimes are set by the operator") return None ``` ```typescript TypeScript theme={null} const noHostFiles: Policy = { preWorkspace(ctx) { const mounts = (ctx.config.mounts ?? {}) as Record if (Object.values(mounts).some((block) => block.vfs === 'disk')) { return { kind: 'deny', reason: 'disk mounts are not offered here' } } if ('runtimes' in ctx.config) { return { kind: 'deny', reason: 'runtimes are set by the operator' } } return null }, } ``` The create answers 403 with the reason, and nothing is built. ## Answers | Return | Effect | | - | - | | `None` | no opinion | | `Deny(reason)` | refuses the action | | `Deny(reason, path=p)` | fails the command with `p`'s own error; the rest of the line still runs | | `Ask(reason)` | asks the host; see [Asks](#asks) | | `Route(runtime)` | chooses the underlying runtime | | `Limit(max_lines=, max_bytes=)` | cuts the output at the bound, with a notice on stderr; with `on_exceed` set to error, no output and exit 1 | TypeScript returns `{ kind: 'deny', reason }`, with `path` for a path, `{ kind: 'ask', reason }`, `{ kind: 'route', runtime }` and `new Limit({ maxLines })`. A method that raises refuses too. What the agent reads for each is on [Explain](/home/policy/explain#what-the-agent-reads). ## Asks An Ask records a question in the workspace's ledger: * With `on_ask` (`onAsk`), an inline allow answer continues the current request; a deny answer refuses it. * Without an inline answer, including when the callback returns no decision, the request returns pending. The host records a decision in the ledger, allowing the caller to retry. Ledger answers apply as follows: * `allow`, scope `once` (default): the retry runs and spends it. * `allow`, scope `session`: everything the ask covers, for the rest of that session. * `deny`: the retry is refused; running it again asks again. A host answers through [`ws.decisions`](/python/access/in-app#ws-decisions), [`mirage workspace allow`](/home/access/cli#asks) or [`POST /asks/{ask_id}`](/api/operations/asks/respond-to-ask). An Ask from a `post_` method comes after the action ran, so nothing is undone: what came back is held, and the approved retry runs it again. ## When answers disagree * Any Deny beats any Ask, so answering an ask never reopens a refusal. * The first Deny speaks. The built-ins come first, then the session's profile, then its script, then `policies=`, then `add()`. * Every Ask is put to the host, and the action runs once all are approved. * Limits merge to the tightest value of each field. * Two Routes to different runtimes refuse the line. * A policy may give several answers at once, a tuple in Python or an array in TypeScript; each counts as if a policy of its own gave it. ## Examples on GitHub [policy.py](https://github.com/strukto-ai/mirage/blob/main/examples/python/policy/policy.py) and [policy.ts](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/policy/policy.ts) run a profile's scripts. # Route Network Source: https://docs.mirage.strukto.ai/home/policy/route-network Send a workspace's connections to one address to another, per workspace and per session. `network.routes` sends a connection to one `host:port` to another, as a container's port mapping does. The agent keeps the address its task names, and each workspace reaches its own copy of the service: ```yaml theme={null} network: allowed_domains: ["127.0.0.1:61001"] routes: localhost:5003: 127.0.0.1:61001 ``` ```bash theme={null} curl localhost:5003/messages # reaches 127.0.0.1:61001 curl localhost:5004/messages # refused: no route, not allowed ``` A second workspace on the same server can route `localhost:5003` to `127.0.0.1:61002` and allow only that, so neither reaches the other's. ## How a route applies * Every connection in the workspace follows it: `curl`, CLIs, mounts, and Python or JavaScript code. HTTPS, WebSocket and database connections too. Over HTTPS, the service's certificate must still match the address the agent typed. * [`allowed_domains`, `denied_domains`](/home/configuration#network) and [`pre_network`](/home/policy/policies#pre_network-and-post_network) policies check where the route goes, not the address the agent typed. * `local` and Sandlock runtimes don't run in a workspace with routes, and programs on a [machine](/home/setup/machine/overview) aren't routed. * In a browser, a route for an `https` or `wss` address can change only the port. ## Per session A [profile](/home/profiles) can set `routes` for its sessions. They replace the workspace's routes for the same address, and the workspace's allowed and denied lists still apply: ```yaml theme={null} network: allowed_domains: ["127.0.0.1"] routes: localhost:5003: 127.0.0.1:61001 profiles: staging: network: routes: localhost:5003: 127.0.0.1:61002 ``` # Route Runtime Source: https://docs.mirage.strukto.ai/home/policy/route-runtime Route commands across runtimes, free from the limits of a local terminal or a single kernel. Mirage’s virtual terminal is not tied to a local terminal or a single kernel. Your agent uses one shell while Mirage routes commands to in-process, containerized or remote runtimes. Use `route_policy` to choose a runtime for each command line with a script or a function. Here, `monty` runs `python3` in-process, while `machine` runs it on the `box` machine, a container with your packages. Start the [Docker container](/home/setup/machine/docker) `my-box` with `/jobs/train.py` and its dependencies before using this excerpt: ```yaml theme={null} mode: exec machines: box: provider: docker container: my-box runtimes: - monty - name: remote captures: ["@python"] machine: box - workspace route_policy: {script: ./route.py, runtime: monty} ``` ```python route.py theme={null} def pre_execute(ctx): paths = [p for c in ctx["commands"] for p in c["paths"]] if any(p.startswith("/jobs/") for p in paths): return {"kind": "route", "runtime": "remote"} ``` `python3 /jobs/train.py` runs in the container; `cat data.csv | python3 -c ...` stays on monty. ## Input and answers A runtime routing script is a [policy program](/home/policy/scripts) shared by every session. Its `pre_execute` function takes the same `ctx` a program gets at `pre_execute`: the line, each of its commands with its words and resolved paths, and the session. It returns its answer: | Returns | Effect | | - | - | | `{"kind": "route", "runtime": "remote"}` | that runtime serves every command it captures | | `{"kind": "route", "machine": "box"}` | the `remote` runtime runs the line's programs on that machine | | `{"kind": "route", "runtime": "remote", "reason": "..."}` | the same, with why for `ws.explain(line)` to show | | `{"kind": "route", "runtime": "workspace"}` | entries that capture `@line` are excluded entirely; other entries still serve their captures, and a command only an excluded entry captures is refused | | `None` | the first capturer in `runtimes` order serves each command | | `{"kind": "deny", "reason": "..."}` | the line is refused, as by any `pre_execute` program | A program that exits non-zero, runs past 10 seconds, or answers anything else fails the line with a routing error. It runs on its own runtime, monty unless the block names one, as [a profile's programs do](/home/policy/scripts#runtimes). In code, `route_policy=` takes the same block with a `ScriptSource`, or a plain function, sync or async, returning a runtime name or `None`: ```python theme={null} from mirage.policy import RouteContext def policy(ctx: RouteContext) -> str | None: paths = [p.virtual for c in ctx.commands for p in c.paths] return "remote" if any(p.startswith("/jobs/") for p in paths) else None ws = Workspace(mounts, runtimes=runtimes, route_policy=policy) ``` ## Admit, then route Runtime selection happens at [`pre_execute`](/home/policy/policies#lifecycle), before commands run. Mirage checks `route_policy` first, then any policies defined in code. These policies can also choose a runtime or refuse a command line: ```python theme={null} from mirage.policy import Deny, Policy, Route, RouteContext class JobsOnTheBox(Policy): async def pre_execute(self, ctx: RouteContext) -> Route | Deny | None: if "/prod/" in ctx.line: return Deny("the prod tree is read only") return Route(machine="box") if "/jobs/" in ctx.line else None ``` A `pre_command` policy may answer a Route too, which places that one command alone: `Route(machine="gpu")` for `python3 train.py` in `ls; python3 train.py` runs only `python3` there. Behind `nohup`, `nice`, `setsid`, `stdbuf` or `ionice`, the policy is asked about the program, and the wrapper runs where the program is placed. A line the rules refuse is never placed. A Deny beats any Route, and two policies naming different runtimes or machines refuse the line. Nested lines (`$( )`, `eval`, `source`, `xargs`) keep the outer line's placement. `ws.explain(line)` shows each placement answer and each command's runtime and machine. The caller's `runtime=` and `machine=` arguments place the line itself. ## Ask a model A routing program can ask an LLM where a line runs. A program on monty has no network, so the model call is a [host function](/home/policy/scripts#host-functions) that returns the runtime and a reason, which `explain` shows. The answer counts against the program's 10 seconds. The example sends each `python3` line to monty or to the host's Python, on an OpenAI model or on Jev: [Python](https://github.com/strukto-ai/mirage/tree/main/examples/python/policy/llm_routing) and [TypeScript](https://github.com/strukto-ai/mirage/tree/main/examples/typescript/policy/llm_routing). # Scripts Source: https://docs.mirage.strukto.ai/home/policy/scripts Write a policy as a program that runs sandboxed on monty or Python on wasm, takes the same context a coded policy reads, and returns its answer. A policy can be a program instead of a class. A profile names a list of programs for each method it answers at, and the runtime each one runs on. A program defines a function named for the method, which takes the same `ctx` a [coded policy](/home/policy/policies) reads and returns its answer. Two places take a program: | Where | Asked | Answers | | - | - | - | | a profile's `policy:` | at `pre_execute`, `pre_command`, `pre_vfs` and `pre_network` before the action, and at their `post_` four after it, for the sessions under that profile | deny or ask; a route at `pre_execute`; nothing at `post_network`, which observes | | [`route_policy:`](/home/policy/route-runtime) | at `pre_execute`, for every session | a route, or a deny or ask | | a server's [policy file](/home/access/http#server-policies) | at the same methods for every session of every workspace it builds, and at `pre_workspace` before it builds one | as a profile's; a deny only at `pre_workspace` | A server's programs read no workspace files: at `pre_workspace` the workspace does not exist yet, and its `ctx` is the `config` and the `caller`. ## A profile's policy Save these files together. Install Monty as described in [Runtimes](#runtimes). The selected profile runs `guard.py` before each command and refuses `rm`. ```yaml workspace.yaml theme={null} mounts: /data: vfs: ram profiles: reviewer: policy: pre_command: - {script: ./guard.py, runtime: monty} profile: reviewer ``` ```python guard.py theme={null} def pre_command(ctx): if ctx["command"] == "rm": return {"kind": "deny", "reason": "deletes are disabled"} ``` ```bash theme={null} mirage workspace create workspace.yaml --id policy-demo mirage shell -w policy-demo -c 'echo hello > /data/note.txt; rm /data/note.txt' # rm: Permission denied mirage workspace delete policy-demo ``` Each entry names its program and its runtime: a name, or `{name, config}` when the runtime needs settings, as in a `runtimes` entry. An entry with no `runtime` runs on monty. A method's programs are asked in order, up to the first deny, and each answer counts as if a policy of its own gave it ([when answers disagree](/home/policy/policies#when-answers-disagree)): an ask from one program and a route from another both hold. A method with no program is never asked and costs nothing. In code, a profile takes the same block, with a `ScriptSource` for each program: ```python Python theme={null} profiles={ "reviewer": { "policy": { "pre_command": [{"script": ScriptSource(Path("guard.py").read_text()), "runtime": "monty"}], }, }, } ``` ```ts TypeScript theme={null} profiles: { reviewer: { policy: { preCommand: [{ script: new ScriptSource(readFileSync('guard.py', 'utf8'), 'python'), runtime: 'monty' }], }, }, } ``` ## The program A program defines a function named for its method at the top level, `def pre_command(ctx)` at `pre_command`, and Mirage calls it after the program runs. A program without one refuses every action it is asked about, with the reason `defines no pre_command(ctx)`. * **Input:** `ctx`, the function's argument, as plain data. Mirage carries it to the program in the environment variable `MIRAGE_POLICY_CTX`, which is reserved; the session never sees it. Beside it, Mirage passes only the entry's own [`env`](#variables): the session's variables stay out of its environment. A runtime may add its own, as wasi adds `PYTHONHOME` and `PYTHONDONTWRITEBYTECODE`. * **Session:** the program starts in the session's working directory, so `os.getcwd()` is the session's. The session's variables are in `ctx["env"]`, not in `os.environ`. An `import` never loads a module from the session's directory. * **Answer:** what the function returns. `None` is no opinion. On monty the function may be `async def`, to await [host functions](#host-functions). | Returns | Effect | | - | - | | `None` | no opinion | | `{"kind": "deny", "reason": "..."}` | refuses | | `{"kind": "ask", "reason": "..."}` | [asks the host](/home/policy/policies#asks) | | `{"kind": "route", "runtime": "docker"}` | at `pre_execute`: runs the line on that runtime | A deny or an ask without a `reason` gets the default one. A route may give one too, which `explain` shows. Mirage prints the return value on stdout as JSON and reads it back there, so anything else the program prints on stdout, such as a debug line, fails it; write those to stderr. ## Variables An entry's `env` gives its program variables beside `MIRAGE_POLICY_CTX`, on every runtime. A value is a string, or a pointer to a [credential source](/home/authentication) such as `aws-sm` or `1password`, read the first time the program runs and kept for the workspace's life: ```yaml workspace.yaml theme={null} profiles: reviewer: policy: pre_command: - script: ./guard.py runtime: monty env: DIRECTORY_URL: https://directory.example.com DIRECTORY_TOKEN: {from: aws-sm, ref: prod/directory, key: token} ``` A session record and a snapshot keep the pointer, never the value it read. A source that cannot answer refuses the action, as a failed program does. `MIRAGE_POLICY_CTX` cannot be set here. ## Host functions A program on monty can call functions the host hands the workspace, by name. They are passed in code, never in a document or over the server API, so a profile can call them but not add one. Programs on `wasi` and `pyodide`, and the agent's own programs, do not see them. ```python Python theme={null} async def lookup_user(session_id: str) -> dict: return {"admin": session_id in ADMINS} ws = Workspace(mounts, profiles=profiles, policy_functions={"lookup_user": lookup_user}) ``` ```ts TypeScript theme={null} const ws = new Workspace(mounts, { profiles, policyFunctions: { lookup_user: async (sessionId: string) => ({ admin: ADMINS.has(sessionId) }), }, }) ``` ```python guard.py theme={null} async def pre_command(ctx): user = await lookup_user(ctx["session_id"]) if ctx["command"] == "rm" and not user["admin"]: return {"kind": "deny", "reason": "only admins delete"} ``` A function may be sync or async and takes and returns plain data: strings, numbers, booleans, `None`, lists and dicts. One that raises raises in the program, which may catch it; uncaught, the program fails and the action is refused. A function may take as long as it needs, within the program's 10 seconds, and programs calling functions run side by side rather than one at a time. ## ctx Every field a coded policy reads, under the Python names, as plain data. For `cat notes.txt | wc -l` in `/data`, `pre_execute` gets: ```json theme={null} { "line": "cat notes.txt | wc -l", "commands": [ { "command": "cat", "line": "cat notes.txt | wc -l", "words": [ {"text": "cat", "kind": "name", "option": null, "path": null}, {"text": "notes.txt", "kind": "operand", "option": null, "path": "/data/notes.txt"} ], "paths": ["/data/notes.txt"], "walks": false, "argv": ["notes.txt"], "env": {"PWD": "/data", "TEAM": "core", "OLDPWD": "/"}, ... }, {"command": "wc", "words": [...], "paths": [], ...} ], "session_id": "agent", "cwd": "/data", "env": {"PWD": "/data", "TEAM": "core", "OLDPWD": "/"}, "profile": "reviewer", "mounts": ["/.bash_history", "/data", "/dev", "/usr/bin"], "caller": {"session": {"session_id": "agent", "cwd": "/data"}} } ``` Each entry of `commands` has the `env` that command runs with, its own `NAME=value` prefix included: for `GPU=1 python3 train.py`, only the `python3` entry has `GPU`. `pre_command` gets one entry of `commands`, with the session fields beside it: | Method | `ctx` holds | | - | - | | `pre_execute` | `line`, `commands` | | `pre_command` | `line`, `command`, `words`, `paths`, `walks` | | `pre_vfs` | `call` (`name`, `effect`, `target`, `creates`, `subtree`), `path`, `write` | | `pre_network` | `host`, `address`, `port`, `command`, `program`, `words`, `line`, `mount` | A `post_` method gets its `pre_` method's `ctx` plus what came back: | Method | adds | | - | - | | `post_execute` | `exit_code`, `output`, `results` | | `post_command` | `exit_code`, `stderr`, `records` | | `post_vfs` | `result` | | `post_network` | `bytes_sent`, `bytes_received`, `seconds`, `ended` | Every `ctx` also has `session_id`, `cwd`, `env`, `profile`, `mounts`, the mount roots the session can see, and `caller`, whose `session` holds the `session_id` and `cwd` a coded policy reads off `ctx.caller`. The agent sets most of these fields; [what the agent controls](/home/policy/policies#what-the-agent-controls) says which ones a program can trust. ## Files and the session A program reads the workspace as the session it judges for: * `open()`, `os.listdir()` and `os.stat()` go through the workspace. A hidden path does not exist, path rules apply, and a write is refused (`EROFS`). * Its own reads are not judged again by its profile's `pre_vfs` or `post_vfs`. So a program can judge a file by what is in it. This one disables `rm`, and a Python script whose code deletes files: ```python guard.py theme={null} def deletes(path): try: code = open(path).read() except OSError: return False return any(call in code for call in ("os.remove", "os.unlink", "shutil.rmtree")) def pre_command(ctx): if ctx["command"] == "rm" or ( ctx["command"].startswith("python") and any(deletes(p) for p in ctx["paths"]) ): return {"kind": "deny", "reason": "deleting files is disabled"} ``` The script reads the code as text, so it stops the usual calls, not every way Python can delete a file. A rule that must always hold belongs in a [coded policy](/home/policy/policies), which judges each file call itself. > [tab] Python > > ```python theme={null} > from pathlib import Path > > from mirage import MountMode, Workspace > from mirage.runtime.types import ScriptSource > from mirage.vfs.s3 import S3Config, S3VFS > > ws = Workspace( > {"/s3": (S3VFS(S3Config(bucket="my-bucket")), MountMode.WRITE)}, > profiles={ > "analyst": { > "policy": { > "pre_command": [{"script": ScriptSource(Path("guard.py").read_text()), "runtime": "monty"}], > }, > }, > }, > profile="analyst", > ) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { readFileSync } from 'node:fs' > import { MountMode, S3VFS, ScriptSource, Workspace } from '@struktoai/mirage-node' > > const ws = new Workspace( > { '/s3': [new S3VFS({ bucket: 'my-bucket' }), MountMode.WRITE] }, > { > profiles: { > analyst: { > policy: { > preCommand: [{ script: new ScriptSource(readFileSync('guard.py', 'utf8'), 'python'), runtime: 'monty' }], > }, > }, > }, > profile: 'analyst', > }, > ) > ``` ```console theme={null} $ cat /s3/clean.py import os os.remove("/s3/report.txt") $ rm /s3/report.txt rm: Permission denied $ python3 /s3/clean.py python3: Permission denied ``` ## When a program fails A program that defines no function for its method, exits non-zero, runs past 10 seconds, returns anything but an answer its method can give, or names a runtime that cannot run here refuses the action. The reason names the profile and what went wrong, such as `profile 'reviewer' policy exited 1`, and the program's stderr goes to the log. Silence on failure would let through exactly what the policy is there to judge. `route_policy:` is a deployment setting, so the same mistakes fail the line with a routing error instead. ## Runtimes | Runtime | What it is | Hosts | | - | - | - | | `monty` | a small Python interpreter, a sandboxed subset of the language | Python, TypeScript | | `wasi` | full CPython on wasm, run by wasmtime | Python | | `pyodide` | full CPython on wasm | TypeScript | Each runtime is the policy's own, built from the name and settings the profile gives and never shared with the agent. Monty is the default, and it must be installed: `mirage-ai[monty]` in Python, `@pydantic/monty` in TypeScript. Without it, a program on monty refuses every action it judges and the refusal names the package to install. `wasi` needs a CPython WASI build: its folder as `config: {home: ...}`, or in `MIRAGE_WASI_HOME`. A program gets 10M of memory on monty and 128M on `wasi` and `pyodide`, unless its runtime's config names `max_memory` (`null` for no cap). A program that needs more fails like any other. Monty runs a program in about a millisecond. `wasi` starts CPython on every run, 100 to 300 ms, so it suits the methods asked less often; `pre_vfs`, asked for every file call from outside a line, is usually monty's. # Agent profiles Source: https://docs.mirage.strukto.ai/home/profiles Choose what each agent can run and which files it can see. A profile gives an agent session its permissions. Agents can share a workspace while seeing different files and using different commands. ## What a profile controls | Setting | Purpose | | - | - | | `commands.allow` | Limit the session to the listed tools. | | `commands.ask` | Require approval for matching commands. | | `commands.deny` | Refuse matching commands. | | `paths.hide` | Make matching files and folders invisible to the session. | | `paths.show` | Make a specific path visible within a hidden folder. | | `mounts` | Restrict a data source to `read`, `write` or `exec` access. | | `cwd` and `env` | Set the session's starting directory and environment; `env` takes the same literals and [credential pointers](/home/configuration#environment-and-credential-pointers) as the workspace's. | | `vars.hide` | Make matching variable names, or globs over names, read as unset. | | `processes` | Set whose processes `ps` lists and `kill` stops, and cap the live processes. | | `command_limits` | Override [output and execution limits](/home/core/output-limits) for the session. | | `network` | Narrow where the session's lines may connect, besides the workspace's [`network`](/home/configuration#network). | | `policy` | Run [policy scripts](/home/policy/scripts) at the `pre_` and `post_` methods. | Each of the last five keys takes this shape: ```yaml theme={null} profiles: worker: vars: hide: [AWS_*, GITHUB_TOKEN] processes: list: workspace kill: session max: 8 command_limits: grep: {max_lines: 200} network: allowed_domains: ["*.github.com"] policy: pre_command: - {script: ./guard.py, runtime: monty} ``` `processes.list` and `processes.kill` take `session`, the default, for the session's own processes, or `workspace`, for every session's. `kill` cannot reach past `list`, and a bare scope such as `processes: workspace` sets both. `max` counts every pipeline stage, subshell and background job the session has running; it is 128 unless a block sets it, and `null` lifts it. Starting a process past `max` fails with `Resource temporarily unavailable`. The workspace takes the same `processes` block beside `profiles`, for every session. A profile's block overrides it field by field: here a `batch` session holds 512 processes, and every other session 64, with the workspace's scopes. ```yaml theme={null} processes: {list: workspace, max: 64} profiles: batch: processes: {max: 512} ``` `network` takes the workspace's grammar, and a session's lines are held to both: the profile can narrow where they connect, never widen it. A mount still connects under the workspace's `network`, since it serves every session. A profile's `routes` replace the workspace's for the same address: see [Route Network](/home/policy/route-network#per-session). ## Example: a research agent This profile lets an agent browse and search `/data`, keeps it read-only, and hides `/data/private`. ```yaml workspace.yaml theme={null} mounts: /data: vfs: ram profiles: researcher: cwd: /data mounts: /data: mode: read paths: hide: [/data/private] commands: allow: [ls, cat, grep, find, stat, pwd] profile: researcher ``` Replace RAM with your [VFS](/home/setup/vfs). `profile: researcher` selects the default for new sessions; another session can use a different named profile. A profile cannot grant access beyond the workspace's permissions. The allow list covers shell builtins too. This profile omits `cd` and `echo`, so a session under it is refused both with `Permission denied`. The session's own shell functions are exempt, because each line in a function body passes the same check. ## Use a profile Name the profile when you create a session: | | Create a session under `researcher` | | - | - | | Python | `ws.create_session("s1", profile="researcher")` or `await ws.session("s1", profile="researcher")` | | TypeScript | `ws.createSession('s1', { profile: 'researcher' })` | | [CLI](/home/access/cli#workspaces) | `mirage workspace session create -w ID -p researcher` | A session that names no profile gets the one `profile:` selects. Without `profile:`, it gets the profile named `default` if the workspace defines one, and no restrictions otherwise. ## Change a profile while it runs A host can add a profile or replace what a name means on a running workspace, then move sessions onto it. A session keeps its rules until it is moved, and keeps its working directory, variables and history when it is. The workspace YAML is never rewritten. | | Set a profile | Move a session onto it | | - | - | - | | Python | `ws.set_profile(name, doc)` | `await ws.set_session_profile(id, name)` | | TypeScript | `ws.setProfile(name, doc)` | `await ws.setSessionProfile(id, name)` | | [HTTP](/api/operations/workspaces/set-profile) | `PUT /v1/workspaces/{id}/profiles/{name}` | `PATCH /v1/workspaces/{id}/sessions/{session_id}` | | [CLI](/home/access/cli#workspaces) | `mirage workspace set-profile ID NAME FILE` | `mirage workspace session update -w ID -s S -p NAME` | For HTTP, send a JSON body such as `{"profile":"researcher"}` to the session's `PATCH` route to select that profile. Session operations remain in the [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml), although they are hidden from API navigation. An agent cannot reach these: they are host operations, so no builtin, MCP tool or RPC method changes a profile. ## Rule matching Command patterns match token prefixes. `git push` matches `git push origin main`. Spelling and order matter: `rm -rf` does not match `rm -r -f` or `rm --recursive --force`. A `*` token matches any token; trailing `*` is redundant. Omitting `commands.allow` adds no tool allowlist restriction; `allow: []` admits no installed tools. This list does not govern shell functions, executed paths or direct VFS calls. The shell's own tests count as commands under their own names: an allow list admits `[ ]` only if it names `[`, `[[ ]]` only if it names `[[`, and a path rule judges the file operand of `-e`, `-f` or `-nt` in all three spellings as it does for `test`, however the operand is spelled. Ask and deny rules can name commands, paths, or map a command to its paths: ```yaml theme={null} commands: allow: [rm] ask: - {commands: {rm: ["/data/review/*"]}, reason: deletes need review} deny: - {commands: {rm: ["/data/*"]}, reason: data is retained} ``` Within one profile’s rules, the deeper literal anchor wins for each path. Deny wins at equal depth. Here, `rm /data/review/note.txt` asks for approval despite the broader deny; `rm /data/other.txt` is denied. A multi-path command must pass each path's checks. A rule written under a mount section speaks for that mount: for a line whose working directory or paths lie in it, for a walk or a move of a directory that holds it (`grep -r`, `ls -R`, `mv`), and for each entry inside it that a line reaches on its own (`cp -r`, `chmod -R`). `paths.hide` and ask/deny path entries may be absolute paths or slashless name patterns such as `*.pem`, including inside mount sections. `paths.show` entries must be absolute paths. A literal path covers its subtree; glob patterns use `*`, `?` and `[`, and `*` can cross `/`. A rule naming only `paths` also applies to direct VFS operations. `paths.hide` makes a path appear absent; `paths.show` reopens a more specific path. A hide stays where it is written, so moving a directory that holds a hidden path, or one the session reaches only through a `paths.show` below it, is refused with `Permission denied`: the hidden content would land in view. Ask and deny rules control operations while leaving paths visible. A hidden path is also left out of what commands and CLIs print from their own data, and out of their counts and totals: `git status`, `git ls-files`, `git diff --stat` and `git log --name-only` neither name nor count a file another session staged under it. A link that leads into a hidden path is hidden as well, for every command: `readlink -f`, `test -L`, `ln`, `touch -h`, `chown -R` and `find -newer` meet it as a name that is not there. A repository's history counts as the path too. Under a hide, no revision ever held it: `git show HEAD:secret.txt` answers as it would for a path never committed, `git log -S` finds nothing in it, and an object id stored only there names nothing. A checkout or a branch switch leaves a hidden file as it is: an edit to it neither blocks the switch nor is named in git's refusal. A switch that would remove it, by writing a file where its directory stands, is refused, naming only the visible path. Under a deny rule, git refuses to print the path's content from any revision (`git log -p`, `git show HEAD:secret.txt`) as it refuses the file, and still lists the name. Use [Explain](/home/policy/explain) to check a rule before running a line. For conditions beyond these patterns, attach a [policy script](/home/policy/scripts). # Security limits Source: https://docs.mirage.strukto.ai/home/security The limits that keep one agent's lines from using up what other agents and the host share. A line an agent writes can loop forever, start processes without end, or grow a variable until memory runs out. In Mirage it runs beside other agents' sessions, in one process or one isolate, so each of these would cost them too. Every limit below is on by default except `max_workspaces`, and each stops its case the way bash and Linux would, with the same exit status. Three layers set them: * **The host** (the server, or an edge app) sets ceilings. A workspace may set a lower value, never a higher one, and one that lifts a limit with `null` gets the ceiling instead. * **The workspace** sets each limit for every session it holds. * **A profile** overrides `processes` and `command_limits` for its sessions, field by field over the workspace's. It may raise a workspace's value as well as lower it; only a host ceiling holds it. ## What each limit stops | Case | Limit | Default | What the line sees | | - | - | - | - | | A loop that never ends | `command_limits` `@line` `timeout_seconds` | 600 seconds | exit 124, `line: timed out after 600s` | | A fork bomb, `b() { b \| b; }; b` | `processes.max` | 128 per session | exit 254, `bash: fork: Resource temporarily unavailable` | | A variable that keeps doubling, `x=$x$x` | `max_env` | `2MB` per session | exit 2, `bash: xmalloc: cannot allocate N bytes (past max_env of N bytes, a mirage workspace setting)` | | A file or a command's output held in memory | `max_memory` | `96MB` per workspace | exit 1, `line: memory exhausted`; a write to a RAM file fails with `Disk quota exceeded` | | One API reply read whole | `max_body_bytes` | `64MB` | the call fails | | Deep recursion in functions, `source`, `eval` or `bash -c` | 32 levels | fixed; `FUNCNEST` can lower it | exit 1, `environment: line 1: f: maximum function nesting level exceeded (32)` | | Many sessions on one workspace | `max_sessions` | 16, or 4 on an edge runtime | HTTP 429 | | Many workspaces on one server | `max_workspaces` | no cap | HTTP 503 | | A burst of requests | `rate_limits` | `ip=1000/minute` | HTTP 429 | `max_env` counts the bytes of a session's variables, functions, aliases and positional parameters, one more for each array element and parameter, and a session that would start past it, from the workspace's `env`, a profile's or a snapshot, is refused. `processes.max` counts every pipeline stage, subshell and background job a session has running. `timeout` stops the jobs its command started when the time runs out, as GNU's does by signalling its process group, unless it is given `--foreground`, `-s INT` or `-s QUIT`. As in Bash, a background job that is one program ignores `INT`, one that runs several commands loses only the command, subshell or pipeline it is running and goes on, and one that runs a function ends with it. Some bounds are fixed: * A session id, profile name or workspace id is 1 to 128 characters, with no control characters. * A history read returns the newest 10,000 entries, and `/.bash_history` the newest 10,000 commands. A workspace that keeps its history in memory holds at most 8 MB of it, and drops the oldest entries first. * A line sends at most 1000 `vfs.` spans to [OpenTelemetry](/home/infrastructure/history#send-it-to-opentelemetry), or as many as `MIRAGE_TRACE_MAX_SPANS` says. ## Set them on a workspace ```yaml theme={null} max_memory: 32MB max_env: 2MB processes: {max: 64} command_limits: "@line": {timeout_seconds: 120} profiles: batch: processes: {max: 512} command_limits: "@line": {timeout_seconds: 900} ``` Here a `batch` session runs 512 processes and 15-minute lines, and every other session 64 processes and 2-minute lines. See [configuration](/home/configuration), [profiles](/home/profiles) and [output limits](/home/core/output-limits). ## Set the host's ceilings A tenant controls its own workspace's config and profiles, so a host that runs other people's agents holds them under ceilings. Each comes from the app's option, else its environment variable, else its key in `~/.mirage/config.toml`: | Key | Env var | Holds | | - | - | - | | `max_memory` | `MIRAGE_MAX_MEMORY` | any workspace's `max_memory` | | `max_env` | `MIRAGE_MAX_ENV` | any workspace's `max_env` | | `max_processes` | `MIRAGE_MAX_PROCESSES` | any session's `processes.max` | | `max_line_seconds` | `MIRAGE_MAX_LINE_SECONDS` | any line's time limit | | `max_sessions` | `MIRAGE_MAX_SESSIONS` | the sessions each workspace holds | | `max_workspaces` | `MIRAGE_MAX_WORKSPACES` | the workspaces the server holds | ```toml theme={null} [daemon] max_memory = "64MB" max_env = "2MB" max_processes = 64 max_line_seconds = 300 max_sessions = 8 ``` The ceilings hold whatever sets the value: a create request, a profile replaced over HTTP, or a snapshot loaded later. The [Python](/python/access/server) and [TypeScript](/typescript/access/server) servers and the [Cloudflare app](/typescript/cloudflare-quickstart) take the same settings as options. # Airtable Source: https://docs.mirage.strukto.ai/home/setup/airtable Create an Airtable personal access token for the Airtable VFS. ## Credentials ### 1. Create a Personal Access Token 1. Go to [airtable.com/create/tokens](https://airtable.com/create/tokens) 2. Create a token with the scopes `data.records:read` and `schema.bases:read` 3. For the [airtable CLI](/home/setup/cli/airtable)'s writes, add `data.records:write`, and for comments `data.recordComments:read` and `data.recordComments:write` 4. Under **Access**, add the bases the mount should see 5. Copy the token (it starts with `pat`) The mount only reads; writes go through the airtable CLI. A token without `schema.bases:read` cannot list tables, and a base left out of the token's access list is invisible to it. ### 2. Set Environment Variables ```bash theme={null} # .env.development AIRTABLE_TOKEN=patXXXXXXXXXXXXXX.xxxx... ``` For SDK guides, see [Airtable (Python)](/python/vfs/airtable) and [Airtable (TypeScript)](/typescript/setup/airtable). # Alibaba OSS Source: https://docs.mirage.strukto.ai/home/setup/aliyun Set up Alibaba Cloud OSS credentials for the Aliyun VFS. ## Credentials ### 1. Create an AccessKey pair 1. Sign in to the [Alibaba Cloud console](https://www.aliyun.com/) 2. Go to **AccessKey Management** (RAM user recommended) -> **Create AccessKey** 3. Copy the **AccessKey ID** and **AccessKey Secret** 4. Note your bucket's **region** (e.g. `cn-hangzhou`) and **bucket** name The endpoint is derived from `region` as `s3.oss-.aliyuncs.com`. Note the `s3.` prefix: this is the S3-compatible host, distinct from the native `oss-.aliyuncs.com`. ### 2. Set environment variables ```bash theme={null} # .env.development OSS_BUCKET=my-bucket OSS_REGION=cn-hangzhou OSS_ACCESS_KEY_ID=... OSS_ACCESS_KEY_SECRET=... ``` For SDK guides, see [Alibaba OSS (Python)](/python/vfs/aliyun) and [Alibaba OSS (TypeScript)](/typescript/setup/aliyun). # Backblaze B2 Source: https://docs.mirage.strukto.ai/home/setup/backblaze Set up Backblaze B2 credentials for the Backblaze VFS. ## Credentials ### 1. Create an application key 1. Sign in to [Backblaze](https://secure.backblaze.com/) -> **B2 Cloud Storage** 2. Go to **Application Keys** -> **Add a New Application Key** 3. Scope it to your bucket with at least **Read** access 4. Copy the **keyID** (access key id) and **applicationKey** (secret access key) 5. Note your bucket's **endpoint region** from the bucket details (e.g. `us-west-004`) and the **bucket** name The endpoint is derived from `region` as `s3..backblazeb2.com`. ### 2. Set environment variables ```bash theme={null} # .env.development B2_BUCKET=my-bucket B2_REGION=us-west-004 B2_ACCESS_KEY_ID=... # B2 keyID B2_SECRET_ACCESS_KEY=... # B2 applicationKey ``` For SDK guides, see [Backblaze B2 (Python)](/python/vfs/backblaze) and [Backblaze B2 (TypeScript)](/typescript/setup/backblaze). # Box Source: https://docs.mirage.strukto.ai/home/setup/box Set up Box OAuth2 credentials and obtain a refresh token (Python, Node, and browser). ## Overview The Box VFS uses OAuth2 against the [Box v2 API](https://developer.box.com/reference/) to: * **`/folders/{id}/items`**, list folder items (root id is `0`) * **`/files/{id}/content`**, download file bytes * **`/files/{id}`** / **`/folders/{id}`**, fetch entry metadata * **`/search`**, search files by name/content * **`/oauth2/token`**, refresh access tokens Box is similar to Dropbox in shape but uses **numeric folder/file IDs** rather than paths. Mirage caches the path → ID mapping in the index store, so once you `ls /box/` the IDs are remembered and subsequent reads don't pay the lookup cost. Four credential modes are supported: * **Developer token**, fastest first-run path. Click one button in the Box app console, paste the 32-char access token, and you're done. Lives 60 minutes; you regenerate by hand. No client\_id / refresh\_token / OAuth flow needed. Recommended for `mirage` exploration. * **Code flow with client secret**, for Node/server long-running use. Needs `client_id`, `client_secret`, `refresh_token`. * **PKCE flow**, for browsers. Needs only `client_id` and `refresh_token` (no secret in the bundle). * **Client credentials (service account)**, for headless servers. Needs `client_id`, `client_secret`, `enterprise_id`; no refresh token, expired tokens are re-fetched. Follow the [service-account setup](/typescript/setup/box#service-account-client-credentials-no-refresh-token) to create a Server Authentication app and authorize it in the Box admin console. > [!NOTE] > > **Box rotates the refresh token on every refresh.** The token you copy out of the initial code > exchange is only valid until the next refresh, after that, only the new rotated token works. > The `BoxTokenManager` keeps the latest token in memory; pass `onRefreshTokenRotated` if you > want to persist it across restarts (the browser example does this with `localStorage`). ## Quick Start: Developer Token (60 minutes, no OAuth) If you just want to try the VFS against your own Box account, the developer token is the fastest path, no redirect URI, no client secret, no curl exchange: 1. Go to [https://app.box.com/developers/console](https://app.box.com/developers/console) -> **Create New App** -> **Custom App** -> **User Authentication (OAuth 2.0)** -> name it "Mirage" -> **Create App** 2. On the **Configuration** tab, scroll to the **Developer Token** section near the bottom. 3. Click **Generate Developer Token**. Copy the 32-char token. 4. Save it for the repository examples in `.env.development`: ```bash theme={null} BOX_DEVELOPER_TOKEN=... ``` 5. Run any of the examples in [`examples/typescript/vfs/box/`](https://github.com/strukto-ai/mirage/tree/main/examples/typescript/vfs/box). The token expires in **60 minutes** and there is no programmatic way to renew it; you regenerate by hand. For long-running processes, use the OAuth flow below instead. ## Setup (long-running OAuth flow) ### 1. Create a Box App 1. Go to [https://app.box.com/developers/console](https://app.box.com/developers/console) 2. Click **Create New App** 3. Choose **Custom App** 4. **Authentication Method**: **User Authentication (OAuth 2.0)** 5. Name it (e.g. "Mirage") -> **Create App** ### 2. Configure the App Open the app's **Configuration** tab: * **OAuth 2.0 Redirect URIs**: add every destination you'll redirect back to. Box accepts multiple values, register them all up front so you don't bounce between dev and prod: * For the CLI flow below: `http://localhost:1` * For the browser PKCE example: `http://localhost:5173/vfs/box/box_pkce.html` * For production: e.g. `https://yourapp.com/box/callback` * **Allowed Origins** (only needed if you'll call from a browser; older Box docs call this "CORS Domains"): * `http://localhost:5173` * Any production origins (e.g. `https://yourapp.com`) * **Application Scopes**: * **Read all files and folders stored in Box** (required) * **Write all files and folders stored in Box** (only if you'll mount Box in `WRITE` mode) * Click **Save Changes** ### 3. Submit for Authorization (enterprise apps only) If your Box account is part of an enterprise, the **Authorization** tab requires an admin to approve the app before it can issue tokens. Personal/free Box accounts skip this step. ### 4. Copy the Client Credentials Still on **Configuration**, copy: * **Client ID** -> `BOX_CLIENT_ID` * **Client Secret** -> `BOX_CLIENT_SECRET` (skip if you only need PKCE) ### 5. Get the Refresh Token (CLI flow with client secret) **A) Open this URL in a browser** (replace `YOUR_CLIENT_ID`): ``` https://account.box.com/api/oauth2/authorize?response_type=code&client_id=YOUR_CLIENT_ID&redirect_uri=http://localhost:1 ``` **B) Authorize:** sign in -> click **Grant access**. **C) Copy the code:** browser redirects to `http://localhost:1?code=...` (page won't load, expected). Copy the `code` from the URL bar. **D) Exchange the code:** ```bash theme={null} curl https://api.box.com/oauth2/token \ -d "code=THE_CODE" \ -d "grant_type=authorization_code" \ -d "client_id=YOUR_CLIENT_ID" \ -d "client_secret=YOUR_CLIENT_SECRET" \ -d "redirect_uri=http://localhost:1" ``` Response shape: ```json theme={null} { "access_token": "T...", "expires_in": 3884, "refresh_token": "R...", "restricted_to": [], "token_type": "bearer" } ``` Save the `refresh_token`. ### 6. Set Environment Variables ```bash theme={null} # .env.development BOX_CLIENT_ID=... BOX_CLIENT_SECRET=... BOX_REFRESH_TOKEN=... ``` ## Alternative: PKCE Flow (browser, no client secret) 1. Add `http://localhost:5173/vfs/box/box_pkce.html` to **OAuth 2.0 Redirect URIs** 2. Add `http://localhost:5173` to **Allowed Origins** 3. Set only `BOX_CLIENT_ID` in `.env.development` 4. From `examples/browser/`, run `pnpm dev` 5. Open `http://localhost:5173/vfs/box/box_pkce.html` and click **Connect Box** The example persists the rotated refresh token to `localStorage` via the `onRefreshTokenRotated` callback so subsequent page loads work without re-auth. ## Token Lifetime | Token | Lifetime | | - | - | | Access token | \~1 hour (`expires_in: ~3600`) | | Refresh token | 60 days from issue, OR 60 days from last use (whichever) | A refresh token gets revoked when: * 60 days pass without use * The user revokes the app at [https://app.box.com/account/security](https://app.box.com/account/security) * The Box account password changes * A new refresh token is issued (the old one expires after a short grace period) The `BoxTokenManager` always uses the latest token. For long-running processes restart-safe, provide `onRefreshTokenRotated` to persist the new token to disk / a vault. ## CORS Notes Unlike Dropbox, Box has first-class CORS but **only for origins you've explicitly allowlisted** in the **Allowed Origins** section of the app configuration. If you see browser-side `Access-Control-Allow-Origin` errors, double-check the origin matches exactly (no trailing slash; protocol matters). ## Troubleshooting | Issue | Fix | | - | - | | `400 invalid_grant` on token exchange | The `code` is single-use and short-lived, redo Step 5A with a fresh URL | | `403 access_denied` | Enterprise admin hasn't approved the app on the **Authorization** tab | | `401 unauthorized` after a few hours | Refresh token rotation, the original token is invalid; persist via `onRefreshTokenRotated` | | Browser: `CORS error` even though origin set | Check that the origin in **Allowed Origins** is exact (no trailing slash, http vs https) | | `path/not_found` on `ls /box//` | The folder name was constructed wrong, use `ls /box/` first, then drill into a name from the list | For TypeScript usage: ```ts theme={null} import { BoxVFS } from '@struktoai/mirage-node' const box = new BoxVFS({ clientId: process.env.BOX_CLIENT_ID!, clientSecret: process.env.BOX_CLIENT_SECRET!, refreshToken: process.env.BOX_REFRESH_TOKEN!, }) ``` Or browser (PKCE): ```ts theme={null} import { BoxVFS } from '@struktoai/mirage-browser' const box = new BoxVFS({ clientId: 'YOUR_CLIENT_ID', refreshToken: refreshTokenFromLocalStorage, onRefreshTokenRotated: (next) => localStorage.setItem('box-refresh', next), }) ``` For Python usage (same credentials), see [Box (Python)](/python/vfs/box): ```python theme={null} from mirage.vfs.box import BoxConfig, BoxVFS vfs = BoxVFS(BoxConfig( client_id=os.environ["BOX_CLIENT_ID"], client_secret=os.environ["BOX_CLIENT_SECRET"], refresh_token=os.environ["BOX_REFRESH_TOKEN"], )) ``` # Ceph (Rados Gateway) Source: https://docs.mirage.strukto.ai/home/setup/ceph Set up Ceph Rados Gateway (RGW) credentials for the Ceph VFS. ## Credentials ### 1. Create an RGW user On a host with `radosgw-admin` access: ```bash theme={null} radosgw-admin user create --uid=mirage --display-name="Mirage" ``` The output includes a `keys` block with `access_key` and `secret_key`. Note your gateway **endpoint** (e.g. `https://ceph.example.com`) and the **bucket** name. Ceph RGW is self-hosted, so there is no region-derived endpoint, the `endpoint_url` is required and RGW uses path-style addressing. ### 2. Set environment variables ```bash theme={null} # .env.development CEPH_BUCKET=my-bucket CEPH_ENDPOINT_URL=https://ceph.example.com CEPH_ACCESS_KEY_ID=... CEPH_SECRET_ACCESS_KEY=... ``` For SDK guides, see [Ceph (Rados Gateway) (Python)](/python/vfs/ceph) and [Ceph (Rados Gateway) (TypeScript)](/typescript/setup/ceph). # Chroma Source: https://docs.mirage.strukto.ai/home/setup/chroma Prepare a ChromaDB collection for the Chroma VFS. ## Requirements Mirage mounts an existing ChromaDB collection as a read-only virtual filesystem. The collection must already contain: * One path tree document with ID `__path_tree__`. * One or more page chunk documents. * A metadata field that maps each chunk to a virtual file path slug. * A metadata field that orders chunks within each file. The Python VFS connects via Chroma's `AsyncHttpClient`. ## Path Tree Document The path tree document defines the filesystem tree. Store it in Chroma with the ID `__path_tree__`. Its document content must be either plain JSON or gzip-compressed base64 JSON. ```json theme={null} { "README.md": { "size": 1024, "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-02T00:00:00Z" }, "guides/quickstart.md": { "size": 4096, "updated_at": "2026-01-03T00:00:00Z" } } ``` Path tree keys become file paths below the Mirage mount. Use forward slashes to create directories. Path rules: * Do not use an empty path. * Do not use `.`, `..`, or empty path segments. * Keep every path unique after trimming leading and trailing slashes. * Do not use a path both as a file and as a directory prefix. For example, `guides` and `guides/quickstart.md` cannot both be files. Metadata fields are optional. Mirage uses `size`, `created_at`, and `updated_at` when present. ## Chunk Documents Each file is materialized from one or more Chroma documents. Every chunk must include metadata that identifies the file slug and chunk order: ```json theme={null} { "page_slug": "guides/quickstart.md", "chunk_index": 0 } ``` Default metadata fields: | Field | Default | Purpose | | - | - | - | | Slug field | `page_slug` | File path in the virtual tree | | Chunk index field | `chunk_index` | Sort order when assembling file content | If your collection uses different metadata names, configure `ChromaConfig(slug_field="...", chunk_index_field="...")`. ## Environment Variables ```bash theme={null} # .env.development CHROMA_COLLECTION=knowledge CHROMA_HOST=localhost CHROMA_PORT=8000 CHROMA_SSL=false CHROMA_SLUG_FIELD=page_slug CHROMA_CHUNK_INDEX_FIELD=chunk_index CHROMA_EXAMPLE_QUERY=getting started ``` ## Validate the Collection Before mounting, verify that the collection contains the path tree document and at least one chunk with matching slug metadata: ```python theme={null} import chromadb client = chromadb.HttpClient(host="localhost", port=8000) collection = client.get_collection("knowledge") tree = collection.get(ids=["__path_tree__"]) chunks = collection.get(where={"page_slug": "guides/quickstart.md"}) print(tree["documents"][0]) print(len(chunks["documents"])) ``` For SDK guides, see [Chroma (Python)](/python/vfs/chroma) and [Chroma (TypeScript)](/typescript/setup/chroma). # Airtable Source: https://docs.mirage.strukto.ai/home/setup/cli/airtable Set up the Airtable CLI with Python or TypeScript. Mirage defines this command tree over the [Airtable Web API](https://airtable.com/developers/web/api/introduction). Create a token in [Airtable setup](/home/setup/airtable), with the write scopes the CLI needs, then register it on an existing `ws`. Commands: [Python](/python/cli/airtable) · [TypeScript](/typescript/cli/airtable). > [tab] Python > > ```python theme={null} > from mirage.commands.cli.builtin.airtable import AIRTABLE > from mirage.vfs.airtable import AirtableConfig > > config = AirtableConfig(token="pat...") > ws.register_cli("airtable", AIRTABLE, config.model_dump()) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { AIRTABLE } from '@struktoai/mirage-node' > > const config = { token: 'pat...' } > ws.registerCli('airtable', AIRTABLE, config) > ``` # Discord Source: https://docs.mirage.strukto.ai/home/setup/cli/discord Set up the Discord CLI with Python or TypeScript. Create a bot token in [Discord setup](/home/setup/discord), then register it on an existing `ws`. Commands: [Python](/python/cli/discord) · [TypeScript](/typescript/cli/discord). > [tab] Python > > ```python theme={null} > from mirage.commands.cli.builtin.discord import DISCORD > from mirage.core.discord.config import DiscordConfig > > config = DiscordConfig(token="bot-token") > ws.register_cli("discord", DISCORD, config.model_dump()) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { DISCORD } from '@struktoai/mirage-node' > > const config = { token: 'bot-token' } > ws.registerCli('discord', DISCORD, config) > ``` Grant Send Messages for `send`/`edit`/`poll` and Send Polls for `poll`. Add Reactions is needed for `react`, Create Public Threads for `thread-create`, and Manage Messages when deleting others' messages. # gh Source: https://docs.mirage.strukto.ai/home/setup/cli/gh Set up the GitHub CLI with Python or TypeScript. Mirage implements a subset of the [GitHub CLI (`gh`)](https://github.com/cli/cli). Create a token in [GitHub setup](/home/setup/github), then register it on an existing `ws`. Commands: [Python](/python/cli/gh) · [TypeScript](/typescript/cli/gh). > [tab] Python > > ```python theme={null} > from mirage.commands.cli.builtin.gh import GH > from mirage.core.github.config import GhConfig > > config = GhConfig(token="github_pat_...", repo="acme/tools") > ws.register_cli("gh", GH, config.model_dump()) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { GH } from '@struktoai/mirage-node' > > ws.registerCli('gh', GH, { token: 'github_pat_...', repo: 'acme/tools' }) > ``` Fine-grained tokens need permissions matching the commands used: Issues, Pull requests, Actions, Contents, or Administration. `gh api` is endpoint-specific; consult GitHub's [fine-grained token permission table](https://docs.github.com/en/rest/authentication/permissions-required-for-fine-grained-personal-access-tokens). # git Source: https://docs.mirage.strukto.ai/home/setup/cli/git Set up the credential-free git CLI with Python or TypeScript. Mirage implements a subset of the [Git command line](https://git-scm.com/docs/git), using [Dulwich](https://github.com/jelmer/dulwich) in Python and [isomorphic-git](https://github.com/isomorphic-git/isomorphic-git) in TypeScript. `git` needs no account config and reads repositories through existing mounts. Register it on `ws`. Commands: [Python](/python/cli/git) · [TypeScript](/typescript/cli/git). > [tab] Python > > ```python theme={null} > from mirage.commands.cli.builtin.git import GIT > > ws.register_cli("git", GIT) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { GIT } from '@struktoai/mirage-node' > > ws.registerCli('git', GIT) > ``` # GWS Source: https://docs.mirage.strukto.ai/home/setup/cli/gws Set up the Google Workspace CLI with Python or TypeScript. Mirage implements a subset of the [Google Workspace CLI (`gws`)](https://github.com/googleworkspace/cli). Create OAuth credentials in [Google Workspace setup](/home/setup/google), then register them on an existing `ws`. Commands: [Python](/python/cli/gws) · [TypeScript](/typescript/cli/gws). > [tab] Python > > ```python theme={null} > from mirage.commands.cli.builtin.gws import GWS > from mirage.core.google.config import GoogleConfig > > config = GoogleConfig( > client_id="...", client_secret="...", refresh_token="..." > ) > ws.register_cli("gws", GWS, config.model_dump()) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { GWS } from '@struktoai/mirage-node' > > const config = { clientId: '...', clientSecret: '...', refreshToken: '...' } > ws.registerCli('gws', GWS, config) > ``` Forms is CLI-only. Enable the Google Forms API and grant `https://www.googleapis.com/auth/forms.body` to create or edit forms. Reading responses needs `https://www.googleapis.com/auth/forms.responses.readonly`. Creating forms inside a configured folder also needs the Drive API and scope. # hf Source: https://docs.mirage.strukto.ai/home/setup/cli/hf Set up the Hugging Face CLI with Python or TypeScript. Create a token in [HF Models setup](/home/setup/hf_models), then register it on an existing `ws`. Commands: [Python](/python/cli/hf) · [TypeScript](/typescript/cli/hf). > [tab] Python > > ```python theme={null} > from mirage.commands.cli.builtin.hf import HF > > ws.register_cli("hf", HF, {"token": "hf_..."}) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { HF } from '@struktoai/mirage-node' > > ws.registerCli('hf', HF, { token: 'hf_...' }) > ``` A Hub mount reads; `hf` also writes. Use a write token to upload, delete, create repositories, or create/delete tags. A read token is enough to download files or list tags. To edit a Hub file, download it into a local mount, edit it there, then upload it. A Hub write is a commit, so edits happen through the CLI. # Himalaya Source: https://docs.mirage.strukto.ai/home/setup/cli/himalaya Set up the Himalaya mail CLI with Python or TypeScript. Create credentials in [Email setup](/home/setup/email), then register them on an existing `ws`. Commands: [Python](/python/cli/himalaya) · [TypeScript](/typescript/cli/himalaya). > [tab] Python > > ```bash theme={null} > pip install 'mirage-ai[email]' > ``` > > ```python theme={null} > from mirage.commands.cli.builtin.himalaya import HIMALAYA > from mirage.core.email.config import EmailConfig > > config = EmailConfig( > imap_host="imap.example.com", > smtp_host="smtp.example.com", > username="agent@example.com", > password="app-password", > ) > ws.register_cli("himalaya", HIMALAYA, config.model_dump()) > ``` > [tab] TypeScript > > ```bash theme={null} > pnpm add imapflow mailparser nodemailer > ``` > > ```typescript theme={null} > import { HIMALAYA } from '@struktoai/mirage-node' > > const config = { > imapHost: 'imap.example.com', > smtpHost: 'smtp.example.com', > username: 'agent@example.com', > password: 'app-password', > } > ws.registerCli('himalaya', HIMALAYA, config) > ``` # Linear Source: https://docs.mirage.strukto.ai/home/setup/cli/linear Set up the Linear CLI with Python or TypeScript. Mirage's Linear commands draw partly on [schpet/linear-cli](https://github.com/schpet/linear-cli); the references below define the supported grammar. Create an API key in [Linear setup](/home/setup/linear), then register it on an existing `ws`. Commands: [Python](/python/cli/linear) · [TypeScript](/typescript/cli/linear). > [tab] Python > > ```python theme={null} > from mirage.commands.cli.builtin.linear import LINEAR > from mirage.core.linear.config import LinearConfig > > config = LinearConfig(api_key="lin_api_...") > ws.register_cli("linear", LINEAR, config.model_dump()) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { LINEAR } from '@struktoai/mirage-node' > > const config = { apiKey: 'lin_api_...' } > ws.registerCli('linear', LINEAR, config) > ``` # ntn Source: https://docs.mirage.strukto.ai/home/setup/cli/ntn Set up the Notion CLI with Python or TypeScript. Create a token in [Notion setup](/home/setup/notion), then register it on an existing `ws`. Commands: [Python](/python/cli/ntn) · [TypeScript](/typescript/cli/ntn). > [tab] Python > > ```python theme={null} > from mirage.commands.cli.builtin.ntn import NTN > from mirage.core.notion.config import NotionConfig > > config = NotionConfig(api_key="secret_...") > ws.register_cli("ntn", NTN, config.model_dump()) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { NTN } from '@struktoai/mirage-node' > > const config = { apiKey: 'secret_...' } > ws.registerCli('ntn', NTN, config) > ``` # search Source: https://docs.mirage.strukto.ai/home/setup/cli/search Set up the search CLI for Dify, Chroma, mem0, Qdrant and LanceDB mounts with Python or TypeScript. `search` ranks the records of Dify, Chroma, mem0, Qdrant and LanceDB mounts with each store's own search. It needs no account config and searches the mounts it is pointed at. Register it on `ws`. Commands: [Python](/python/cli/search) · [TypeScript](/typescript/cli/search). > [tab] Python > > ```python theme={null} > from mirage.commands.cli.builtin.search import SEARCH > > ws.register_cli("search", SEARCH) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { SEARCH } from '@struktoai/mirage-node' > > ws.registerCli('search', SEARCH) > ``` # Slack Source: https://docs.mirage.strukto.ai/home/setup/cli/slack Set up the Slack CLI with Python or TypeScript. Create tokens in [Slack setup](/home/setup/slack), then register them on an existing `ws`. Commands: [Python](/python/cli/slack) · [TypeScript](/typescript/cli/slack). > [tab] Python > > ```python theme={null} > from mirage.commands.cli.builtin.slack import SLACK > from mirage.core.slack.config import SlackConfig > > config = SlackConfig(token="xoxb-...", search_token="xoxp-...") > ws.register_cli("slack", SLACK, config.model_dump()) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { SLACK } from '@struktoai/mirage-node' > > const config = { token: 'xoxb-...', searchToken: 'xoxp-...' } > ws.registerCli('slack', SLACK, config) > ``` Reaction commands need `reactions:read`/`reactions:write`, pin commands need `pins:read`/`pins:write`, and `emoji-list` needs `emoji:read`. Reinstall the app after changing scopes. # Trello Source: https://docs.mirage.strukto.ai/home/setup/cli/trello Set up the Trello CLI with Python or TypeScript. Mirage defines this command tree over the [Trello REST API](https://developer.atlassian.com/cloud/trello/rest/). Create an API key and token in [Trello setup](/home/setup/trello), then register them on an existing `ws`. Commands: [Python](/python/cli/trello) · [TypeScript](/typescript/cli/trello). > [tab] Python > > ```python theme={null} > from mirage.commands.cli.builtin.trello import TRELLO > from mirage.core.trello.config import TrelloConfig > > config = TrelloConfig(api_key="...", api_token="...") > ws.register_cli("trello", TRELLO, config.model_dump()) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { TRELLO } from '@struktoai/mirage-node' > > const config = { apiKey: '...', apiToken: '...' } > ws.registerCli('trello', TRELLO, config) > ``` # Overview Source: https://docs.mirage.strukto.ai/home/setup/clis Set up Mirage CLIs with Python or TypeScript. Mirage bundles twelve command-line programs for its workspace shell. The [host `mirage` CLI](/home/access/cli) connects to a workspace; these programs run inside it. Each setup page includes Python and TypeScript registration. | Program | Supported operations | Commands | | - | - | - | | [airtable](/home/setup/cli/airtable) | Query bases and tables; read, create, update and delete records; add comments | 10 | | [discord](/home/setup/cli/discord) | Read and send messages; edit, react, create threads and polls; inspect guilds | 14 | | [gh](/home/setup/cli/gh) | Manage repositories, issues, pull requests, releases and Actions; call GitHub APIs | 103 | | [git](/home/setup/cli/git) | Inspect history, stage and commit files, manage branches and tags, clone and fetch | 44 | | [gws](/home/setup/cli/gws) | Call Drive, Sheets, Docs, Slides, Calendar, Forms and Gmail APIs | 54 | | [hf](/home/setup/cli/hf) | Download and upload Hub files; create repositories; manage tags and delete files | 11 | | [himalaya](/home/setup/cli/himalaya) | List and search mail; read, compose, reply, forward and send messages | 17 | | [linear](/home/setup/cli/linear) | Query teams, issues, projects and documents; update issues and comments | 30 | | [ntn](/home/setup/cli/ntn) | Read and edit Markdown pages, query data sources and call Notion APIs | 12 | | [search](/home/setup/cli/search) | Rank the records of Dify, Chroma, mem0, Qdrant and LanceDB mounts for a query | 1 | | [slack](/home/setup/cli/slack) | Read and send messages; manage reactions and pins; find members and search | 14 | | [trello](/home/setup/cli/trello) | Read boards, lists, labels and cards; create, update, move, assign, label and comment on cards | 16 | Account CLIs use their own validated config and can run without a service mount. Credentials can be reused with the corresponding VFS; mounting a service does not register its CLI. `git` and `search` need no account config: `git` uses repositories on workspace mounts and `search` asks the search of the mounts it is pointed at. All twelve are available in Python and TypeScript on Node. TypeScript exports `hf` and `himalaya` from `@struktoai/mirage-node`, and the other ten from `@struktoai/mirage-core`. Use ` --help` for its groups, ` --help` for flags, and `man ` for its manual. The [Python](/python/cli/index) and [TypeScript](/typescript/cli/index) references list the implemented commands and explain how CLI file arguments use the VFS. ## Compatibility and licenses Each CLI reference links the original project or service API and defines the implemented subset. Compatibility covers the documented commands, flags, output and behavior; it does not promise every upstream feature. Git also names its actual runtime dependencies: Dulwich in Python and isomorphic-git in TypeScript. Mirage-authored code is [Apache-2.0 licensed](https://github.com/strukto-ai/mirage/blob/main/LICENSE). Behavioral compatibility does not change the license of any project's code. Copied or ported source and redistributed dependencies must satisfy their own license and notice requirements. The [Python notices](https://github.com/strukto-ai/mirage/blob/main/python/THIRD_PARTY_NOTICES) and the TypeScript notices of [core](https://github.com/strukto-ai/mirage/blob/main/typescript/packages/core/THIRD_PARTY_NOTICES) and [node](https://github.com/strukto-ai/mirage/blob/main/typescript/packages/node/THIRD_PARTY_NOTICES) cover incorporated third-party code; installed libraries also include their own license files. A compatibility claim is not a substitute for checking source provenance and the contents of a distribution. # Custom VFS Source: https://docs.mirage.strukto.ai/home/setup/custom-vfs Mount a service Mirage does not ship by writing your own VFS in Python or TypeScript. A VFS is a class that extends `BaseVFS`. Override `readdir`, `stat` and `read`, and `ls`, `cat`, `grep`, `find` and the other read commands work on your service. Every other method is optional: override one, and the commands that need it start working, or complete with fewer requests. ## The base class The methods you can override, with the arguments you normally use: > [tab] Python > > ```python theme={null} > class BaseVFS: > name: str > vfs_md: str > > async def readdir(self, path: PathSpec) -> list[FileStat]: ... > async def stat(self, path: PathSpec) -> FileStat: ... > async def read(self, path: PathSpec) -> bytes | AsyncIterator[bytes]: ... > > async def write(self, path: PathSpec, data: bytes | AsyncIterator[bytes]) -> FileStat | None: ... > async def append(self, path: PathSpec, data: bytes | AsyncIterator[bytes]) -> FileStat | None: ... > async def copy(self, src: PathSpec, dst: PathSpec) -> FileStat | None: ... > async def truncate(self, path: PathSpec, length: int, no_create: bool = False) -> FileStat | None: ... > async def rename(self, src: PathSpec, dst: PathSpec) -> FileStat | None: ... > async def unlink(self, path: PathSpec) -> None: ... > async def mkdir(self, path: PathSpec, parents: bool = False) -> FileStat | None: ... > async def rmdir(self, path: PathSpec) -> None: ... > async def rm_r(self, path: PathSpec) -> None: ... > async def dir_copy(self, src: PathSpec, dst: PathSpec) -> FileStat | None: ... > async def setattr(self, path: PathSpec, *, mode: int | None = None, uid: int | str | None = None, gid: int | str | None = None, atime: str | None = None, mtime: str | None = None) -> dict[str, int | str]: ... > > async def files_containing(self, path: PathSpec, text: str, *, whole_word: bool, ignore_case: bool) -> list[PathSpec] | None: ... > async def lines_containing(self, path: PathSpec, text: str, *, ignore_case: bool) -> bytes | AsyncIterator[bytes] | None: ... > async def first_lines(self, path: PathSpec, n: int) -> bytes | None: ... > async def last_lines(self, path: PathSpec, n: int) -> bytes | None: ... > async def line_count(self, path: PathSpec) -> int | None: ... > async def follow(self, path: PathSpec, n: int, interval: float) -> AsyncIterator[bytes] | None: ... > async def checksum(self, path: PathSpec, algorithm: str) -> str | None: ... > async def read_tree(self, path: PathSpec) -> dict[str, FileStat] | None: ... > > async def close(self) -> None: ... > ``` > [tab] TypeScript > > ```typescript theme={null} > declare class BaseVFS { > name: string > vfsMd: string > > readdir(path: PathSpec): Promise > stat(path: PathSpec): Promise > read(path: PathSpec): Promise> | AsyncIterable > > write(path: PathSpec, data: Uint8Array | AsyncIterable): Promise > append(path: PathSpec, data: Uint8Array | AsyncIterable): Promise > copy(src: PathSpec, dst: PathSpec): Promise > truncate(path: PathSpec, length: number, noCreate?: boolean): Promise > rename(src: PathSpec, dst: PathSpec): Promise > unlink(path: PathSpec): Promise > mkdir(path: PathSpec, parents?: boolean): Promise > rmdir(path: PathSpec): Promise > rmR(path: PathSpec): Promise > dirCopy(src: PathSpec, dst: PathSpec): Promise > setattr(path: PathSpec, fields: SetAttrFields): Promise> > > filesContaining(path: PathSpec, text: string, opts: { wholeWord: boolean; ignoreCase: boolean }): Promise > linesContaining(path: PathSpec, text: string, opts: { ignoreCase: boolean }): Promise | null> > firstLines(path: PathSpec, n: number): Promise > lastLines(path: PathSpec, n: number): Promise > lineCount(path: PathSpec): Promise > follow(path: PathSpec, n: number, interval: number): Promise | null> > checksum(path: PathSpec, algorithm: string): Promise > readTree(path: PathSpec): Promise | null> > > close(): Promise > } > ``` ## How to integrate your service ### Required | Method | Used by | | - | - | | `readdir` | `ls`, `find`, `tree`, globs | | `stat` | every command | | `read` | `cat`, `grep`, `head`, `wc` and every other command that reads | ### Write Writes need a writable mount: `MountMode.WRITE`, or `mode: write` in YAML. | Method | With it | Without it | | - | - | - | | `write` | `>`, `tee`, `touch` and `sed -i` work. | They fail. | | `append` | `>>` calls it. | `>>` reads the file and calls `write`. | | `copy` | `cp` calls it. | `cp` reads the file and calls `write`. | | `truncate` | `truncate` calls it. | `truncate` calls `write`, and `truncate -c` fails with `Operation not supported`. | | `rename` | `mv` works. | `mv` fails with `Operation not supported`. | | `unlink` | `rm` works. | `rm` fails with `Operation not supported`. | | `mkdir` | `mkdir` works. | `mkdir` fails with `Operation not supported`. | | `rmdir` | `rmdir` works. | `rmdir` fails with `Operation not supported`. | | `rm_r` | `rm -r` calls it once. | `rm -r` calls `unlink` and `rmdir` for each entry. | | `dir_copy` | `cp -r` calls it once when it copies a folder to a new place and `copy` is overridden too. | `cp -r` calls `mkdir` for each folder and `copy`, or a read and `write`, for each file. | | `setattr` | `chmod` and `touch -d` call it. | Mirage keeps the mode and times itself. | [VFS.md](/home/setup/vfs-md) tells the agent which of these commands work on each mount, from the methods its VFS overrides. ### Answer commands with your service Override these to answer from your service's own search, query or metadata API instead of reading files. Each links to its guide. | Method | With it | Without it | | - | - | - | | [`files_containing`](/home/integration/search) | `grep -r` and `rg` read only the files it names. | They read every file. | | [`lines_containing`](/home/integration/search) | `grep` and `rg` match only the lines it returns. | They read the file. | | [`first_lines`, `last_lines`](/home/integration/lines) | `head` and `tail` do not read the file. | They read the file. | | [`line_count`](/home/integration/lines) | `wc -l` reads nothing. | `wc -l` reads the file. | | [`follow`](/home/integration/lines) | `tail -f` waits on it. | `tail -f` re-reads the file every second. | | [`checksum`](/home/integration/checksums) | `md5sum` and `sha256sum` read nothing. | They read the file and hash it. | | [`read_tree`](/home/integration/walks) | `find`, `du`, `ls -R` and `tree` call it once. | They list each folder. | ### Attributes | Attribute | Does | | - | - | | `name` | Names the VFS. | | `vfs_md` | The mount's layout and file formats in its VFS.md, in Markdown: a `text` tree, then notes. Leave it empty for plain files. `{prefix}` becomes the mount's folder. | | `whole_word_search` | `files_containing` answers only a whole-word search (`grep -w`, `rg -w`); VFS.md tells the agent so. | Set them as class attributes. `name` and `vfs_md` can also be passed to `super().__init__()` (`super({...})` in TypeScript, with `vfsMd`). To replace a built-in VFS's description, set `vfs_md` on it (`vfsMd` in TypeScript). ## Example: a read-only VFS This VFS serves pages from a dictionary: > [tab] Python > > ```python notes.py theme={null} > from mirage import BaseVFS, FileStat, FileType, PathSpec > > > class NotesVFS(BaseVFS): > def __init__(self, pages: dict[str, str]) -> None: > super().__init__(name="notes") > self.pages = pages > > def page(self, path: PathSpec) -> str: > if path.vfs_path not in self.pages: > raise FileNotFoundError(path.virtual) > return self.pages[path.vfs_path] > > async def readdir(self, path: PathSpec) -> list[FileStat]: > if path.vfs_path: > self.page(path) > raise NotADirectoryError(path.virtual) > return [FileStat(name=name, type=FileType.FILE) for name in self.pages] > > async def stat(self, path: PathSpec) -> FileStat: > if not path.vfs_path: > return FileStat(name="/", type=FileType.DIRECTORY) > self.page(path) > return FileStat(name=path.vfs_path, type=FileType.FILE) > > async def read(self, path: PathSpec) -> bytes: > return self.page(path).encode() > ``` > [tab] TypeScript > > ```typescript notes.ts theme={null} > import { BaseVFS, enoent, enotdir, FileStat, FileType, type PathSpec } from '@struktoai/mirage-node' > > export class NotesVFS extends BaseVFS { > readonly pages: Record > > constructor(config: { pages: Record }) { > super({ name: 'notes' }) > this.pages = config.pages > } > > page(path: PathSpec): string { > if (!Object.hasOwn(this.pages, path.vfsPath)) throw enoent(path) > return this.pages[path.vfsPath]! > } > > override async readdir(path: PathSpec): Promise { > if (path.vfsPath !== '') { > this.page(path) > throw enotdir(path) > } > return Object.keys(this.pages).map((name) => new FileStat({ name, type: FileType.FILE })) > } > > override async stat(path: PathSpec): Promise { > if (path.vfsPath === '') return new FileStat({ name: '/', type: FileType.DIRECTORY }) > this.page(path) > return new FileStat({ name: path.vfsPath, type: FileType.FILE }) > } > > override async read(path: PathSpec): Promise { > return new TextEncoder().encode(this.page(path)) > } > } > ``` Mount it like any other VFS: > [tab] Python > > ```python theme={null} > from mirage import Workspace > > from notes import NotesVFS > > ws = Workspace({"/notes": NotesVFS({"hello.txt": "hello mirage\n"})}) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { Workspace } from '@struktoai/mirage-node' > import { NotesVFS } from './notes.ts' > > const ws = new Workspace({ '/notes': new NotesVFS({ pages: { 'hello.txt': 'hello mirage\n' } }) }) > ``` > [tab] YAML > > ```yaml theme={null} > mounts: > /notes: > vfs: ./notes.py:NotesVFS > config: > pages: > hello.txt: "hello mirage\n" > ``` `cat /notes/hello.txt` then prints `hello mirage`, and `grep -rn mirage /notes` reads every page. In YAML, `vfs` names the class as `file:Class`, relative to the YAML file, and `config` is what its constructor gets; the TypeScript server takes `./notes.ts:NotesVFS`. To name it `vfs: notes` instead, register it with `register_vfs` in Python or `registerVfs` in TypeScript. ## Example: make it writable Override `write` and `unlink`: > [tab] Python > > ```python theme={null} > from mirage import PathSpec > from mirage.io.types import ByteSource, materialize > > from notes import NotesVFS > > > class WritableNotesVFS(NotesVFS): > async def write(self, path: PathSpec, data: ByteSource) -> None: > self.pages[path.vfs_path] = (await materialize(data)).decode() > > async def unlink(self, path: PathSpec) -> None: > del self.pages[path.vfs_path] > ``` > [tab] TypeScript > > ```typescript theme={null} > import type { PathSpec } from '@struktoai/mirage-node' > import { type ByteSource, materialize } from '@struktoai/mirage-core/io/types' > import { NotesVFS } from './notes.ts' > > export class WritableNotesVFS extends NotesVFS { > override async write(path: PathSpec, data: ByteSource): Promise { > this.pages[path.vfsPath] = new TextDecoder().decode(await materialize(data)) > } > > override async unlink(path: PathSpec): Promise { > delete this.pages[path.vfsPath] > } > } > ``` On a writable mount, `echo hi > /notes/new.txt`, `sed -i` and `rm` now work, and `>>` reads the page and writes it back. `mv` still answers `Operation not supported` until you override `rename`. ## Example: let grep use your search Override `files_containing` to name the files that may contain the text (the TypeScript sample needs `pnpm add @struktoai/mirage-core`): > [tab] Python > > ```python theme={null} > from mirage import PathSpec > from mirage.utils.key_prefix import mounted_path > > from notes import NotesVFS > > > class SearchableNotesVFS(NotesVFS): > async def files_containing( > self, path: PathSpec, text: str, *, whole_word: bool, ignore_case: bool > ) -> list[PathSpec] | None: > if ignore_case: > return None > return [ > mounted_path(path, "/" + name) > for name, page in self.pages.items() > if text in page > ] > ``` > [tab] TypeScript > > ```typescript theme={null} > import type { PathSpec } from '@struktoai/mirage-node' > import { mountedPath } from '@struktoai/mirage-core/utils/key_prefix' > import { NotesVFS } from './notes.ts' > > export class SearchableNotesVFS extends NotesVFS { > override async filesContaining( > path: PathSpec, > text: string, > opts: { wholeWord: boolean; ignoreCase: boolean }, > ): Promise { > if (opts.ignoreCase) return null > return Object.entries(this.pages) > .filter(([, page]) => page.includes(text)) > .map(([name]) => mountedPath(path, `/${name}`)) > } > } > ``` `grep -rn mirage /notes` now reads only the pages this returns, and Mirage still checks each line, so the output is the same. The dictionary stands in for your service's search API. `mounted_path` turns a name inside the mount into a path. `grep -ri` gets `None` here, so it reads every page. For a real one, see [Chroma](/python/vfs/chroma#exact-search-with-grep), the search behind a RAG knowledge base: its `files_containing` asks Chroma for the chunks whose text contains the word (`$contains`) and returns their pages, and it also returns `None` for `-i`. Source: [Python](https://github.com/strukto-ai/mirage/blob/main/python/mirage/core/chroma/search.py), [TypeScript](https://github.com/strukto-ai/mirage/blob/main/typescript/packages/core/src/core/chroma/search.ts). ## Example: count lines without reading Override `line_count`: > [tab] Python > > ```python theme={null} > from mirage import PathSpec > > from notes import NotesVFS > > > class CountedNotesVFS(NotesVFS): > async def line_count(self, path: PathSpec) -> int | None: > return self.page(path).count("\n") > ``` > [tab] TypeScript > > ```typescript theme={null} > import type { PathSpec } from '@struktoai/mirage-node' > import { NotesVFS } from './notes.ts' > > export class CountedNotesVFS extends NotesVFS { > override async lineCount(path: PathSpec): Promise { > return this.page(path).split('\n').length - 1 > } > } > ``` `wc -l /notes/hello.txt` now returns without reading the page. For a database, this is where a `count(*)` query goes. Plain `wc` still reads the page, since it also counts words and bytes. ## Next The [Python](/python/vfs/new) and [TypeScript](/typescript/vfs/new) guides add folders, snapshots, packaging and contributing a VFS to Mirage. # Databricks Volume Source: https://docs.mirage.strukto.ai/home/setup/databricks Set up Databricks credentials for the Unity Catalog volume VFS. ## Credentials The VFS accesses a Unity Catalog volume through the Databricks Files REST API. Both Python and TypeScript require an explicit workspace host and token. The token can be a personal access token, an OAuth access token, or a callback that supplies the current access token. No extra Python package is required. Obtain a workspace access token. For local testing, you can create a personal access token under **Settings → Developer → Access tokens**. Scoped tokens need the [`files` API scope](https://docs.databricks.com/api/files/v2/file). ### Set the workspace host Use your workspace origin, such as `https://dbc-xxxxxxxx-xxxx.cloud.databricks.com` on AWS or `https://adb-xxxxxxxxxxxx.xx.azuredatabricks.net` on Azure. The host accepts HTTP or HTTPS and rejects a path, query, fragment, or userinfo. A trailing slash is allowed. ### Find a readable volume Choose a volume in Catalog Explorer. Its `/Volumes////...` path supplies the three config fields. The principal needs `USE CATALOG`, `USE SCHEMA`, and `READ VOLUME`; a write mount also needs `WRITE VOLUME`. See [volume permissions](https://docs.databricks.com/aws/en/volumes/utility-commands). ### Supply a token Pass your token and host to the VFS configuration. For example, your application can read them from environment variables: ```bash theme={null} DATABRICKS_HOST=https://dbc-xxxxxxxx-xxxx.cloud.databricks.com DATABRICKS_TOKEN=dapi... ``` Mirage does not discover environment variables, SDK profiles, or default credentials. Your application can use an external SDK or credential broker to obtain a token, then pass the token or a callback to Mirage. A callback owns refresh, caching, and coordination between concurrent requests. Mirage does not retry an unauthorized request with another credential source. Keep each VFS and workspace bound to one principal and permission scope. Isolate file caches, indexes, and external cache prefixes across identities. If the principal or permission scope changes, rebuild the workspace or invalidate its caches. Token refresh for the same principal and scope can use the existing VFS. See the [Python Databricks Volume VFS](/python/vfs/databricks_volume) or [TypeScript Databricks Volume VFS](/typescript/setup/databricks_volume) page for configuration and first-read examples. # Dify Source: https://docs.mirage.strukto.ai/home/setup/dify Set up a Dify Knowledge API key and dataset for the Dify VFS. ## Credentials Mirage uses the Dify Knowledge Base API. You need a dataset API key and the dataset ID for the knowledge base you want to mount. ### 1. Get a Knowledge API Key 1. Open your Dify workspace. 2. Go to the target knowledge base. 3. Open **API Access** or the dataset API settings. 4. Create or copy an API key with permission to read documents, segments, and retrieval results. The key is sent as a bearer token to the Dify API. ### 2. Find the Dataset ID Use the dataset ID from the knowledge base URL or Dify API settings. The ID is used in API paths such as: ```text theme={null} /datasets//documents ``` ### 3. Set Environment Variables ```bash theme={null} # .env.development DIFY_API_KEY=dataset-... DIFY_BASE_URL=https://api.dify.ai/v1 DIFY_DATASET_ID=... DIFY_SLUG_METADATA_NAME=slug ``` For self-hosted Dify, set `DIFY_BASE_URL` to your API base URL, for example: ```bash theme={null} DIFY_BASE_URL=https://dify.example.com/v1 ``` ## Document Metadata Mirage can mount a Dify dataset without custom metadata, but scoped search works best when every document has a stable slug metadata field. Mirage looks for a field named `slug` by default; Python users can change that field name with `DifyConfig(slug_metadata_name="...")`. ### Recommended: Add a Slug Metadata Field Create a metadata field on the Dify knowledge dataset and use the value as the virtual path below the Mirage mount. The default field name is `slug`. | Dify document | `slug` metadata value | Mirage path | | - | - | - | | Quickstart | `guides/quickstart.md` | `/knowledge/guides/quickstart.md` | | Support Policy | `policies/support.md` | `/knowledge/policies/support.md` | If your Dify metadata field is named `path`, set `slug_metadata_name="path"` in the Dify VFS config and use `name: path` in Dify metadata. Guidelines: * Use forward slashes to create folders. * Do not start with `/`; Mirage normalizes leading and trailing slashes. * Do not use empty segments, `.`, or `..`. * Keep values unique. Two documents with the same slug metadata value will raise a duplicate path error. * Avoid making one document's slug metadata value a parent of another document's slug metadata value. For example, do not use both `guides` and `guides/quickstart.md`; Mirage treats that as a path collision. ### Add or Update Slug Metadata in Dify In Dify's Knowledge UI, open each document and edit its metadata. Add a custom metadata item: ```text theme={null} name: slug value: guides/quickstart.md ``` If you upload or sync documents programmatically, include the same metadata on the document. Mirage reads Dify's `doc_metadata` field and looks for an item whose `name` matches `slug_metadata_name`. ### Enable Built-in Fields for Name-Based Documents If a document does not have the configured slug metadata field, Mirage falls back to the Dify document name for its file path. Scoped `search` can still target those name-based documents, but Dify must expose the `document_name` built-in field for metadata filtering. In the Dify knowledge dataset settings: 1. Open the dataset metadata settings. 2. Enable **Built-in Fields**. 3. Ensure `document_name` is available for metadata filtering. Without Built-in Fields, commands like `ls`, `find`, `cat`, and `grep` still work because Mirage resolves files through the document list and segment APIs. Scoped `search` against name-based paths may return no records because Dify cannot filter retrieval by `document_name`. For the most predictable behavior, add the configured slug metadata field to every document and use slug-based paths. For SDK configuration, see the [Dify (Python)](/python/vfs/dify) and [Dify (TypeScript)](/typescript/setup/dify) guides. # DigitalOcean Spaces Source: https://docs.mirage.strukto.ai/home/setup/digitalocean Set up DigitalOcean Spaces credentials for the DigitalOcean VFS. ## Credentials ### 1. Create a Spaces access key 1. Sign in to the [DigitalOcean console](https://cloud.digitalocean.com/) 2. Go to **API** -> **Spaces Keys** -> **Generate New Key** 3. Copy the **Access Key** and **Secret** 4. Note your Space's **region** (e.g. `nyc3`) and **Space name** (the bucket) The endpoint is derived from `region` as `.digitaloceanspaces.com`. ### 2. Set environment variables ```bash theme={null} # .env.development DO_SPACE=my-space DO_REGION=nyc3 DO_ACCESS_KEY_ID=... DO_SECRET_ACCESS_KEY=... ``` For SDK guides, see [DigitalOcean Spaces (Python)](/python/vfs/digitalocean) and [DigitalOcean Spaces (TypeScript)](/typescript/setup/digitalocean). # Discord Source: https://docs.mirage.strukto.ai/home/setup/discord Set up a Discord Bot Token for the Discord VFS. ## Credentials ### 1. Create a Discord Application 1. Go to [https://discord.com/developers/applications](https://discord.com/developers/applications) 2. **New Application** -> name it (e.g., "Mirage") ### 2. Create a Bot 1. **Bot** in the left sidebar 2. **Reset Token** -> copy the **Bot Token** 3. Under **Privileged Gateway Intents**, enable: * **Message Content Intent** (required to read message content) * **Server Members Intent** for the VFS `members/` directory or the CLI `discord members` command without `--query` ### 3. Invite the Bot to Your Server 1. **OAuth2** -> **URL Generator** in the left sidebar 2. Select scopes: `bot` 3. Select bot permissions: `Read Messages/View Channels`, `Read Message History`; add `Send Messages` for the CLI's writes and `Attach Files` for `send --file` 4. Copy the generated URL and open it in a browser to invite ### 4. Set Environment Variables ```bash theme={null} # .env.development DISCORD_BOT_TOKEN=MTIx... ``` For SDK guides, see [Discord (Python)](/python/vfs/discord) and [Discord (TypeScript)](/typescript/setup/discord). # Disk Source: https://docs.mirage.strukto.ai/home/setup/disk Make a directory on your host available as workspace files. Disk mounts a host directory at a workspace path. Available in Python and Node; for browser storage, use [OPFS](/home/setup/opfs). ## Configuration Replace `root` with the directory you want to access: ```yaml theme={null} mounts: /data: vfs: disk mode: read config: root: /path/to/files ``` `ls /data` lists that directory. Set `mode: write` to allow changes to its files through Mirage. Add `capacity: 1GB` under `config` to cap the bytes the directory holds; see [capacity](/home/configuration#capacity). A second disk mount whose `root` resolves to a folder already mounted is refused; a folder inside one is fine. ## SDK guides * [Python Disk VFS](/python/vfs/disk) * [TypeScript Disk setup](/typescript/setup/disk) # Dropbox Source: https://docs.mirage.strukto.ai/home/setup/dropbox Set up Dropbox OAuth2 credentials and obtain a long-lived refresh token. ## Overview The Dropbox VFS uses OAuth2 with a long-lived refresh token to authenticate against the [Dropbox v2 HTTP API](https://www.dropbox.com/developers/documentation/http/documentation): * **`/2/files/list_folder`**, list folder entries * **`/2/files/download`**, download file bytes * **`/2/files/search_v2`**, search files by name/content * **`/2/files/get_metadata`**, fetch entry metadata Two flows are supported: * **Code flow with client secret**, for Node/server. Needs `client_id`, `client_secret`, `refresh_token`. * **PKCE flow**, for browsers. Needs only `client_id` and `refresh_token` (no secret in the bundle). Both produce the same long-lived refresh token; the VFS auto-refreshes short-lived access tokens (≈4h) behind the scenes. ## Setup ### 1. Create a Dropbox App 1. Go to [https://www.dropbox.com/developers/apps](https://www.dropbox.com/developers/apps) 2. Click **Create app** 3. Choose: * API: **Scoped access** * Access type: **App folder** (sandboxed to one folder Dropbox creates for you) or **Full Dropbox** (your entire account). Pick App folder for least privilege. * Name it (e.g., "Mirage") -> **Create app** ### 2. Configure Permissions On the app's settings page, click the **Permissions** tab and check: * `files.metadata.read`, list folders, read file metadata * `files.content.read`, download file bytes For a write mount, also check `files.content.write`. Mirage uses it for uploads, overwrites, creates, deletes, moves and copies. Click **Submit** at the bottom of the Permissions tab. **Required**: Dropbox does not include unchecked scopes in tokens, even if the auth URL requests them. ### 3. Configure OAuth 2 Redirect URI On the **Settings** tab, scroll to **OAuth 2 -> Redirect URIs** and add: * For the CLI flow below: `http://localhost:1` * For the browser PKCE example: `http://localhost:5173/vfs/dropbox/dropbox_pkce.html` Click **Add** after each. ### 4. Copy the App Key (and Secret) Still on **Settings**, copy: * **App key**, this is your `DROPBOX_APP_KEY` * **App secret**, click **Show** -> copy. This is your `DROPBOX_APP_SECRET`. **Skip if you only need the PKCE flow.** ### 5. Get the Refresh Token (CLI flow with client secret) This mirrors the Google flow, easiest path for Node/server use. **A) Open this URL in a browser** (replace `YOUR_APP_KEY`): ``` https://www.dropbox.com/oauth2/authorize?client_id=YOUR_APP_KEY&response_type=code&token_access_type=offline&redirect_uri=http://localhost:1 ``` * `token_access_type=offline`, **required** to receive a refresh token. Without this you only get a short-lived access token. **B) Authorize:** sign in -> click **Allow**. **C) Copy the code:** the browser redirects to `http://localhost:1?code=ABC...` (the page won't load, expected). Copy the `code` value from the URL bar. **D) Exchange the code for a refresh token:** ```bash theme={null} curl https://api.dropboxapi.com/oauth2/token \ -d "code=THE_CODE_FROM_STEP_C" \ -d "grant_type=authorization_code" \ -d "client_id=YOUR_APP_KEY" \ -d "client_secret=YOUR_APP_SECRET" \ -d "redirect_uri=http://localhost:1" ``` The response contains `refresh_token`, save it. Example: ```json theme={null} { "access_token": "sl.B...", "expires_in": 14400, "refresh_token": "abc123...", "scope": "files.metadata.read files.content.read", "token_type": "bearer", "uid": "12345", "account_id": "dbid:..." } ``` ### 6. Set Environment Variables ```bash theme={null} # .env.development DROPBOX_APP_KEY=abc123app4key DROPBOX_APP_SECRET=def456app4secret DROPBOX_REFRESH_TOKEN=ghi789refresh4token ``` ## Alternative: PKCE Flow (browser, no client secret) If you're mounting Dropbox from a browser SPA and don't want to ship a client secret, use the PKCE flow. The bundled example does the dance end-to-end. 1. In the Dropbox app **Settings** tab, ensure the redirect URI `http://localhost:5173/vfs/dropbox/dropbox_pkce.html` is registered (Step 3). 2. Set only `DROPBOX_APP_KEY` in `.env.development` at the repo root (no secret needed). 3. From `examples/browser/`, run `pnpm dev`. 4. Open `http://localhost:5173/vfs/dropbox/dropbox_pkce.html` and click **Connect Dropbox**. The example persists the refresh token to `localStorage`, then mounts a `DropboxVFS` with just `{ clientId, refreshToken }` and runs `ls /dropbox/`. Inspect DevTools -> Network -> filter `token` to confirm refresh calls don't include `client_secret`. The same `refresh_token` can be reused for headless setups, copy it out of `localStorage` and set it as `DROPBOX_REFRESH_TOKEN` in your env. ## Token Lifetime | Token | Lifetime | | - | - | | Access token | \~4 hours (`expires_in: 14400`) | | Refresh token | Long-lived; survives until manually revoked | Refresh tokens get revoked if: * The user revokes the app at [https://www.dropbox.com/account/connected\_apps](https://www.dropbox.com/account/connected_apps) * The Dropbox account password is changed * The app is deleted in the developer console The `DropboxTokenManager` in the VFS transparently exchanges the refresh token for a fresh access token whenever the cached one is within 5 minutes of expiry. ## Scopes Reference | Scope | Purpose | | - | - | | `files.metadata.read` | List folders, read file metadata | | `files.content.read` | Download file bytes | | `files.content.write` | Upload, overwrite, create, delete, move and copy | | `account_info.read` | Account space usage, for `df` (optional) | ## Troubleshooting | Issue | Fix | | - | - | | `400 invalid_grant` on token exchange | The `code` is single-use and expires fast, re-do Step 5A with a fresh URL | | No `refresh_token` in token response | Add `token_access_type=offline` to the auth URL | | `path/not_found/.` on `ls /dropbox/` | Account is empty, or app is **App folder** scoped and the sandbox folder hasn't been created | | `missing_scope` on download | Check `files.content.read` is enabled in the **Permissions** tab and **submitted** | | Browser PKCE: redirect URI mismatch | Dropbox is strict, `http://localhost:5173/vfs/dropbox/dropbox_pkce.html` must match exactly (no trailing slash) | | Token works locally but fails after a while | Access token expired, the `TokenManager` should auto-refresh; if not, refresh token may be revoked | For TypeScript usage, mount with: ```ts theme={null} import { DropboxVFS } from '@struktoai/mirage-node' const dropbox = new DropboxVFS({ clientId: process.env.DROPBOX_APP_KEY!, clientSecret: process.env.DROPBOX_APP_SECRET!, refreshToken: process.env.DROPBOX_REFRESH_TOKEN!, }) ``` Or browser (PKCE): ```ts theme={null} import { DropboxVFS } from '@struktoai/mirage-browser' const dropbox = new DropboxVFS({ clientId: 'YOUR_APP_KEY', refreshToken: refreshTokenFromLocalStorage, }) ``` # Email Source: https://docs.mirage.strukto.ai/home/setup/email Set up IMAP/SMTP credentials for the Email VFS. ## Credentials The Email VFS connects to password-authenticated IMAP (reading) and SMTP (sending) servers. You need the server hostnames and a password or app password accepted by that provider. > [!WARNING] > > Microsoft 365 is unsupported because it requires OAuth for IMAP, while the > current Email VFS accepts only passwords. ### 1. Find Your IMAP/SMTP Settings | Provider | IMAP Host | IMAP Port | SMTP Host | SMTP Port | | - | - | - | - | - | | Yahoo | `imap.mail.yahoo.com` | 993 | `smtp.mail.yahoo.com` | 587 | | Fastmail | `imap.fastmail.com` | 993 | `smtp.fastmail.com` | 587 | | iCloud | `imap.mail.me.com` | 993 | `smtp.mail.me.com` | 587 | | ProtonMail | `127.0.0.1` | 1143 | `127.0.0.1` | 1025 | | Self-hosted | Your server hostname | 993 | Your server hostname | 587 | ProtonMail requires [ProtonMail Bridge](https://proton.me/mail/bridge) running locally. ### 2. Create an App Password Many providers require an **app password** instead of your regular account password. Check that your provider still supports password-authenticated IMAP and SMTP before creating one. **Yahoo:** 1. Go to [https://login.yahoo.com/account/security](https://login.yahoo.com/account/security) 2. **Generate app password** 3. Select **Other App**, name it (e.g., "Mirage") 4. Copy the generated password **Fastmail:** 1. Go to [https://www.fastmail.com/settings/security/tokens](https://www.fastmail.com/settings/security/tokens) 2. **New App Password** 3. Select **IMAP/SMTP** access 4. Copy the generated password **iCloud:** 1. Go to [https://appleid.apple.com/account/manage](https://appleid.apple.com/account/manage) 2. **Sign-In and Security** -> **App-Specific Passwords** 3. **Generate an app-specific password** 4. Copy the generated password **Self-hosted / Other:** Use your regular email password, or whatever your mail server requires. ### 3. Save the credentials ```bash theme={null} # .env.development IMAP_HOST=imap.fastmail.com SMTP_HOST=smtp.fastmail.com EMAIL_USERNAME=you@fastmail.com EMAIL_PASSWORD=your-app-password ``` ## Troubleshooting **"Authentication failed"** - Check whether your provider accepts passwords for IMAP/SMTP and whether it requires an app password. **"Connection refused"** - Check the hostname and port. Some networks block port 993/587. For ProtonMail, make sure Bridge is running. **"SSL handshake failed"** - Verify the host and implicit-TLS port (commonly 993 for IMAP). The current Python adapter's `use_ssl=False` setting opens a plain connection; it does not perform a STARTTLS upgrade. For SDK guides, see [Email (Python)](/python/vfs/email) and [Email (TypeScript)](/typescript/setup/email). # Overview Source: https://docs.mirage.strukto.ai/home/setup/fuse Expose a VFS as a folder on the machine running Mirage. A FUSE mount shows a VFS as a folder on the machine running Mirage, so editors, language servers and scripts use it like any other folder, even when the data lives in S3 or another service. Mount from your [Python](/python/setup/fuse) or [TypeScript](/typescript/setup/fuse) app, or through the CLI. To mount a workspace from another machine, use [SSHFS](/home/access/ssh#connect). ## Support | OS | Python | TypeScript (Node) | Setup | | - | - | - | - | | Linux | Supported | Supported | [Linux](/home/setup/linux) | | macOS | Supported, one mount per process | Supported, one mount per process | [macOS](/home/setup/macos) | | Windows | Experimental | Not supported | [Windows](/home/setup/windows) | A browser cannot mount a folder; use Mirage's shell and file APIs there. | | Linux | macOS | Windows | | - | - | - | - | | Unmount | `fusermount3 -u` or closing the workspace | `diskutil unmount` or closing the workspace | When the process exits | | A file whose size is unknown | Reads in full | Reads in full | Size fetched when opened | | Mountpoint folder | Created if missing | Created if missing | Must not exist; created for you | ## Set up **1. Install FUSE for your OS** Follow the [Linux](/home/setup/linux), [macOS](/home/setup/macos) or [Windows](/home/setup/windows) guide. **2. Install your SDK's FUSE binding** Follow the [Python](/python/setup/fuse#install-mirage-with-the-fuse-extra) or [TypeScript](/typescript/setup/fuse) guide. ## Try it with the CLI Set `backend: fuse` and a local folder on a mount: ```yaml workspace.yaml theme={null} mounts: /data: vfs: ram mode: write backend: fuse mountpoint: /tmp/mirage-data ``` Write a file through Mirage, then read it from the folder: ```bash theme={null} mkdir -p /tmp/mirage-data mirage workspace create workspace.yaml --id demo mirage shell -w demo -c 'echo "hello mirage" > /data/hello.txt' cat /tmp/mirage-data/hello.txt ``` This prints `hello mirage`. `mirage workspace delete demo` unmounts the folder. * Replace RAM with any [supported VFS](/home/setup/vfs) to expose your own data. * The folder follows the mount's mode: a `read` mount cannot be written. * A mount set up this way is not tied to an agent session or profile. # Google Calendar Source: https://docs.mirage.strukto.ai/home/setup/gcal Virtualize Google Calendar calendars and events as JSON files. The Google Calendar VFS mounts every calendar the account can see as a directory of date buckets, with one JSON file per event. It uses the same OAuth credentials as the other Google mounts; enable the Google Calendar API and its scope as described in [Google Workspace Setup](/home/setup/google). For SDK guides, see [Google Calendar (Python)](/python/vfs/gcal) and [Google Calendar (TypeScript)](/typescript/setup/gcal). ## Connect > [tab] Python > > ```python theme={null} > import asyncio > import os > > from mirage import MountMode, Workspace > from mirage.vfs.gcal import GCalConfig, GCalVFS > > > async def main() -> None: > config = GCalConfig( > client_id=os.environ["GOOGLE_CLIENT_ID"], > client_secret=os.environ["GOOGLE_CLIENT_SECRET"], > refresh_token=os.environ["GOOGLE_REFRESH_TOKEN"], > ) > ws = Workspace({"/gcal": GCalVFS(config)}, mode=MountMode.READ) > result = await ws.shell("ls /gcal/primary") > print(await result.stdout_str(), end="") > await ws.close() > > > asyncio.run(main()) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { GCalVFS, MountMode, Workspace } from '@struktoai/mirage-node' > > const ws = new Workspace({ > '/gcal': new GCalVFS({ > clientId: process.env.GOOGLE_CLIENT_ID!, > clientSecret: process.env.GOOGLE_CLIENT_SECRET!, > refreshToken: process.env.GOOGLE_REFRESH_TOKEN!, > }), > }, { mode: MountMode.READ }) > const result = await ws.shell('ls /gcal/primary') > process.stdout.write(result.stdoutText) > await ws.close() > ``` > [tab] YAML > > ```yaml theme={null} > mounts: > /gcal: > vfs: gcal > mode: read > config: > client_id: ${GOOGLE_CLIENT_ID} > client_secret: ${GOOGLE_CLIENT_SECRET} > refresh_token: ${GOOGLE_REFRESH_TOKEN} > ``` ## Browse events ```text theme={null} /gcal/ primary/ calendar.json / ___.gcal.json <name>__<calendar-id>/ ... ``` The primary calendar is always `primary`; every other calendar directory ends in `__<calendar-id>`. Each date directory holds the events of one day by default; set `bucket_days` to `7` or `30` for 7-day or 30-day buckets. Without `start_time` or `end_time`, a calendar lists all of its history up to 90 days after today. Use `ls` and date globs such as `ls /gcal/primary/2026-11-*` to find events, then `cat` or `jq` to read the Calendar API payload. On a mount in write mode, `rm` an event file to delete that event for every attendee; that needs the `owner` or `writer` role on its calendar. Create and edit events with the [`gws calendar`](/home/setup/cli/gws) CLI. # Google Cloud Storage Source: https://docs.mirage.strukto.ai/home/setup/gcs Set up Google Cloud Storage credentials for the GCS VFS. ## Credentials ### 1. Create HMAC Keys 1. Go to [https://console.cloud.google.com/storage/settings](https://console.cloud.google.com/storage/settings) -> **Interoperability** 2. Under **Service account HMAC**, click **Create a key for a service account** 3. Select a service account with Storage Object Viewer (read) or Storage Object Admin (read/write) 4. Copy the **Access key** and **Secret** ### 2. Set Environment Variables ```bash theme={null} # .env.development GCS_BUCKET=mirage-ai GCS_ACCESS_KEY_ID=GOOG... GCS_SECRET_ACCESS_KEY=... ``` For SDK guides, see [Google Cloud Storage (Python)](/python/vfs/gcs) and [Google Cloud Storage (TypeScript)](/typescript/setup/gcs). # GitHub Source: https://docs.mirage.strukto.ai/home/setup/github Set up a GitHub Personal Access Token for the GitHub VFS. ## Credentials ### 1. Create a Personal Access Token 1. Go to [https://github.com/settings/tokens](https://github.com/settings/tokens) 2. **Generate new token (classic)** or **Fine-grained token** 3. For classic tokens, select scopes: * `repo` for private repositories. This broad scope includes write access; prefer a fine-grained token when you need tighter permissions. 4. For fine-grained tokens: * **Repository access**: select the repos you need * **Permissions**: Contents -> Read-only 5. Copy the token ### 2. Set Environment Variables ```bash theme={null} # .env.development GITHUB_TOKEN=ghp_xxxx... ``` For SDK guides, see [GitHub (Python)](/python/vfs/github) and [GitHub (TypeScript)](/typescript/setup/github). # Google Workspace Source: https://docs.mirage.strukto.ai/home/setup/google Set up Google OAuth2 credentials for Google mounts and the GWS CLI. ## Overview Google mounts and the `gws` CLI accept an access token or OAuth refresh credentials. The steps below obtain refresh credentials for the services you enable. ## Setup ### 1. Create a Google Cloud Project 1. Go to [https://console.cloud.google.com/](https://console.cloud.google.com/) 2. Click the project selector dropdown -> **New Project** 3. Name it (e.g., "Mirage") -> **Create** 4. Select it from the dropdown ### 2. Enable APIs 1. Go to [https://console.cloud.google.com/apis/library](https://console.cloud.google.com/apis/library) Enable the API for each service you plan to use: | Service | API to enable | Scope for Mirage's read/write commands | | - | - | - | | Drive | Google Drive API | `https://www.googleapis.com/auth/drive` | | Docs | Google Docs API | `https://www.googleapis.com/auth/documents` | | Sheets | Google Sheets API | `https://www.googleapis.com/auth/spreadsheets` | | Slides | Google Slides API | `https://www.googleapis.com/auth/presentations` | | Gmail | Gmail API | `https://www.googleapis.com/auth/gmail.modify` | | Calendar | Google Calendar API | `https://www.googleapis.com/auth/calendar` | Keep the Drive API and scope when using Google file mounts. The `gws` create commands also need Drive when placing new files inside a configured folder. For read-only use, select the corresponding read-only scopes. ### 3. Configure Google Auth Platform The OAuth settings are under **Google Auth Platform** in the Cloud Console left sidebar (or go to [https://console.cloud.google.com/auth/overview](https://console.cloud.google.com/auth/overview)). **A) Branding** (left sidebar): 1. Fill in: App name (e.g., "Mirage"), support email, developer contact email 2. Save **B) Audience** (left sidebar): 1. Set user type to **External** 2. Add your own Google email as a **test user** 3. Save **C) Data Access** (left sidebar) - this is where scopes are configured: 1. Click **Add or Remove Scopes** 2. Add the scopes for the services you enabled in [Step 2](#2-enable-apis). 3. Select them -> Save ### 4. Create OAuth2 Client 1. Go to **Clients** in the left sidebar (or click **Create OAuth client** on the Overview page) 2. Application type: **Desktop app** 3. Name it -> **Create** 4. Copy the **Client ID** and **Client Secret** ### 5. Get the Refresh Token **A) Build and open the authorization URL.** Replace `YOUR_CLIENT_ID` and add the scopes selected above to `scope`. This example requests Drive and Docs: ``` https://accounts.google.com/o/oauth2/v2/auth?client_id=YOUR_CLIENT_ID&redirect_uri=http://localhost:1&response_type=code&scope=https://www.googleapis.com/auth/drive%20https://www.googleapis.com/auth/documents&access_type=offline&prompt=consent ``` * `access_type=offline` - required to receive a refresh token * `prompt=consent` - forces refresh token issuance on re-auth **B) Authorize:** Sign in -> click through "unverified app" warning -> grant permissions. **C) Copy the code:** The browser redirects to `http://localhost:1?code=4/0AXXXX...` (page won't load - expected). Copy the `code` value from the URL bar. **D) Exchange for tokens:** ```bash theme={null} curl -X POST https://oauth2.googleapis.com/token \ -d "client_id=YOUR_CLIENT_ID" \ -d "client_secret=YOUR_CLIENT_SECRET" \ -d "code=THE_CODE_FROM_STEP_C" \ -d "grant_type=authorization_code" \ -d "redirect_uri=http://localhost:1" ``` The response JSON contains `refresh_token` - save it. ### 6. Save the credentials ```bash theme={null} # .env.development GOOGLE_CLIENT_ID=123456789-abc.apps.googleusercontent.com GOOGLE_CLIENT_SECRET=GOCSPx-xxx GOOGLE_REFRESH_TOKEN=1//0abc... ``` ## Token Lifetime | App Publishing Status | Typical behavior | | - | - | | Testing (default) | External-user grants expire after 7 days unless only basic profile scopes are requested | | In production | Long-lived while the grant remains valid | You can complete setup in Testing mode. To publish, go to **Audience** and click **Publish App**. The `TokenManager` exchanges a valid refresh token for short-lived access tokens automatically. Refresh tokens can still be revoked or expire; repeat authorization when that happens. See [Google's token lifecycle documentation](https://developers.google.com/identity/protocols/oauth2#expiration). ## Troubleshooting | Issue | Fix | | - | - | | 403 during OAuth flow | Add yourself as a test user under **Audience** | | No `refresh_token` in response | Ensure `access_type=offline` and `prompt=consent` in the auth URL | | Token exchange fails | `redirect_uri` must exactly match between auth URL and curl | | Refresh token expires after 7 days | Publish the app under **Audience**, or re-authorize while testing | | Auth code doesn't work twice | Codes are single-use - re-authorize if exchange fails | For Python configuration, see [Gmail](/python/vfs/gmail), [Drive](/python/vfs/gdrive), [Docs](/python/vfs/gdocs), [Sheets](/python/vfs/gsheets), [Slides](/python/vfs/gslides), and [Calendar](/python/vfs/gcal). For TypeScript configuration, see [Gmail](/typescript/setup/gmail), [Drive](/typescript/setup/gdrive), [Docs](/typescript/setup/gdocs), [Sheets](/typescript/setup/gsheets), [Slides](/typescript/setup/gslides), and [Calendar](/typescript/setup/gcal). For Forms and service command trees, see [GWS setup](/home/setup/cli/gws). # GridFS Source: https://docs.mirage.strukto.ai/home/setup/gridfs Set up a MongoDB connection for the GridFS file-storage VFS. GridFS stores files inside MongoDB (metadata in `fs.files`, content chunks in `fs.chunks`). The GridFS VFS only needs a MongoDB connection URI plus a database name; the connection is set up exactly like the [MongoDB VFS](/home/setup/mongodb). ## Credentials ### 1. Get Your Connection URI #### Local MongoDB ```bash theme={null} # Default local instance MONGODB_URI=mongodb://localhost:27017 ``` #### MongoDB Atlas (Cloud) 1. Go to [https://cloud.mongodb.com](https://cloud.mongodb.com) 2. Select your cluster -> **Connect** -> **Drivers** 3. Copy the connection string: ``` mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/ ``` #### Self-hosted with Authentication ```bash theme={null} MONGODB_URI=mongodb://username:password@host:27017/?authSource=admin ``` ### 2. Set Environment Variables ```bash theme={null} # .env.development MONGODB_URI=mongodb+srv://user:pass@cluster0.xxxxx.mongodb.net/ ``` For usage, see the [Python GridFS VFS](/python/vfs/gridfs) or the [TypeScript GridFS setup](/typescript/setup/gridfs). # HF Buckets Source: https://docs.mirage.strukto.ai/home/setup/hf_buckets Set up Hugging Face Buckets credentials for the HF Buckets VFS. ## Credentials ### 1. Create a Bucket 1. Go to [https://huggingface.co/new-bucket](https://huggingface.co/new-bucket) and create a bucket 2. Note the full name in `namespace/bucket-name` form (e.g. `your-user/my-data`) ### 2. Create an Access Token 1. Go to [https://huggingface.co/settings/tokens](https://huggingface.co/settings/tokens) 2. Create a fine-grained token with **Read** (or **Write** if you need to upload) access to the bucket's namespace ### 3. Set Environment Variables ```bash theme={null} # .env.development HF_BUCKET_NAME=your-user/my-data HF_TOKEN=hf_... ``` For SDK guides, see [HF Buckets (Python)](/python/vfs/hf_buckets) and [HF Buckets (TypeScript)](/typescript/setup/hf_buckets). # HF Datasets Source: https://docs.mirage.strukto.ai/home/setup/hf_datasets Set up Hugging Face Datasets credentials. ## Credentials ### 1. Pick a Dataset Repo Browse [huggingface.co/datasets](https://huggingface.co/datasets) and note the full `namespace/dataset-name` (e.g. `AlienKevin/SWE-ZERO-12M-trajectories`). Public datasets need no token. Gated/private datasets do. ### 2. Create an Access Token (gated/private only) 1. Go to [https://huggingface.co/settings/tokens](https://huggingface.co/settings/tokens) 2. Create a fine-grained token with **Read** access to the dataset ### 3. Set Environment Variables ```bash theme={null} # .env.development HF_DATASET_REPO=AlienKevin/SWE-ZERO-12M-trajectories HF_TOKEN=hf_... # optional, public datasets work without it ``` For SDK guides, see [HF Datasets (Python)](/python/vfs/hf_datasets) and [HF Datasets (TypeScript)](/typescript/setup/hf_datasets). # HF Models Source: https://docs.mirage.strukto.ai/home/setup/hf_models Set up Hugging Face Models credentials. ## Credentials ### 1. Pick a Model Repo Browse [huggingface.co/models](https://huggingface.co/models) and note the full `namespace/model-name` (e.g. `sapientinc/HRM-Text-1B`). Public models need no token. Gated/private models do. ### 2. Create an Access Token (gated/private only) 1. Go to [https://huggingface.co/settings/tokens](https://huggingface.co/settings/tokens) 2. Create a fine-grained token with **Read** access to the model ### 3. Set Environment Variables ```bash theme={null} # .env.development HF_MODEL_REPO=sapientinc/HRM-Text-1B HF_TOKEN=hf_... # optional, public models work without it ``` For SDK guides, see [HF Models (Python)](/python/vfs/hf_models) and [HF Models (TypeScript)](/typescript/setup/hf_models). # HF Spaces Source: https://docs.mirage.strukto.ai/home/setup/hf_spaces Set up Hugging Face Spaces credentials. ## Credentials ### 1. Pick a Space Repo Browse [huggingface.co/spaces](https://huggingface.co/spaces) and note the full `namespace/space-name` (e.g. `HuggingFaceBio/carbon-demo`). Public spaces need no token. Private spaces do. ### 2. Create an Access Token (private only) 1. Go to [https://huggingface.co/settings/tokens](https://huggingface.co/settings/tokens) 2. Create a fine-grained token with **Read** access to the space ### 3. Set Environment Variables ```bash theme={null} # .env.development HF_SPACE_REPO=HuggingFaceBio/carbon-demo HF_TOKEN=hf_... # optional, public spaces work without it ``` For SDK guides, see [HF Spaces (Python)](/python/vfs/hf_spaces) and [HF Spaces (TypeScript)](/typescript/setup/hf_spaces). # Jaeger Source: https://docs.mirage.strukto.ai/home/setup/jaeger Virtualize Jaeger services and traces as read-only JSON files. Connect to an existing Jaeger query service. Set `host` to its base URL, such as `http://localhost:16686`. For SDK guides, see [Jaeger (Python)](/python/vfs/jaeger) and [Jaeger (TypeScript)](/typescript/setup/jaeger). ## Connect > [tab] Python > > ```python theme={null} > import asyncio > > from mirage import Workspace > from mirage.vfs.jaeger import JaegerConfig, JaegerVFS > > > async def main() -> None: > ws = Workspace({ > "/jaeger": JaegerVFS(JaegerConfig(host="http://localhost:16686")), > }) > result = await ws.shell("ls /jaeger/services") > print(await result.stdout_str(), end="") > await ws.close() > > > asyncio.run(main()) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { JaegerVFS, Workspace } from '@struktoai/mirage-node' > > const ws = new Workspace({ > '/jaeger': new JaegerVFS({ host: 'http://localhost:16686' }), > }) > const result = await ws.shell('ls /jaeger/services') > process.stdout.write(result.stdoutText) > await ws.close() > ``` > [tab] YAML > > ```yaml theme={null} > mounts: > /jaeger: > vfs: jaeger > config: > host: http://localhost:16686 > ``` ## Browse traces Each service has an operations list and a directory of traces: ```text theme={null} /jaeger/services/<service>/ operations.json traces/ <trace-id>.json ``` Use `ls` to find services and traces, then `cat` or `jq` to read a trace. Files are read-only. Trace listings return up to 100 traces per service by default; set `default_trace_limit` in Python or YAML, or `defaultTraceLimit` in TypeScript, to change the limit. # LanceDB Source: https://docs.mirage.strukto.ai/home/setup/lancedb Set up a LanceDB connection for the LanceDB VFS. LanceDB mounts a table as a read-only filesystem: group-by columns become nested folders, each row is a card plus an optional blob file, and semantic search is the [`search` CLI](/home/setup/cli/search). ## Connection ### Local / embedded Point `uri` at a directory. LanceDB stores the table there, no server needed. ```bash theme={null} # .env.development LANCEDB_URI=/data/fashion.lancedb ``` ### Object storage `uri` also accepts `s3://`, `gs://`, and `az://` prefixes for tables backed by object storage. ### Cloud and Enterprise `db://` URIs connect to LanceDB Cloud (`api_key` + `region`) or Enterprise (`api_key` + `host_override`): ```bash theme={null} # .env.development LANCEDB_URI=db://my-database LANCEDB_API_KEY=sk_... LANCEDB_REGION=us-east-1 # Enterprise only LANCEDB_HOST_OVERRIDE=https://my-database.us-east-1.api.lancedb.com ``` ## Search Search is the [`search` CLI](/home/setup/cli/search)'s `search "<query>" <path>`. It returns ranked rows as their canonical `<id>.md` file paths plus a score, so results compose with `cat`, `wc`, and pipes (`grep`/`rg` stay lexical). It requires a table built with an embedding function on a source field, so `tbl.search(text)` auto-embeds the query. ## Limits The VFS is read-only and bounds how much an agent can pull: * `search_limit` (10): default top-k returned by `search`. * `max_rows` (1,000): hard ceiling on rows listed per folder. See the [Python](/python/vfs/lancedb) and [TypeScript](/typescript/setup/lancedb) VFS pages for full config. # Langfuse Source: https://docs.mirage.strukto.ai/home/setup/langfuse Set up Langfuse API keys for the Langfuse VFS. ## Credentials ### 1. Get API Keys #### Langfuse Cloud 1. Go to [https://cloud.langfuse.com](https://cloud.langfuse.com) 2. Select your project -> **Settings** -> **API Keys** 3. Copy the **Public Key** and **Secret Key** #### Self-hosted 1. Go to your Langfuse instance (e.g., `https://langfuse.yourcompany.com`) 2. Select your project -> **Settings** -> **API Keys** 3. Copy the **Public Key** and **Secret Key** The VFS reads the Langfuse v4 API, so a self-hosted instance must run Langfuse v4. ### 2. Set Environment Variables ```bash theme={null} # .env.development LANGFUSE_PUBLIC_KEY=pk-lf-... LANGFUSE_SECRET_KEY=sk-lf-... LANGFUSE_HOST=https://cloud.langfuse.com ``` For SDK guides, see [Langfuse (Python)](/python/vfs/langfuse) and [Langfuse (TypeScript)](/typescript/setup/langfuse). # Linear Source: https://docs.mirage.strukto.ai/home/setup/linear Set up a Linear personal API key for the Linear VFS. ## Credentials ### 1. Create a Personal API Key 1. Go to Settings -> Security & Access 2. Create a new personal API key 3. Copy the key ### 2. Set Environment Variables ```bash theme={null} # .env.development LINEAR_API_KEY=lin_api_xxxx... ``` For SDK guides, see [Linear (Python)](/python/vfs/linear) and [Linear (TypeScript)](/typescript/setup/linear). # Linux Source: https://docs.mirage.strukto.ai/home/setup/linux Install FUSE 3 for Mirage's FUSE mounts. **1. Install FUSE 3** > [tab] Ubuntu / Debian > > ```bash theme={null} > sudo apt-get install fuse3 libfuse3-dev > ``` > [tab] Fedora / RHEL > > ```bash theme={null} > sudo dnf install fuse3 fuse3-devel > ``` > [tab] Arch Linux > > ```bash theme={null} > sudo pacman -S fuse3 > ``` **2. Verify** ```bash theme={null} fusermount3 --version ``` Mirage needs only `fusermount3`, so it works where the older `fusermount` is missing, as on Fedora, RHEL, Amazon Linux 2023, openSUSE and Alpine. # Apple Container Source: https://docs.mirage.strukto.ai/home/setup/machine/apple_container Run captured programs in containers under Apple's container tool on macOS. The `apple_container` machine provider reaches a running container under Apple's `container` tool, and the `remote` runtime runs captured programs in it. You start the containers; Mirage only runs programs in them. Needs Apple silicon and macOS 26 or later. Python SDK and Node. ## Installation Install and start Apple's `container`. From the Mirage repository root, build [the machine image](/home/setup/machine/overview#the-machine-image), which carries Mirage and `fuse3`, and start a container from it: ```bash theme={null} brew install container container system start container build -f docker/sandbox/Dockerfile --target fuse \ -t mirage-python-fuse . container run -d --init --cap-add SYS_ADMIN \ --name my-sandbox mirage-python-fuse sleep infinity ``` `--init` gives the container a process that collects what ends; without it a program that is killed stays behind as a zombie. ## Usage `captures` defaults to [`@external`](/home/setup/runtime/overview#captures): every program Mirage does not have itself. Name `@python` to run Python in the container too. For one container per agent, make each container a machine of its own and send each session to its machine with a [route](/home/policy/route-runtime#admit-then-route). > [tab] Python > > ```python theme={null} > from mirage import RAMVFS, MountMode, Workspace > from mirage.runtime.machine import RemoteRuntime > > ws = Workspace( > {"/data": RAMVFS()}, > mode=MountMode.EXEC, > machines={"box": {"provider": "apple_container", "container": "my-sandbox"}}, > runtimes=[RemoteRuntime(["@python", "@external"], machine="box")], > ) > await ws.shell("python3 -c 'print(1 + 1)'") > ``` > [tab] TypeScript > > ```typescript theme={null} > import { MountMode, RemoteRuntime, RAMVFS, Workspace } from '@struktoai/mirage-node' > > const ws = new Workspace( > { '/data': new RAMVFS() }, > { > mode: MountMode.EXEC, > machines: { box: { provider: 'apple_container', container: 'my-sandbox' } }, > runtimes: [new RemoteRuntime({ captures: ['@python', '@external'], machine: 'box' })], > }, > ) > await ws.shell("python3 -c 'print(1 + 1)'") > ``` > [tab] YAML > > ```yaml theme={null} > mode: exec > machines: > box: > provider: apple_container > container: my-sandbox > runtimes: > - name: remote > captures: ["@python", "@external"] > machine: box > mounts: > /data: > vfs: ram > ``` ## Connecting the workspace Pick a [`mount_type`](/home/setup/machine/overview#connecting-the-workspace). The default image lacks `sshfs` for `ssh`; add it with `apt-get update && apt-get install sshfs`. With `fuse`, copy `sandbox.yaml` in and start Mirage in the container: ```bash theme={null} container cp sandbox.yaml my-sandbox:/tmp/sandbox.yaml container exec my-sandbox mirage workspace create /tmp/sandbox.yaml ``` ## Notes * Set `container` to the name of a running container. * The image needs a POSIX-compatible `/bin/sh`. The session's environment wins over the image's. The working directory must already exist in the container. * Host directories reach the container only through `--volume`. A service on your Mac is not at `127.0.0.1` inside; Apple's [host integration guide](https://github.com/apple/container/blob/main/docs/host-integration.md) sets up `host.container.internal`. * Each container is its own VM, so agents with one each share no files, processes, CPU or memory. Give each one that agent's rules: the `default` profile in its `sandbox.yaml`. * A [timeout](/home/setup/machine/overview#timeouts) does not kill the program: `container` 1.4.1 does not deliver signals into the guest ([apple/container#1941](https://github.com/apple/container/issues/1941)). # Daytona Source: https://docs.mirage.strukto.ai/home/setup/machine/daytona Run captured programs in a Daytona cloud sandbox you created. The `daytona` machine provider reaches a running [Daytona](https://www.daytona.io) sandbox, by ID, and the `remote` runtime runs captured programs in it. You create and size the sandbox; Mirage only runs programs in it. Python SDK and Node. ## Installation > [tab] Python > > ```bash theme={null} > pip install 'mirage-ai[daytona]' > ``` > [tab] TypeScript > > ```bash theme={null} > pnpm add @daytonaio/sdk > ``` Boot the sandbox from an image or snapshot that has what [connecting the workspace](#connecting-the-workspace) needs. Set `api_key` in the config, or `DAYTONA_API_KEY`. ## Usage `captures` defaults to [`@external`](/home/setup/runtime/overview#captures): every program Mirage does not have itself. Name `@python` to run Python in the sandbox too. > [tab] Python > > ```python theme={null} > from mirage import RAMVFS, MountMode, Workspace > from mirage.runtime.machine import RemoteRuntime > > ws = Workspace( > {"/data": RAMVFS()}, > mode=MountMode.EXEC, > machines={"box": {"provider": "daytona", "sandbox_id": "sandbox-id"}}, > runtimes=[RemoteRuntime(["@python", "@external"], machine="box")], > ) > await ws.shell("python3 -c 'print(1 + 1)'") > ``` > [tab] TypeScript > > ```typescript theme={null} > import { MountMode, RemoteRuntime, RAMVFS, Workspace } from '@struktoai/mirage-node' > > const ws = new Workspace( > { '/data': new RAMVFS() }, > { > mode: MountMode.EXEC, > machines: { box: { provider: 'daytona', sandboxId: 'sandbox-id' } }, > runtimes: [new RemoteRuntime({ captures: ['@python', '@external'], machine: 'box' })], > }, > ) > await ws.shell("python3 -c 'print(1 + 1)'") > ``` > [tab] YAML > > ```yaml theme={null} > mode: exec > machines: > box: > provider: daytona > sandbox_id: ${DAYTONA_SANDBOX_ID} > runtimes: > - name: remote > captures: ["@python", "@external"] > machine: box > mounts: > /data: > vfs: ram > ``` ## Connecting the workspace Mirage does not serve mounts into a Daytona sandbox. Use [the machine image](/home/setup/machine/overview#the-machine-image) and the [`fuse` steps](/home/setup/machine/overview#fuse), then start Mirage in the sandbox: ```bash theme={null} mirage workspace create /tmp/sandbox.yaml ``` ## Notes * Stopping or closing the workspace leaves the sandbox running. * Piped input is uploaded to a temporary file in the sandbox and read as stdin. * Output comes back as the program wrote it, binary included: the sandbox base64-encodes it on the way out, so the image needs `dd` and `base64` (Debian, Ubuntu and Alpine images have both), and output takes about a third more to transfer. Without them a line runs nothing, prints why and exits 127. * Sizing, GPUs, snapshots, networking, idle-stop and auto-delete stay Daytona settings. The [Daytona example](https://github.com/strukto-ai/mirage/tree/main/examples/python/machine/daytona) covers baking a snapshot and a full read and write round trip. * A Daytona sandbox has no timeout of its own. After a Mirage [timeout](/home/setup/machine/overview#timeouts), Python stops the program; in TypeScript it keeps running and billing until you stop it. # Docker Source: https://docs.mirage.strukto.ai/home/setup/machine/docker Run captured programs in a Docker container you started. The `docker` machine provider reaches a running container, by name, and the `remote` runtime runs captured programs in it. You start and stop the container; Mirage only runs programs in it. Python SDK and Node. ## Installation > [tab] Python > > ```bash theme={null} > pip install 'mirage-ai[ssh]' > ``` > [tab] TypeScript > > ```bash theme={null} > pnpm add ssh2 > ``` These serve the workspace into the container with `mount_type: ssh`. Start the container with FUSE allowed and `sshfs` in it, or from an image that has what [connecting the workspace](#connecting-the-workspace) needs: ```bash theme={null} docker run -d --cap-add SYS_ADMIN --device /dev/fuse \ --name my-sandbox python:3.12-slim sleep infinity docker exec my-sandbox sh -c 'apt-get update && apt-get install -y sshfs' ``` ## Usage `captures` defaults to [`@external`](/home/setup/runtime/overview#captures): every program Mirage does not have itself. Name `@python` to run Python in the container too. > [tab] Python > > ```python theme={null} > from mirage import RAMVFS, MountMode, Workspace > from mirage.runtime.machine import RemoteRuntime > > ws = Workspace( > {"/data": RAMVFS()}, > mode=MountMode.EXEC, > machines={ > "box": { > "provider": "docker", > "container": "my-sandbox", > "mount_type": "ssh", > } > }, > runtimes=[RemoteRuntime(["@python", "@external"], machine="box")], > ) > await ws.shell("python3 -c 'print(1 + 1)'") > ``` > [tab] TypeScript > > ```typescript theme={null} > import { MountMode, RemoteRuntime, RAMVFS, Workspace } from '@struktoai/mirage-node' > > const ws = new Workspace( > { '/data': new RAMVFS() }, > { > mode: MountMode.EXEC, > machines: { box: { provider: 'docker', container: 'my-sandbox', mountType: 'ssh' } }, > runtimes: [new RemoteRuntime({ captures: ['@python', '@external'], machine: 'box' })], > }, > ) > await ws.shell("python3 -c 'print(1 + 1)'") > ``` > [tab] YAML > > ```yaml theme={null} > mode: exec > machines: > box: > provider: docker > container: my-sandbox > mount_type: ssh > runtimes: > - name: remote > captures: ["@python", "@external"] > machine: box > mounts: > /data: > vfs: ram > ``` Save the YAML as `workspace.yaml` and run a line from the CLI: ```bash theme={null} mirage workspace create workspace.yaml -w box-demo mirage shell -w box-demo -c 'echo hello > /data/hi.txt; python3 -c "print(open(\"/data/hi.txt\").read().upper())"' ``` `python3` runs in the container and reads the file Mirage wrote, so this prints `HELLO`. Remove both with `mirage workspace delete box-demo` and `docker rm -f my-sandbox`. ## Connecting the workspace Pick a [`mount_type`](/home/setup/machine/overview#connecting-the-workspace). With `ssh`, the image needs only `sshfs`. With `fuse`, copy `sandbox.yaml` in and start Mirage in the container: ```bash theme={null} docker cp sandbox.yaml my-sandbox:/tmp/sandbox.yaml docker exec my-sandbox mirage workspace create /tmp/sandbox.yaml ``` ## Notes * `container` takes a name or an ID. The Docker CLI is the transport, so Docker Desktop, Colima and a compatible Podman alias all work. * Sizing, GPUs, networks, volumes and bind mounts go on your own `docker run`. You can bake `sandbox.yaml` into the image instead of copying it, and point it at `host.docker.internal` for a host service. > [!WARNING] > > Environment values go on the `docker exec` command line, so other users of > the host can see them in `ps`. Avoid secrets on a host shared with > untrusted users. # E2B Source: https://docs.mirage.strukto.ai/home/setup/machine/e2b Run captured programs in an E2B cloud sandbox you created. The `e2b` machine provider reaches a running [E2B](https://e2b.dev) sandbox, by ID, and the `remote` runtime runs captured programs in it. You create the sandbox from a template; Mirage only runs programs in it. Python SDK, Node and browsers. ## Installation > [tab] Python > > ```bash theme={null} > pip install 'mirage-ai[e2b,ssh]' > ``` > [tab] TypeScript > > ```bash theme={null} > pnpm add e2b ssh2 > ``` The `ssh` extra and `ssh2` serve the workspace into the sandbox with `mount_type: ssh`. Create the sandbox from a template that has what [connecting the workspace](#connecting-the-workspace) needs. Set `api_key` in the config, as a value or a [credential pointer](/home/authentication#pointer-fields), or `E2B_API_KEY`. ## Usage `captures` defaults to [`@external`](/home/setup/runtime/overview#captures): every program Mirage does not have itself. Name `@python` to run Python in the sandbox too. > [tab] Python > > ```python theme={null} > from mirage import RAMVFS, MountMode, Workspace > from mirage.runtime.machine import RemoteRuntime > > ws = Workspace( > {"/data": RAMVFS()}, > mode=MountMode.EXEC, > machines={ > "box": { > "provider": "e2b", > "sandbox_id": "sandbox-id", > "mount_type": "ssh", > } > }, > runtimes=[RemoteRuntime(["@python", "@external"], machine="box")], > ) > await ws.shell("python3 -c 'print(1 + 1)'") > ``` > [tab] TypeScript > > ```typescript theme={null} > import { MountMode, RemoteRuntime, RAMVFS, Workspace } from '@struktoai/mirage-node' > > const ws = new Workspace( > { '/data': new RAMVFS() }, > { > mode: MountMode.EXEC, > machines: { box: { provider: 'e2b', sandboxId: 'sandbox-id', mountType: 'ssh' } }, > runtimes: [new RemoteRuntime({ captures: ['@python', '@external'], machine: 'box' })], > }, > ) > await ws.shell("python3 -c 'print(1 + 1)'") > ``` > > In a browser, import `@struktoai/mirage-core/machine/e2b/handle` once > to register the provider (`pnpm add @struktoai/mirage-core`), pass > `apiKey`, and use `mountType: 'fuse'` or leave it unset. > [tab] YAML > > ```yaml theme={null} > mode: exec > machines: > box: > provider: e2b > sandbox_id: ${E2B_SANDBOX_ID} > mount_type: ssh > runtimes: > - name: remote > captures: ["@python", "@external"] > machine: box > mounts: > /data: > vfs: ram > ``` ## Connecting the workspace Pick a [`mount_type`](/home/setup/machine/overview#connecting-the-workspace). `ssh` and `both` do not work in browsers, and each file call is about 150 ms for a small file from a laptop. With `fuse`, base the template on [the machine image](/home/setup/machine/overview#the-machine-image) and run `mirage workspace create /tmp/sandbox.yaml` in the sandbox. ### A template for ssh Build a template with `sshfs` and pass its sandbox ID as `sandbox_id`: > [tab] Python > > ```python theme={null} > from e2b import AsyncSandbox, Template > > Template.build(Template().from_base_image().apt_install("sshfs"), "mirage-sshfs") > sandbox = await AsyncSandbox.create("mirage-sshfs") > print(sandbox.sandbox_id) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { Sandbox, Template } from 'e2b' > > await Template.build(Template().fromBaseImage().aptInstall('sshfs'), 'mirage-sshfs') > const sandbox = await Sandbox.create('mirage-sshfs') > console.log(sandbox.sandboxId) > ``` Keep the base image's user, which has `sudo` for mountpoints such as `/data`. On the default template, run `sudo apt-get update && sudo apt-get install -y sshfs` instead. ## Notes * Stopping or closing the workspace leaves the sandbox running. * Output comes back as the program wrote it, binary included: the sandbox base64-encodes it on the way out, so the image needs `dd` and `base64` (Debian, Ubuntu and Alpine images have both), and output takes about a third more to transfer. Without them a line runs nothing, prints why and exits 127. * Commands run concurrently, each with its own input and output. Without piped input, stdin starts closed. * Templates, sizing, networking and lifecycle stay E2B settings. * A Mirage [timeout](/home/setup/machine/overview#timeouts) tries to kill the command; its child processes may survive. # Kubernetes Source: https://docs.mirage.strukto.ai/home/setup/machine/kubernetes Run captured programs in a Kubernetes pod, including a Nitro Sandbox on EKS. The `kubernetes` machine provider reaches a running pod, by name, through `kubectl exec`, and the `remote` runtime runs captured programs in it. You create the pod; Mirage only runs programs in it. Python SDK and Node. ## Installation Install `kubectl` and sign it in to the cluster. Mirage uses the credentials and context `kubectl` already has. Create a pod that stays running: ```yaml theme={null} apiVersion: v1 kind: Pod metadata: name: mirage-box spec: containers: - name: main image: my-mirage-image command: ["sleep", "infinity"] ``` ## Nitro Sandboxes on EKS To run the pod in an [AWS Nitro Sandbox](https://docs.aws.amazon.com/eks/latest/userguide/sandboxing.html), a lightweight VM with its own kernel, set the runtime class on it. This needs Kubernetes 1.36 or later. ```yaml theme={null} spec: runtimeClassName: isolated-sandbox ``` Mirage needs `exec` and stdin, so use `isolated-sandbox`. A `confidential-sandbox` pod denies them, and programs cannot run in it. ## Usage `captures` defaults to [`@external`](/home/setup/runtime/overview#captures): every program Mirage does not have itself. Name `@python` to run Python in the pod too. > [tab] Python > > ```python theme={null} > from mirage import RAMVFS, MountMode, Workspace > from mirage.runtime.machine import RemoteRuntime > > ws = Workspace( > {"/data": RAMVFS()}, > mode=MountMode.EXEC, > machines={"box": {"provider": "kubernetes", "pod": "mirage-box"}}, > runtimes=[RemoteRuntime(["@python", "@external"], machine="box")], > ) > await ws.shell("python3 -c 'print(1 + 1)'") > ``` > [tab] TypeScript > > ```typescript theme={null} > import { MountMode, RemoteRuntime, RAMVFS, Workspace } from '@struktoai/mirage-node' > > const ws = new Workspace( > { '/data': new RAMVFS() }, > { > mode: MountMode.EXEC, > machines: { box: { provider: 'kubernetes', pod: 'mirage-box' } }, > runtimes: [new RemoteRuntime({ captures: ['@python', '@external'], machine: 'box' })], > }, > ) > await ws.shell("python3 -c 'print(1 + 1)'") > ``` > [tab] YAML > > ```yaml theme={null} > mode: exec > machines: > box: > provider: kubernetes > pod: mirage-box > runtimes: > - name: remote > captures: ["@python", "@external"] > machine: box > mounts: > /data: > vfs: ram > ``` ## Configuration | Field | Meaning | | - | - | | `pod` | Name of a running pod. Required. | | `namespace` | The pod's namespace. Defaults to the context's. | | `container` | The container in the pod. Defaults to the pod's default. | | `context` | The kubeconfig context. Defaults to the current one. | ## Connecting the workspace Pick a [`mount_type`](/home/setup/machine/overview#connecting-the-workspace). With `ssh`, the pod needs `sshfs` and access to `/dev/fuse`. With `fuse`, put `sandbox.yaml` in the pod and start Mirage: ```bash theme={null} kubectl exec mirage-box -- mirage workspace create /tmp/sandbox.yaml ``` ## Notes * The pod's phase must be `Running`. * The working directory and environment travel on the `kubectl` command line, where other users of the host can see them in `ps`. * A run whose connection to the pod drops ends with status 129. * Lines sent to one pod share its files and processes. Give each tenant its own pod. # microsandbox Source: https://docs.mirage.strukto.ai/home/setup/machine/microsandbox Run captured programs in an existing microsandbox microVM. The `microsandbox` machine provider reaches a running [microsandbox](https://microsandbox.dev) microVM, by name, and the `machine` runtime runs captured programs in it. You create and start the sandbox; Mirage runs programs in it through the `msb` CLI. Python SDK and Node. ## Installation Install `msb` 0.7.14 or newer on the host and put it on `PATH`. Create a sandbox from an image with `sh`, your programs, and the tools needed for [connecting the workspace](#connecting-the-workspace): ```bash theme={null} msb create my-registry/mirage-fuse:latest --name mirage-box ``` ## Usage `captures` defaults to [`@external`](/home/setup/runtime/overview#captures). Add `@python` to run Python programs in the guest too. > [tab] Python > > ```python theme={null} > from mirage import RAMVFS, MountMode, Workspace > from mirage.runtime.machine import RemoteRuntime > > ws = Workspace( > {"/data": RAMVFS()}, > mode=MountMode.EXEC, > machines={"box": {"provider": "microsandbox", "sandbox": "mirage-box"}}, > runtimes=[RemoteRuntime(["@python", "@external"], machine="box")], > ) > await ws.shell("python3 -c 'print(1 + 1)'") > ``` > [tab] TypeScript > > ```typescript theme={null} > import { MountMode, RemoteRuntime, RAMVFS, Workspace } from '@struktoai/mirage-node' > > const ws = new Workspace( > { '/data': new RAMVFS() }, > { > mode: MountMode.EXEC, > machines: { box: { provider: 'microsandbox', sandbox: 'mirage-box' } }, > runtimes: [new RemoteRuntime({ captures: ['@python', '@external'], machine: 'box' })], > }, > ) > await ws.shell("python3 -c 'print(1 + 1)'") > ``` > [tab] YAML > > ```yaml theme={null} > mode: exec > machines: > box: > provider: microsandbox > sandbox: mirage-box > runtimes: > - name: remote > captures: ["@python", "@external"] > machine: box > mounts: > /data: > vfs: ram > ``` ## Connecting the workspace Pick a [`mount_type`](/home/setup/machine/overview#connecting-the-workspace). With `ssh`, install `mirage-ai[ssh]` on a Python host or `ssh2` on a Node host; the guest needs `sshfs` and access to `/dev/fuse`. With `fuse`, copy `sandbox.yaml` in and start Mirage in the guest: ```bash theme={null} msb copy sandbox.yaml mirage-box:/tmp/sandbox.yaml msb exec mirage-box -- mkdir -p /data msb exec mirage-box -- mirage workspace create /tmp/sandbox.yaml ``` Matching paths alone does not share data; configure both workspaces to use the same backend. ## Notes * Keep the sandbox running while Mirage uses it. Each line runs its own `msb exec`, so a restart needs no reconnect. With `fuse` or `both`, start the sandbox's Mirage again after a restart, or from its image's entrypoint; until then lines exit 126. * Stopping or closing the workspace leaves the sandbox running. * A [timeout](/home/setup/machine/overview#timeouts) cancels the CLI call and stops that run's processes in the sandbox. * A program's output reaches Mirage as it prints, except when Mirage pipes input into the program: then the output arrives when the program ends. * Commands share the sandbox's files and processes. Use one sandbox per tenant. * Environment values are passed as CLI arguments. Avoid secrets on hosts shared with untrusted users. # Overview Source: https://docs.mirage.strukto.ai/home/setup/machine/overview Run captured programs on a container, VM, cloud sandbox or remote machine you already have. A machine is somewhere you already have: a container, a microVM, a cloud sandbox or a host over SSH. You create and stop it; Mirage only runs programs on it. Declare each machine under `machines:` with the `provider` that reaches it, and run captured programs there with the `remote` runtime. `captures` defaults to [`@external`](/home/setup/runtime/overview#captures), every program Mirage does not have itself. ```yaml theme={null} machines: box: provider: docker container: my-sandbox runtimes: - name: remote machine: box ``` A line or a command can also name its machine: `execute(machine=)`, a `machine` on the shell request, or a policy's `Route(machine=)`. | Provider | Runs programs in | | - | - | | [Docker](/home/setup/machine/docker) | A Docker container | | [E2B](/home/setup/machine/e2b) | An E2B cloud sandbox | | [Daytona](/home/setup/machine/daytona) | A Daytona cloud sandbox | | [Kubernetes](/home/setup/machine/kubernetes) | A pod, including an AWS Nitro Sandbox on EKS | | [smolvm](/home/setup/machine/smolvm) | A microVM with its own kernel | | [Microsandbox](/home/setup/machine/microsandbox) | A microVM with its own kernel | | [Apple Container](/home/setup/machine/apple_container) | A container on macOS, a VM of its own | | [SSH](/home/setup/machine/ssh) | Any machine running `sshd` | [Sandlock](/home/setup/runtime/sandlock) is a runtime, not a machine: it runs programs on this Linux host, confined. To try one, start with [Docker](/home/setup/machine/docker). ## Connecting the workspace A program on a machine opens workspace files at the same paths as in Mirage, so the machine must see the mounts. `mount_type` picks how: | `mount_type` | How the files get there | Rules that apply | | - | - | - | | `ssh` | Mirage serves every mount over the provider's connection; the machine mounts each with `sshfs` | This workspace's mount modes, hides, permissions and policies | | `fuse` | A Mirage on the machine mounts your backends with FUSE | That Mirage's own config | | `both` | The machine's own FUSE mounts where it has them, `ssh` for the rest | Each side's own | | unset | Nothing; you put the files there yourself | The machine's | Daytona takes no `mount_type`: run a Mirage on the machine, as `fuse` does, or put the files there yourself. Once connected, run the shared [workspace file check](/home/setup/runtime/overview#verify-workspace-file-access). ### ssh * The machine needs only `sshfs`. No Mirage, keys or open port. * Each file call is a round trip to the workspace. With `both`, keep bulk data on the machine's own mounts. * A machine shows one session's view, the first that runs a line there. An sshfs already serving a path Mirage serves is left alone and the line exits 1. Give each agent and each workspace its own machine. * If the machine restarts, Mirage mounts the paths again. A line caught mid-restart exits 126 without running. * A write the workspace refuses, such as one past a mount's `capacity`, looks done to the program, but its command fails when the program ends: stderr names the file, as `docker: /data/big.bin: Disk quota exceeded`, and a command that would exit 0 exits 1. * The root mount and `/dev` are not served. Mirage refuses to run a program when it cannot enforce the session's file rules: restrictions on `/` or `/dev`, hiding a mount when that would expose the machine's own files underneath, restrictions on mounts a Mirage on the machine serves, and rules that depend on which program opens a file. ### fuse Build [the machine image](#the-machine-image), write the same mounts at the same paths into `sandbox.yaml`, and start Mirage with it on the machine. Each provider page has the commands. ```yaml theme={null} mounts: /data: vfs: s3 config: bucket: my-bucket backend: fuse mountpoint: /data ``` * This workspace's rules do not reach those files, so a line is refused while the session's permissions hide or narrow anything under them. * If a path the machine mounted goes away, lines exit 126 until it is mounted again. Start Mirage from the image's entrypoint so a restart mounts it again. * Keep the machine's paths in step with the host's mounts yourself. `sandbox.yaml` can differ where it should, such as narrower credentials. ## What a program sees | | On the machine | | - | - | | Command | The captured program and its words, as typed | | Piped input | stdin | | Environment | The session's, over the config `env`, plus `MIRAGE_PROCESS`, the id of its Mirage process. Docker, Apple Container, Kubernetes, smolvm and Microsandbox pass it on the exec command line, where other users of the host can see it in `ps`. | | Working directory | The shell's, unchanged; one the machine lacks exits 126 | | Disk, network, language modules | The machine's own | ## Processes and jobs One session can run jobs on several machines at once. `jobs`, `wait`, `kill` and `ps` ask the machines what is running, so they answer with what is true there now. `ps` lists each program with its real pid and its machine, and what the program started under it: ```text theme={null} PID MACHINE CMD 4194305 mirage ps 13 docker:box python3 train.py 19 docker:box sleep 300 13 ssh:gpu python3 eval.py ``` `ps -o pid,machine` selects those columns, and `ps f` draws each command under its parent's. `$!` is the program's real pid, through `nohup` and other wrappers too, and `STAT` is what the machine reports, `T` for a program `kill -STOP` paused. `kill` sends a signal to a program as you sent it: a program that traps `USR1` runs on, and one that `TERM` ends exits with its own status, which `wait` reports. KILL is sent only when you ask for it (`kill -9`, `timeout -k`) or when Mirage shuts the workspace down. Mirage's own commands have pids from 4194305 up. A pid two machines both have is refused as an ambiguous job spec, so name the machine with `-m` or `--machine`, as `ps` shows it or without the provider: `kill -m box 13` or `wait --machine ssh:gpu 13`. All of this follows the session's `processes` grants. `pgrep`, `pkill`, `pidof` and `killall` search the processes `ps` shows, so they reach every machine at once and do not see processes Mirage did not start. ## Reading machines `hostname`, `nproc`, `lscpu` and `free` answer for the workspace, as `mirage`, and for each machine. `uptime` and `top -b` answer for the machines. One answer prints what the real command prints. Several print a row each with the machine on the right, so a column you read by position stays where it is; `hostname` prints one name a line. Figures are never added up, as one program cannot use another machine's memory. ```bash theme={null} $ nproc 1 mirage 5 apple_container:mac 1 microsandbox:local 2 e2b:cloud $ hostname mirage mirage-box e2b.local $ lscpu mirage microsandbox:local e2b:cloud Architecture: - aarch64 x86_64 Byte Order: Little Endian Little Endian Little Endian CPU(s): 1 1 2 Model name: - - Intel(R) Xeon(R) Processor @ 2.60GHz $ free -h total used free shared buff/cache available MACHINE Mem: 96Mi 1.2Mi 94Mi - - 94Mi mirage Swap: 0B 0B 0B mirage Mem: 1.1Gi 107Mi 794Mi 4.0Ki 213Mi 994Mi apple_container:mac Swap: 0B 0B 0B apple_container:mac Mem: 1.9Gi 139Mi 1.8Gi 0B 70Mi 1.8Gi microsandbox:local Swap: 0B 0B 0B microsandbox:local ``` The workspace reports one processor, little-endian byte order and, in `free`, its [`max_memory`](/home/core/output-limits) with what it holds of that. It prints `-` for everything else, so nothing about the server Mirage runs on shows. `lscpu` leaves the flags and vulnerability rows out of its table; `lscpu --machine cloud` prints that machine's full output, and any other option goes to the default machine's own `lscpu`. `df` and `mount` list the workspace's mounts, not a machine's disks. Inside `$( )` they answer for the machine programs run on by default, so `make -j$(nproc)` gets one number. `--machine` picks another: `workers=$(nproc --machine cloud)`. `--machine mirage` picks the workspace. The host counts as a machine only while a runtime runs programs on it, and prints `-` for figures it has no such thing for. `uptime`, `top` and `lscpu` exist only in a workspace that runs programs on a machine or the host; there `top` needs `-b`, as it does without a terminal. `ps -o %cpu,%mem,rss,vsz,time` shows what each program has used, and `ps --machine cloud` narrows it to one machine. `top` reads each machine's processors twice a second apart, so it takes about a second. ## Machine states | State | Means | | - | - | | `managed` | Mirage sees and stops every process its programs start there. The workspace's own host is always `managed`. | | `reachable` | Mirage reached it, but sees and stops only what it started itself. The machine lacks `/proc`, `sh`, `tr` or `grep`. | | `unreachable` | The last check failed. | Mirage finds a run's processes by `MIRAGE_PROCESS` in `/proc`, so it misses one that drops the variable or whose `/proc` entry it cannot read, such as a process of another user. `GET /v1/workspaces/{id}/machines` checks every machine, and `GET /v1/workspaces/{id}/machines/{machine}` checks one and lists its processes. `{machine}` is the id `ps` shows, `provider:name` such as `docker:box`; a bare name answers 400. `mirage workspace list-machines -w ID` prints each machine and its state. ## The machine image Every machine needs a POSIX shell at `/bin/sh` and `grep`. E2B and Daytona also need `dd` and `base64`, which carry a program's output back. With [libfaketime](https://github.com/wolfcw/libfaketime) in the image, programs see the workspace's [`system_time`](/home/configuration#system-time). With `mount_type: ssh` the machine also needs `sshfs`, and a machine that runs its own Mirage needs `fuse3` and Mirage. The repository's Dockerfile builds an image with `fuse3`, Mirage and libfaketime for every provider. It has no `sshfs`: add it for `mount_type: ssh`. ```bash theme={null} docker build -f docker/sandbox/Dockerfile --target fuse \ --build-arg MIRAGE_EXTRAS=s3,postgres -t mirage-fuse . ``` Leave out `MIRAGE_EXTRAS` for every mountable backend. Add the programs your captures need, such as Node.js for `node`. ## Timeouts `command_limits` apply to a program on a machine as to any command: a line past its `timeout_seconds` exits 124, and `max_bytes` and `max_lines` cap its output. A timeout sends TERM, then KILL a second later, to every process of that run, and gives up after 5 seconds if the machine stops answering. That needs `/bin/sh`, `tr`, `grep` and `/proc` on the machine. > [!WARNING] > > In TypeScript, a Daytona command keeps running after a timeout, and a > Daytona sandbox has no timeout of its own, so it keeps billing. Use the > provider's own limits for anything that must not outlive a timeout. # smolvm Source: https://docs.mirage.strukto.ai/home/setup/machine/smolvm Run captured programs in a smolvm microVM with its own kernel. The `smolvm` machine provider reaches a running [smolvm](https://smolmachines.com) microVM, by name, and the `remote` runtime runs captured programs in it. Each machine has its own guest kernel, on macOS, Linux and Windows. You create and start the machine; Mirage only runs programs in it. Python SDK and Node. ## Installation Install the `smolvm` CLI. Create and start a machine from an image that has what [connecting the workspace](#connecting-the-workspace) needs: ```bash theme={null} smolvm machine create --net --name mirage-box --image my-mirage-image smolvm machine start --name mirage-box ``` ## Usage `captures` defaults to [`@external`](/home/setup/runtime/overview#captures): every program Mirage does not have itself. Name `@python` to run Python in the machine too. > [tab] Python > > ```python theme={null} > from mirage import RAMVFS, MountMode, Workspace > from mirage.runtime.machine import RemoteRuntime > > ws = Workspace( > {"/data": RAMVFS()}, > mode=MountMode.EXEC, > machines={"box": {"provider": "smolvm", "machine": "mirage-box"}}, > runtimes=[RemoteRuntime(["@python", "@external"], machine="box")], > ) > await ws.shell("python3 -c 'print(1 + 1)'") > ``` > [tab] TypeScript > > ```typescript theme={null} > import { MountMode, RemoteRuntime, RAMVFS, Workspace } from '@struktoai/mirage-node' > > const ws = new Workspace( > { '/data': new RAMVFS() }, > { > mode: MountMode.EXEC, > machines: { box: { provider: 'smolvm', machine: 'mirage-box' } }, > runtimes: [new RemoteRuntime({ captures: ['@python', '@external'], machine: 'box' })], > }, > ) > await ws.shell("python3 -c 'print(1 + 1)'") > ``` > [tab] YAML > > ```yaml theme={null} > mode: exec > machines: > box: > provider: smolvm > machine: mirage-box > runtimes: > - name: remote > captures: ["@python", "@external"] > machine: box > mounts: > /data: > vfs: ram > ``` ## Connecting the workspace Pick a [`mount_type`](/home/setup/machine/overview#connecting-the-workspace). With `ssh`, the guest needs `sshfs`. With `fuse`, put `sandbox.yaml` in the machine, in its image or a directory passed with `--volume`, and start Mirage: ```bash theme={null} smolvm machine exec --name mirage-box -- mirage workspace create /tmp/sandbox.yaml ``` ## Notes * Host files reach the machine only through directories passed with `--volume` at boot. * The machine must be `running`. Start a `stopped` or `created` machine, or clone a `frozen` machine before using it. Mirage cannot run commands while a machine is `unreachable`. * Lines sent to one machine share its files and processes. Give each tenant its own machine. # SSH Source: https://docs.mirage.strukto.ai/home/setup/machine/ssh Run captured programs on any machine you can reach over SSH. The `ssh` machine provider reaches a machine running `sshd`, and the `machine` runtime runs captured programs on it. Anything you can already `ssh` into works, with nothing to install on it. You run the machine; Mirage only runs programs on it. Python SDK and Node. ## Installation > [tab] Python > > ```bash theme={null} > pip install 'mirage-ai[ssh]' > ``` > [tab] TypeScript > > ```bash theme={null} > pnpm add ssh2 > ``` ## Usage `captures` defaults to [`@external`](/home/setup/runtime/overview#captures): every program Mirage does not have itself. Name `@python` to run Python on the machine too. > [tab] Python > > ```python theme={null} > from mirage import RAMVFS, MountMode, Workspace > from mirage.runtime.machine import RemoteRuntime > > ws = Workspace( > {"/data": RAMVFS()}, > mode=MountMode.EXEC, > machines={ > "box": { > "provider": "ssh", > "host": "mybox", > "username": "deploy", > "identity_file": "~/.ssh/id_ed25519", > } > }, > runtimes=[RemoteRuntime(["@python", "@external"], machine="box")], > ) > await ws.shell("python3 -c 'print(1 + 1)'") > ``` > [tab] TypeScript > > ```typescript theme={null} > import { MountMode, RemoteRuntime, RAMVFS, Workspace } from '@struktoai/mirage-node' > > const ws = new Workspace( > { '/data': new RAMVFS() }, > { > mode: MountMode.EXEC, > machines: { > box: { > provider: 'ssh', > host: 'mybox', > username: 'deploy', > identityFile: '~/.ssh/id_ed25519', > }, > }, > runtimes: [new RemoteRuntime({ captures: ['@python', '@external'], machine: 'box' })], > }, > ) > await ws.shell("python3 -c 'print(1 + 1)'") > ``` > [tab] YAML > > ```yaml theme={null} > mode: exec > machines: > box: > provider: ssh > host: mybox > username: deploy > identity_file: ~/.ssh/id_ed25519 > runtimes: > - name: remote > captures: ["@python", "@external"] > machine: box > mounts: > /data: > vfs: ram > ``` ## Connecting the workspace Pick a [`mount_type`](/home/setup/machine/overview#connecting-the-workspace). With `ssh`, the machine needs `sshfs`, and passwordless `sudo` for a mountpoint its user cannot create (`/data`). Without `mount_type`, two ways: **Files already on the machine.** Mount the machine's directory with the [ssh VFS](/python/vfs/ssh) at a prefix equal to its path there. The same path then names the same file on both sides, with nothing to install: ```yaml theme={null} mounts: /home/user/proj: vfs: ssh config: host: mybox root: /home/user/proj machines: box: provider: ssh host: mybox runtimes: - name: remote captures: ["@python", "@external"] machine: box ``` **Any other mount** (S3, Slack and so on). Install Mirage and `fuse3` on the machine, and start Mirage with a `sandbox.yaml` that lists the same paths: ```bash theme={null} ssh mybox mirage workspace create sandbox.yaml ``` Mirage never rewrites paths and nothing checks that they match. A program on the machine opens its files directly, outside this workspace's mount modes and permissions. ## Notes * `host` is also the address unless `hostname` overrides it; `port`, `username`, `identity_file`, `private_key` and `timeout` are optional. Authentication is a key or an agent, never a password. * `private_key` takes the key's own text rather than a path, so a [credential pointer](/home/authentication#pointer-fields) can read it from a secret store. * The machine's login shell must be POSIX-compatible. Commands use the session's working directory and environment. > [!WARNING] > > Host keys are not verified, so treat the network path to the machine as > trusted. # macOS Source: https://docs.mirage.strukto.ai/home/setup/macos Install macFUSE for Mirage's FUSE mounts. **1. Install macFUSE** ```bash theme={null} brew install --cask macfuse ``` **2. Allow the system extension** Open **System Settings → Privacy & Security**. At the bottom, next to "System software from developer 'Benjamin Fleischer' was blocked from loading", click **Allow**. **3. Restart** macOS loads the extension after a restart. **4. Verify** ```bash theme={null} ls /Library/Filesystems/macfuse.fs ``` The folder exists when macFUSE is installed. > [accordion] No Allow button on Apple silicon > > **1. Shut down** > > Shut down your Mac completely. > > **2. Open Recovery** > > Hold the power button until "Loading startup options" appears, then > click **Options → Continue**. > > **3. Allow kernel extensions** > > Open **Utilities → Startup Security Utility**, set **Reduced Security** > and check **Allow user management of kernel extensions**. > > **4. Restart** > > Restart, then allow the extension in **System Settings → Privacy & Security**. # Mem0 Source: https://docs.mirage.strukto.ai/home/setup/mem0 Set up a Mem0 API key and memory scope for the Mem0 VFS. ## Credentials Mirage uses the [Mem0 Platform](https://docs.mem0.ai) managed API. You need a Mem0 API key and one memory scope — a `user_id`, `agent_id`, or `run_id` — to mount. ### 1. Get a Mem0 API Key 1. Sign in to the [Mem0 dashboard](https://app.mem0.ai). 2. Open **API Keys**. 3. Create or copy a key (it starts with `m0-...`). The key is sent as a `Token` authorization header to the Mem0 API. Your organization and project are resolved from the key. ### 2. Choose a Scope Mem0 stores each memory under a single entity. A Mirage mount is scoped to exactly one of: | Scope | Mem0 filter | | - | - | | User | `user_id` | | Agent | `agent_id` | | Run / session | `run_id` | Set exactly one. Combining two (for example `user_id` **and** `agent_id`) is rejected, because a memory added with both is split into separate user-scoped and agent-scoped memories — a combined filter matches nothing. ### 3. Set Environment Variables ```bash theme={null} # .env.development MEM0_API_KEY=m0-... MEM0_USER_ID=alex ``` For an agent or run scope, set `MEM0_AGENT_ID` or `MEM0_RUN_ID` instead of `MEM0_USER_ID`. For self-hosted or a custom host, set `MEM0_HOST`: ```bash theme={null} MEM0_HOST=https://api.mem0.ai ``` For SDK guides, see [Mem0 (Python)](/python/vfs/mem0) and [Mem0 (TypeScript)](/typescript/setup/mem0). # MinIO Source: https://docs.mirage.strukto.ai/home/setup/minio Set up MinIO credentials for the MinIO VFS. ## Credentials ### 1. Create an access key 1. Open the **MinIO Console** (e.g. `http://localhost:9001`) and sign in 2. Go to **Access Keys** -> **Create access key** 3. Copy the **Access Key** and **Secret Key** 4. Note your server **endpoint** (e.g. `http://localhost:9000`) and **bucket** name MinIO is self-hosted, so there is no region-derived endpoint, the `endpoint_url` is required and MinIO uses path-style addressing. ### 2. Set environment variables ```bash theme={null} # .env.development MINIO_BUCKET=my-bucket MINIO_ENDPOINT=http://localhost:9000 MINIO_ACCESS_KEY=... MINIO_SECRET_KEY=... ``` For SDK guides, see [MinIO (Python)](/python/vfs/minio) and [MinIO (TypeScript)](/typescript/setup/minio). # MongoDB Source: https://docs.mirage.strukto.ai/home/setup/mongodb Set up a MongoDB connection for the MongoDB VFS. ## Credentials ### 1. Get Your Connection URI #### Local MongoDB ```bash theme={null} # Default local instance MONGODB_URI=mongodb://localhost:27017 ``` #### MongoDB Atlas (Cloud) 1. Create a database user and allow the application host through **Network Access**. 2. Select your cluster, then **Connect** → **Drivers**. 3. Copy the connection URI, replace its username and password, and percent-encode special characters in the credentials: ``` mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/ ``` See the Atlas [connection guide](https://www.mongodb.com/docs/atlas/connect-to-database-deployment/). #### Self-hosted with Authentication ```bash theme={null} MONGODB_URI=mongodb://username:password@host:27017/?authSource=admin ``` ### 2. Set Environment Variables ```bash theme={null} # .env.development MONGODB_URI=mongodb+srv://user:pass@cluster0.xxxxx.mongodb.net/ ``` For SDK guides, see [MongoDB (Python)](/python/vfs/mongodb) and [MongoDB (TypeScript)](/typescript/setup/mongodb). # Nextcloud Source: https://docs.mirage.strukto.ai/home/setup/nextcloud Set up Nextcloud / ownCloud / WebDAV credentials for the Nextcloud VFS. ## Overview The Nextcloud VFS talks to any [WebDAV](http://www.webdav.org/specs/rfc4918.html) server: self-hosted Nextcloud, ownCloud, Hetzner Storage Share, or any generic WebDAV endpoint. Authentication is HTTP Basic with an **app password** (not your account password). ## Credentials ### 1. Pick a server Any of these works: * **Nextcloud Hosted trial** at [https://try.nextcloud.com](https://try.nextcloud.com) * **Self-hosted**: `docker run -p 8080:80 nextcloud` * **Hetzner Storage Share**, **ownCloud**, or any WebDAV server ### 2. Create an app password In your Nextcloud web UI: 1. Open **Settings** → **Security** → **Devices & sessions** 2. Enter an app name (e.g. `mirage`) and click **Create new app password** 3. Copy the generated password (shown once) Login password also works but **app passwords are strongly preferred** so you can revoke per-app access without changing your account password. ### 3. Find your WebDAV URL The standard Nextcloud path is: ```text theme={null} https://<your-server>/remote.php/dav/files/<username>/ ``` For example: `https://cloud.example.com/remote.php/dav/files/alice/`. For generic WebDAV servers, use whatever URL the provider gives. ### 4. Set environment variables ```bash theme={null} # .env.development NEXTCLOUD_URL=https://cloud.example.com/remote.php/dav/files/alice/ NEXTCLOUD_USERNAME=alice NEXTCLOUD_PASSWORD=<app-password> ``` For SDK configuration, see the [Nextcloud (Python)](/python/vfs/nextcloud) and [Nextcloud (TypeScript)](/typescript/setup/nextcloud) guides. # Notion Source: https://docs.mirage.strukto.ai/home/setup/notion Set up a Notion internal integration for the Notion VFS. ## Credentials ### 1. Create an Internal Integration 1. Go to [My Integrations](https://www.notion.com/my-integrations) 2. Click **+ New integration** 3. Name it (e.g. "mirage"), select your workspace 4. Under **Content Capabilities**, enable: * **Read content** (required) * **Update content** (for write commands) * **Insert content** (for creating pages and comments) 5. Click **Save changes** 6. Copy the **Internal Integration Secret** (starts with `ntn_`) ### 2. Share Pages with the Integration The integration has no access by default. You must share each page: 1. Open a Notion page you want to mount 2. Click `...` (top-right) -> **+ Add connections** 3. Search for your integration name and select it 4. Child pages inherit the connection - share a top-level page to expose its entire subtree ### 3. Set Environment Variables ```bash theme={null} # .env.development NOTION_API_KEY=ntn_xxxx... ``` For SDK guides, see [Notion (Python)](/python/vfs/notion) and [Notion (TypeScript)](/typescript/setup/notion). # OCI Object Storage Source: https://docs.mirage.strukto.ai/home/setup/oci Set up Oracle Cloud Infrastructure Object Storage credentials for the OCI VFS. ## Credentials The OCI VFS needs: * an Object Storage bucket * your Object Storage namespace * your OCI region * a Customer Secret Key pair for the S3 Compatibility API ### 1. Create a Bucket 1. Open the OCI Console 2. Go to `Storage` -> `Buckets` 3. Choose the target compartment 4. Click `Create bucket` 5. Enter the bucket name, such as `mirage` 6. Keep the storage tier as `Standard` unless you specifically want archive If you want MIRAGE data under a prefix like `data/`, create objects under that prefix inside the bucket. The prefix is not part of the bucket name. ### 2. Get the Namespace 1. Open the profile menu in the OCI Console 2. Go to `Tenancy` 3. Copy the Object Storage namespace string, such as `idsiqbdbcr4i` You can also fetch it with: ```bash theme={null} oci os ns get ``` ### 3. Get S3-compatible Keys 1. Open the profile menu 2. Go to `User settings` 3. Open `Customer secret keys` 4. Click `Generate secret key` 5. Copy both the `Access Key` and `Secret Key` Oracle only shows the secret once, so save it immediately. ### 4. Find the Region Use the OCI Console region selector in the top-right. For example: * `us-ashburn-1` * `us-phoenix-1` * `eu-frankfurt-1` ### 5. Set Environment Variables ```bash theme={null} # .env.development OCI_BUCKET=mirage OCI_NAMESPACE=idsiqbdbcr4i OCI_REGION=us-ashburn-1 OCI_ACCESS_KEY_ID=... OCI_SECRET_ACCESS_KEY=... ``` For SDK guides, see [OCI Object Storage (Python)](/python/vfs/oci) and [OCI Object Storage (TypeScript)](/typescript/setup/oci). # OneDrive Source: https://docs.mirage.strukto.ai/home/setup/onedrive Get a Microsoft Graph access token and drive ID for the OneDrive VFS. The OneDrive VFS talks to Microsoft OneDrive and SharePoint document libraries through the [Microsoft Graph API](https://learn.microsoft.com/en-us/graph/). It authenticates with an OAuth2 **bearer access token**, optionally scoped to a specific **drive**. ## Credentials You need an **access token** and, for app-only auth or a drive other than the signed-in user's default, one explicit drive selector. Pick whichever token path fits. ### Option A: Quick token (Graph Explorer) Fastest way to try it. The token lasts about an hour, which is plenty for a test run. 1. Open [Graph Explorer](https://developer.microsoft.com/graph/graph-explorer) and **Sign in**. 2. Run any query (for example `GET /me/drive`) and consent when prompted. 3. Open the **Access token** tab and copy the token. This is a **delegated** token, so it works against your own `/me/drive` and you do **not** need a drive ID. ### Option B: Interactive device-code token Use this to obtain a delegated token through your own app registration; the initial sign-in makes it a development bootstrap, not an unattended credential. 1. In the [Microsoft Entra admin center](https://entra.microsoft.com), go to **Identity** -> **Applications** -> **App registrations** -> **New registration**. For a personal account, choose *Accounts in any organizational directory and personal Microsoft accounts*. 2. Under **Authentication** -> **Advanced settings**, set **Allow public client flows** to **Yes**. 3. Under **API permissions** -> **Microsoft Graph** -> **Delegated**, add `Files.Read` for your own drive or `Files.ReadWrite` for writes. Other drives or SharePoint may require the corresponding `Files.*.All` or `Sites.*` scope. 4. Run the device-code flow with your **Application (client) ID**. For writes, replace `Files.Read` with `Files.ReadWrite` in the request below: ```bash theme={null} CLIENT_ID="<your app client id>" # 1) request a device code curl -s -X POST "https://login.microsoftonline.com/common/oauth2/v2.0/devicecode" \ -d "client_id=$CLIENT_ID" \ -d "scope=Files.Read offline_access" # -> open https://microsoft.com/devicelogin and enter the user_code it prints # 2) after you sign in, exchange the device_code for a token curl -s -X POST "https://login.microsoftonline.com/common/oauth2/v2.0/token" \ -d "grant_type=urn:ietf:params:oauth:grant-type:device_code" \ -d "client_id=$CLIENT_ID" \ -d "device_code=<device_code from step 1>" ``` The response includes access and refresh tokens. Mirage accepts an access token or provider callback but does not refresh Microsoft tokens itself, so a long-running application must refresh through that callback. ### Save the token for the examples ```bash theme={null} # .env.development MS_GRAPH_DRIVE_TOKEN=<token> MS_GRAPH_DRIVE_ID=<drive id> # optional; use at most one drive selector ``` For SDK configuration and the other drive selectors, see [Python OneDrive](/python/vfs/onedrive) or [TypeScript OneDrive](/typescript/setup/onedrive). ### Get your drive ID (optional) > [!NOTE] > > App-only tokens cannot use `/me/drive`; set one of `drive_id`, `site_id`, > `group_id`, or `user_id`. Delegated tokens can use `/me/drive` directly. Only needed when you use the `drive_id` selector. With your token exported as `TOKEN`: ```bash theme={null} # your personal OneDrive drive id curl -s -H "Authorization: Bearer $TOKEN" \ https://graph.microsoft.com/v1.0/me/drive | jq -r .id # list every drive you can see (name + id) curl -s -H "Authorization: Bearer $TOKEN" \ https://graph.microsoft.com/v1.0/me/drives | jq '.value[] | {name, id}' # a SharePoint site's drives curl -s -H "Authorization: Bearer $TOKEN" \ "https://graph.microsoft.com/v1.0/sites/{hostname}:/sites/{site-path}" | jq -r .id curl -s -H "Authorization: Bearer $TOKEN" \ "https://graph.microsoft.com/v1.0/sites/{site-id}/drives" | jq '.value[] | {name, id}' ``` The drive ID looks like `b!a1B2c3...`. > [!NOTE] > > Snapshots and version pinning rely on OneDrive/SharePoint **version history**, > which is on by default. Older versions are only readable while the library > retains them (the version cap is configurable, and an admin can disable > versioning). # OPFS Source: https://docs.mirage.strukto.ai/home/setup/opfs Keep workspace files in browser storage across page reloads. OPFS uses the browser's Origin Private File System. Files stay scoped to the current website's origin and persist across page reloads. Browser only; for Python or Node, use [Disk](/home/setup/disk). ## Configuration ```typescript theme={null} import { MountMode, OPFSVFS, Workspace } from '@struktoai/mirage-browser' const ws = new Workspace( { '/data': new OPFSVFS({ root: 'mirage' }) }, { mode: MountMode.WRITE }, ) await ws.shell('echo "hello" > /data/note.txt') await ws.close() ``` The browser controls storage quotas and may remove data under storage pressure. See the [OPFS guide](/typescript/setup/opfs#storage-and-quotas) for checking usage and requesting persistent storage. # Postgres Source: https://docs.mirage.strukto.ai/home/setup/postgres Set up a Postgres connection for the Postgres VFS. ## Credentials ### 1. Get Your Connection DSN #### Local Postgres ```bash theme={null} # Default local instance DATABASE_URL=postgres://postgres:postgres@localhost:5432/postgres ``` #### Managed Postgres (Supabase, Neon, RDS, ...) Copy the connection string from your provider's dashboard. It usually looks like: ``` postgres://<user>:<password>@<host>:5432/<database>?sslmode=require ``` ### 2. Set Environment Variables ```bash theme={null} # .env.development DATABASE_URL=postgres://user:pass@host:5432/db?sslmode=require ``` ## Permissions The Postgres VFS is read-only. Grant the role you connect with at minimum: ```sql theme={null} GRANT USAGE ON SCHEMA public TO mirage_reader; GRANT SELECT ON ALL TABLES IN SCHEMA public TO mirage_reader; ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO mirage_reader; ``` If you only want to expose a subset of schemas, set `schemas` in the VFS config: ```python theme={null} PostgresConfig(dsn=os.environ["DATABASE_URL"], schemas=["public", "analytics"]) ``` ## Limits The VFS has built-in safety limits to keep an agent from accidentally pulling a whole table: * `default_row_limit` (1,000): rows a windowed read returns when it passes an offset but no limit. * `max_read_rows` (10,000): hard ceiling per read. A whole read past it is refused (on the rows the table really has, not only on the planner's estimate); a `head -n` / `tail -n` count past it on a table that long is refused too (`File too large`); `wc -l` counts past it. * `max_read_bytes` (10 MiB): hard ceiling per read. Override in the config if you need bigger reads. # Qdrant Source: https://docs.mirage.strukto.ai/home/setup/qdrant Set up a Qdrant connection for the Qdrant VFS. [Qdrant](https://qdrant.tech/) mounts a collection as a read-only filesystem: group-by payload fields become nested folders, each point is a `.json` payload file (plus a `.txt` text file and an optional blob), and semantic search is the [`search` CLI](/home/setup/cli/search). ## Connection ### Local / self-hosted Point `host`/`port` at a running Qdrant (defaults `localhost:6333`): ```bash theme={null} # .env.development QDRANT_HOST=localhost QDRANT_PORT=6333 ``` ### Qdrant Cloud Use `url` plus an `api_key`: ```bash theme={null} # .env.development QDRANT_URL=https://xyz.us-east4-0.gcp.cloud.qdrant.io QDRANT_API_KEY=... ``` ## Search Search is the [`search` CLI](/home/setup/cli/search)'s `search "<query>" <path>`. It returns ranked points as their canonical `<id>.txt` (or `<id>.json`) file paths plus a similarity score, so results compose with `cat`, `wc`, and pipes (`grep`/`rg` stay lexical). The query text is turned into a vector two ways: * **In process:** pass an `embed` hook (text in, vector out) and your own model vectorizes the query, so a self-hosted Qdrant works. * **Server-side:** set `cloud_inference` to let a Qdrant Cloud (inference-enabled) cluster embed the query with `embedding_model` (default `sentence-transformers/all-MiniLM-L6-v2`). With neither, `search` refuses the query. Either way the collection must already store vectors produced by the same model. ## Limits The VFS is read-only and bounds how much an agent can pull: * `search_limit` (10): default top-k returned by `search`. * `max_rows` (1,000): hard ceiling on points listed per folder. Folder listings filter on payload fields. A filtered listing scrolls first and only creates keyword payload indexes for the `group_by` fields if Qdrant reports one is required. `max_rows` caps how many points are scanned per folder. For document/chunk collections, config field names accept dotted payload paths: use `group_by=["metadata.source"]`, `basename_fields=["metadata.source"]`, `name_field="metadata.page"`, and `text_field="page_content"` to expose a source-document folder with readable page/chunk filenames. TypeScript uses the camelCase equivalents `groupBy`, `basenameFields`, `nameField`, and `textField`. See the [Python](/python/vfs/qdrant) and [TypeScript](/typescript/setup/qdrant) VFS pages for full config. # QingStor Source: https://docs.mirage.strukto.ai/home/setup/qingstor Set up QingStor (QingCloud) Object Storage credentials for the QingStor VFS. ## Credentials ### 1. Create an access key 1. Sign in to the [QingCloud console](https://console.qingcloud.com/) 2. Go to **API Keys** (under your account) -> **Create** 3. Copy the **Access Key ID** and **Secret Access Key** 4. Note your bucket's **zone** (e.g. `pek3a`) and **bucket** name The endpoint is derived from the zone (`region`) as `s3.<region>.qingstor.com`, QingStor's S3-compatible host (distinct from the native `<zone>.qingstor.com`). Set `QINGSTOR_ENDPOINT_URL` to override. ### 2. Set environment variables ```bash theme={null} # .env.development QINGSTOR_BUCKET=my-bucket QINGSTOR_ZONE=pek3a QINGSTOR_ACCESS_KEY_ID=... QINGSTOR_SECRET_ACCESS_KEY=... # QINGSTOR_ENDPOINT_URL=https://s3.pek3a.qingstor.com # optional override ``` For SDK guides, see [QingStor (Python)](/python/vfs/qingstor) and [QingStor (TypeScript)](/typescript/setup/qingstor). # Cloudflare R2 Source: https://docs.mirage.strukto.ai/home/setup/r2 Set up Cloudflare R2 credentials for the R2 VFS. ## Credentials ### 1. Create R2 API Token 1. Go to [https://dash.cloudflare.com/](https://dash.cloudflare.com/) -> **R2 Object Storage** 2. **Manage R2 API Tokens** -> **Create API Token** 3. Set permissions: **Object Read** (or **Object Read & Write**) 4. Scope to your bucket 5. Copy the **Access Key ID** and **Secret Access Key** 6. Note your **Account ID** from the Cloudflare dashboard URL ### 2. Set Environment Variables ```bash theme={null} # .env.development R2_BUCKET=my-bucket R2_ACCOUNT_ID=abc123... R2_ACCESS_KEY_ID=... R2_SECRET_ACCESS_KEY=... ``` For SDK guides, see [Cloudflare R2 (Python)](/python/vfs/r2) and [Cloudflare R2 (TypeScript)](/typescript/setup/r2). # RAM Source: https://docs.mirage.strukto.ai/home/setup/ram Use temporary workspace files without installing a service or configuring credentials. RAM stores files in memory. Use it for scratch files, tests and trying Mirage. Files are lost when the application exits. Available in Python, Node and browsers. ## Configuration ```yaml theme={null} mounts: /data: vfs: ram mode: write ``` The mount starts empty. In Mirage's shell, create and read a file: ```bash theme={null} echo "hello" > /data/note.txt cat /data/note.txt ``` Add `capacity: 100MB` under `config` to cap the bytes it holds. See [capacity](/home/configuration#capacity). ## SDK guides * [Python RAM VFS](/python/vfs/ram) * [TypeScript RAM VFS](/typescript/setup/ram) * [TypeScript quickstart](/typescript/quickstart) * [Browser quickstart](/typescript/browser-quickstart) # Redis Source: https://docs.mirage.strukto.ai/home/setup/redis Store workspace files in Redis. Redis stores workspace files in a Redis database. Available in Python, Node, Cloudflare Workers and browsers. File persistence depends on the database's configuration. ## Configuration For Python, Node or Cloudflare Workers, set `url` to your Redis connection URL. Use `key_prefix` to keep this workspace's files separate from other data: ```yaml theme={null} mounts: /data: vfs: redis mode: write config: url: redis://localhost:6379/0 key_prefix: "mirage:fs:" ``` Add `capacity: 100MB` under `config` to cap the bytes the files hold. See [capacity](/home/configuration#capacity). Browsers connect through a compatible HTTP endpoint, such as Upstash REST. See [browser Redis setup](/typescript/setup/redis#browser) for configuration. ## SDK guides * [Python Redis VFS](/python/vfs/redis) * [TypeScript Redis setup](/typescript/setup/redis) # Custom runtime Source: https://docs.mirage.strukto.ai/home/setup/runtime/custom Run programs somewhere Mirage does not ship, such as your own execution service, by writing a runtime in Python or TypeScript and naming it from YAML. A runtime decides where a program runs. Write one when the agent's programs should run somewhere Mirage does not ship: your team's job runner, a GPU machine or a build farm. A runtime is a class that extends `Runtime`, names the programs it captures and implements one entry point. You ship it as a file next to your workspace YAML and name it by file and class: ```yaml theme={null} runtimes: - name: ./remote_runtime.py:RemoteRuntime # TypeScript: ./remote_runtime.mjs:RemoteRuntime config: url: ${EXEC_URL} token: ${EXEC_TOKEN} - workspace ``` The part before the colon is a file path, relative to the YAML file, or an importable module (`mypkg.runtimes:RemoteRuntime`). The part after it is the class. Mirage loads the file, checks that the class is a `Runtime` subclass and builds it with the entry's `captures` and `config`, like a runtime it ships. Loading runs the file's top-level code in the Mirage process, so name only code you trust. ## Runtime or CLI? A [CLI](/python/cli/custom) is a command Mirage implements: its spec, help and exit codes live in Mirage, and its handler calls a service through an accessor. A runtime is where Mirage hands off programs it does not implement: code the agent writes, or any binary. It answers "where does this run", not "what does this command do". To give the agent one command with a known interface, such as `deploy` or `tickets`, write a CLI. To choose where `python3`, `node` or any other program runs, write a runtime. ## Choose an entry point | Implement | Receives | For | | - | - | - | | `run_process` / `runProcess`, with `ProcessExecutorMixin` / `[PROCESS_EXECUTOR]` | one program's argv, as words | a service or machine that runs one program at a time | | `run_line` / `runLine`, with `LineExecutorMixin` / `[LINE_EXECUTOR]` | a whole shell line in `ctx.flags["c"]` | a shell of its own: a container, a VM, an SSH machine | | `interpret`, on a `LanguageRuntime` subclass | the code of a `python3` or `node` program | an interpreter Mirage calls with the program's source | A runtime captures the program names you give it. `@external` captures every program no builtin, CLI or other runtime claims, and `@line` takes every line. Interpreter names (`python3`, `python`, `node`, `js`) are never left over, so capture the ones you want by name or by group (`@python`, `@js`). Only a line executor can take `@line`, and only a line or process executor can take `@external`. A `LanguageRuntime` that is neither runs only its own language's names; naming another is refused when the workspace is built. ## Reach files through `ctx.vfs` The machine your runtime sends a program to cannot see a mount. Read and write workspace files through `ctx.vfs`, the session's files. Each call goes through the workspace dispatcher, so mount modes, profiles, policy and the cache apply to it as they apply to `cp`. A runtime that opens host paths directly skips all of them. Read with `raw` when you copy a file out to write it back: it returns the stored bytes, not a form a `filetype` registration renders. ## Example: an execution service This runtime sends each program to an HTTP execution service with a copy of the session's working directory, then writes back the files the program created or changed. The service runs the program in a scratch directory and answers with its output, exit code and changed files. The full example includes a small stand-in service, so it runs on one machine. > [tab] Python > > ```python remote_runtime.py theme={null} > import base64 > import posixpath > from dataclasses import dataclass > > import aiohttp > > from mirage import Context, ProcessExecutorMixin, RunResult, Runtime, RuntimeConfig > from mirage.runtime.constants import EXTERNAL_COMMANDS > > > @dataclass(frozen=True, slots=True) > class RemoteConfig(RuntimeConfig): > url: str = "" > token: str = "" > max_bytes: int = 16 * 1024 * 1024 > > > class RemoteRuntime(Runtime[aiohttp.ClientSession], ProcessExecutorMixin[aiohttp.ClientSession]): > name = "remote" > captures = ("python3", "python", "node", EXTERNAL_COMMANDS) > reach = "remote" > config_cls = RemoteConfig > config: RemoteConfig > > async def open_engine(self) -> aiohttp.ClientSession: > return aiohttp.ClientSession() > > async def close_engine(self, engine: aiohttp.ClientSession) -> None: > await engine.close() > > async def run_process(self, engine, paths, texts, ctx: Context, output=None, errors=None) -> RunResult: > cwd = ctx.cwd.virtual > files = await self._snapshot(ctx, cwd) > stdin = await self._stdin(ctx) # up to max_bytes, within the memory budget; see the full example > request = { > "argv": texts, > "stdin": base64.b64encode(stdin).decode(), > "files": {rel: base64.b64encode(data).decode() for rel, data in files.items()}, > } > headers = {"Authorization": f"Bearer {self.config.token}"} > async with engine.post(self.config.url, json=request, headers=headers) as resp: > resp.raise_for_status() > answer = await resp.json() > for rel, data in answer["files"].items(): > # The full example also creates missing folders first. > await ctx.vfs.write(posixpath.join(cwd, rel), base64.b64decode(data)) > return RunResult( > stdout=base64.b64decode(answer["stdout"]), > stderr=base64.b64decode(answer["stderr"]) or None, > exit_code=answer["exit_code"], > ) > > async def _snapshot(self, ctx: Context, cwd: str) -> dict[str, bytes]: > files, total, pending = {}, 0, [cwd] > mount = ctx.vfs.mount_of(cwd) > while pending: > for entry in await ctx.vfs.readdir(pending.pop()): > if ctx.vfs.mount_of(entry) != mount: > continue > if await ctx.vfs.is_dir(entry): > pending.append(entry) > continue > data = await ctx.vfs.read(entry, raw=True) > total += len(data) > if total > self.config.max_bytes: > raise ValueError(f"working directory is over {self.config.max_bytes} bytes") > files[posixpath.relpath(entry, cwd)] = data > return files > ``` > [tab] TypeScript > > ```javascript remote_runtime.mjs theme={null} > import { posix } from 'node:path' > import { EXTERNAL_COMMANDS, PROCESS_EXECUTOR, Runtime } from '@struktoai/mirage-node' > > export class RemoteRuntime extends Runtime { > [PROCESS_EXECUTOR] = true > name = 'remote' > reach = 'remote' > static configFields = { > url: { type: 'string' }, > token: { type: 'string' }, > maxBytes: { type: 'number' }, > } > > constructor(options = {}) { > super(options, ['python3', 'python', 'node', EXTERNAL_COMMANDS], RemoteRuntime.configFields) > } > > /** @param {import('@struktoai/mirage-node').Context} ctx */ > async runProcess(_engine, _paths, texts, ctx) { > const cwd = ctx.cwd.virtual > const maxBytes = this.config.maxBytes ?? 16 * 1024 * 1024 > const files = await snapshot(ctx, cwd, maxBytes) > const resp = await fetch(this.config.url, { > method: 'POST', > headers: { 'content-type': 'application/json', authorization: `Bearer ${this.config.token}` }, > body: JSON.stringify({ > argv: texts, > stdin: b64(await collect(ctx.stdin, maxBytes)), > files: Object.fromEntries(Object.entries(files).map(([rel, data]) => [rel, b64(data)])), > }), > signal: ctx.signal, > }) > if (!resp.ok) throw new Error(`execution service answered ${resp.status}`) > const answer = await resp.json() > for (const [rel, data] of Object.entries(answer.files)) { > // The full example also creates missing folders first. > await ctx.vfs.write(posix.join(cwd, rel), unb64(data)) > } > const stderr = unb64(answer.stderr) > return { stdout: unb64(answer.stdout), stderr: stderr.length > 0 ? stderr : null, exitCode: answer.exit_code } > } > } > > // snapshot() walks ctx.vfs.readdir from cwd within its mount and reads > // each file with { raw: true }; collect() reads stdin up to maxBytes; > // b64() and unb64() convert. All four are in the full example. > ``` The Python runtime opens one `aiohttp` session as its engine: `open_engine` runs once, at the first program, and `close_engine` when the workspace closes. The TypeScript one needs no engine, because `fetch` is global. In TypeScript the static `configFields` maps each config key the runtime accepts to its type (`string`, `number`, `boolean`, `list` or `map`), with `required`, `options` and `default` where they apply, and the constructor hands it to `super`; the keys arrive in camelCase (`max_bytes` in the YAML is `maxBytes`). In Python the config class's fields do the same. Either way, an unknown key in the YAML fails when the workspace loads, and a saved runtime's form shows these fields. With `/work` a writable RAM mount and `/archive` a read-only disk folder, each holding `report.py` and `orders.csv`: ```bash theme={null} $ cd /work && python3 report.py wrote summary.txt on the service: total 245 $ cat /work/summary.txt 3 orders, total 245 $ cd /work && python3 report.py | grep -o 'total [0-9]*' total 245 $ echo 'print(6 * 7)' | python3 - 42 $ cd /archive && python3 report.py python3: [Errno 30] Read-only file system: '/archive/summary.txt' $ timeout 1 python3 -c 'import time; time.sleep(30)' $ echo $? 124 ``` `python3` runs on the service while `cat`, `grep` and the pipe stay in the workspace. The output file comes back into the mount, stdin reaches the program, and the read-only mount refuses the write-back. The refusal's wording is the host's: TypeScript prints `python3: mount /archive/ is read-only`. The complete examples, with the YAML, the stand-in service and a script that runs these lines, are in [`examples/python/runtime/custom`](https://github.com/strukto-ai/mirage/tree/main/examples/python/runtime/custom) and [`examples/typescript/runtime/custom`](https://github.com/strukto-ai/mirage/tree/main/examples/typescript/runtime/custom). The stand-in service accepts work only with the token it was started with, and your real service should authenticate callers too: it runs whatever program it is sent. ## Stop when the run stops `timeout`, a closed session or a reader that stops early cancels the run. In Python the cancellation arrives as `asyncio.CancelledError` in your coroutine; in TypeScript, `ctx.signal` aborts. Pass the cancellation on to whatever runs the program, and make sure that stops it: * The example's request is cancelled with the run (`ctx.signal` in TypeScript), and the service kills the program when the connection drops. It starts each program in its own process group and kills the group, so children the program started stop too. * A runtime that spawns a process itself kills it and waits for it before it removes the process's files. * A process that exits without reading its input closes the pipe. In Node, give the child's `stdin` an `error` listener that treats `EPIPE` as that, not as a failure; without one, the stream error stops the host. ## What the copy holds The example sends the working directory's own mount, never a mount below it, so a run from `/` does not try to copy `/dev` or every other mount. It sends stdin whole too, because the service takes a run's input up front; it stops reading at `max_bytes`, so an endless producer fails the run with `stdin is over ... bytes` instead of hanging it. A service that streams input would feed stdin as it arrives instead. The example copies files out and writes them back whole. Two runs that change the same file at the same time each write back their own copy, and the later write replaces the earlier one. That is fine for one agent's sequential commands. A runtime shared by concurrent sessions should check that a file is unchanged before writing it back, or lock it for the run. ## Reach A runtime declares `reach`: `workspace` when `ctx.vfs` is its only way to files, `process` or `remote` when its code can act around that gate. The example declares `remote`: the program runs on another machine and can reach whatever that machine can. The default is `process`, so a runtime that does not declare its reach claims no promise. Embedders read it to decide whether "agent code cannot bypass mount modes and policy" holds for the workspace. ## Next [Routing](/home/setup/runtime/overview#routing) orders your runtime among the others, and [Route Runtime](/home/policy/route-runtime) picks one per command line. # Local Source: https://docs.mirage.strukto.ai/home/setup/runtime/local Run programs installed on your host with the Python or TypeScript SDK. `local` runs programs installed on your host, such as `python3`, `node`, `tsx`, `ffmpeg` or a vendor CLI. Add their names to `captures` to select them. A program sees the host's files and network, not the workspace mounts; to reach the mounts, give it a [FUSE folder](/home/setup/fuse). Nothing confines it; on Linux, [Sandlock](/home/setup/runtime/sandlock) does. Python SDK and Node only, and never in the default runtimes. ## Installation Install the programs you want to run on the host. `home` selects only the Python interpreter. Without it, Mirage uses `MIRAGE_LOCAL_HOME`, then the interpreter running Mirage (Python) or `python3` on `PATH` (Node). ## Usage `captures` defaults to `@python` (`python3` and `python`). Add names such as `node` or `tsx`, or [`@external`](/home/setup/runtime/overview#captures) for every program Mirage does not have itself. Mirage's own commands, pipes and redirects stay in Mirage: `ffmpeg -i in.mp4 out.webm | wc -c` sends only `ffmpeg`. > [tab] Python > > ```python theme={null} > from mirage import RAMVFS, MountMode, Workspace > from mirage.runtime.python import LocalRuntime > > ws = Workspace( > {"/data": RAMVFS()}, > mode=MountMode.EXEC, > runtimes=[LocalRuntime(captures=["@python", "@external"])], > ) > await ws.shell("python3 -c 'print(1 + 1)'; echo hi | cksum") > ``` > [tab] TypeScript > > ```typescript theme={null} > import { LocalRuntime, MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node' > > const ws = new Workspace( > { '/data': new RAMVFS() }, > { mode: MountMode.EXEC, runtimes: [new LocalRuntime({ captures: ['@python', '@external'] })] }, > ) > await ws.shell("python3 -c 'print(1 + 1)'; echo hi | cksum") > ``` > [tab] YAML > > ```yaml theme={null} > mode: exec > runtimes: > - name: local > captures: ["@python", "@external"] > config: > home: /path/to/venv/bin/python > mounts: > /data: > vfs: ram > ``` ## Connecting the workspace A local program opens host paths, not the workspace's. To give it workspace files, expose a mount as a [FUSE folder](/home/setup/fuse): ```yaml theme={null} mounts: /data: vfs: s3 config: bucket: my-bucket backend: fuse mountpoint: /data runtimes: - name: local captures: ["@python", "@external"] ``` After the folder is mounted, run the shared [workspace file check](/home/setup/runtime/overview#verify-workspace-file-access). * Put the folder at the mount's own path when you can, so a path typed in the shell names the same file in the program. * Calls into the folder follow mount modes and policies. A folder added in code with a session, `add_fuse_mount(prefix, mountpoint, session_id)` or `addFuseMount(prefix, mountpoint, sessionId)`, also follows that session's permissions. ## Python compatibility `python3` is the same Mirage command on every Python runtime: Mirage reads the script from the workspace and checks it like any file, and `local` runs it on the host's interpreter. Every other program is a plain host program. Python module availability and file modes come from the host interpreter. Mirage does not replace them with a subset. Workspace paths become host paths only when exposed through a FUSE folder. Examples below assume that folder is mounted at `/data`. ### `open()` Files are host files, including any FUSE folders. Modes and modifiers follow the host interpreter's Python version. | Mode or modifier | Support | | - | - | | `r` | Host interpreter | | `w` | Host interpreter | | `a` | Host interpreter | | `x` | Host interpreter | | `b` | Host interpreter | | `t` | Host interpreter | | `+` | Host interpreter | > [accordion] Example: append to a workspace file > > ```python theme={null} > with open("/data/log.txt", "a") as f: > f.write("Job completed.\n") > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | File access | Opens host files. Workspace files are accessible only through a mounted FUSE folder. | ### File objects | API | Support | | - | - | | File-object methods | Host interpreter | > [accordion] Example: write, read and truncate a file > > ```python theme={null} > with open("/data/example.txt", "w+") as f: > f.write("first\nsecond\n") > f.seek(0) > print(f.read(5)) # first > f.truncate(5) > ``` ### `os` | API | Support | | - | - | | Filesystem APIs | Host interpreter | | `os.environ` | ✓ | | `os.getcwd()` | ✓ | > [accordion] Example: list a workspace directory > > ```python theme={null} > import os > > print(os.listdir("/data")) > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | Filesystem APIs | Operate on host paths, including FUSE folders. | > | `os.environ` | The session's environment plus config `env`; none of the host's environment. | > | `os.getcwd()` | Starts in Mirage's own working directory. | ### `pathlib` | API | Support | | - | - | | `Path` | Host interpreter | > [accordion] Example: create and inspect a workspace file > > ```python theme={null} > from pathlib import Path > > path = Path("/data/example.txt") > path.write_text("hello\n") > print(path.read_text()) > print(path.stat().st_size) > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `Path` | Operates on host paths, including FUSE folders. | ### `sys` | API | Support | | - | - | | `sys.argv` | ✓ | | `sys.stdin` | ✓ | | `sys.path[0]` | Host interpreter | > [accordion] Example: read arguments and piped input > > ```python theme={null} > import sys > > print(sys.argv[1:]) > print(sys.stdin.read()) > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `sys.path[0]` | The host's working directory. | ### Runtime globals | API | Support | | - | - | | `__file__` | ✓ | * `__file__`: The script's workspace path; tracebacks use that path too. > [accordion] Example: print the script path > > ```python theme={null} > print(__file__) > ``` ## Runtime behavior | Capability | `python3` | Other programs | | - | - | - | | Program | The host's `python3`, given the script from the workspace | The name, found on the host's `PATH`; exit 127 if it is not there | | Arguments | `sys.argv` | Its argv, with no shell | | Piped input | stdin | stdin | | Environment | The session's, plus the config `env`; none of the host's | The same | | Working directory | Mirage's own | The shell's; exit 126 if it does not exist on the host | | Files | The host's, and FUSE folders | The host's, and FUSE folders | | Network | The host's | The host's | | Time | The workspace's [`system_time`](/home/configuration#system-time) when it sets one and libfaketime is installed, on Linux; otherwise the host's | The same | ## Notes * A workspace whose [`network`](/home/configuration#network) limits anything, or whose policies judge connections, runs nothing here: the program would connect around both. It answers `Permission denied`, exit 126\. * A timeout kills the subprocess. `kill` sends it the signal it names, then `KILL` a second later if it is still running. A program that handles the signal and exits gives `wait` its own exit status, as in Bash. # Monty Source: https://docs.mirage.strukto.ai/home/setup/runtime/monty A Python runtime in both Mirage SDKs, supporting a subset of Python. [Pydantic Monty](https://github.com/pydantic/monty) runs `python3` in both SDKs, including Node and browsers. It supports a subset of Python and works with workspace files under the same permissions as shell commands. Programs cannot access host files, host environment variables or the network. ## Installation > [tab] Python > > ```bash theme={null} > pip install 'mirage-ai[monty]' > ``` > [tab] TypeScript > > ```bash theme={null} > pnpm add @pydantic/monty > ``` ## Usage Name Monty in `runtimes` to run `python3` on it: > [tab] Python > > ```python theme={null} > from mirage import RAMVFS, MountMode, Workspace > > ws = Workspace({"/data": RAMVFS()}, mode=MountMode.EXEC, runtimes=["monty"]) > await ws.shell("python3 -c 'print(1 + 1)'") > ``` > [tab] TypeScript > > ```typescript theme={null} > import { MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node' > > const ws = new Workspace({ '/data': new RAMVFS() }, { mode: MountMode.EXEC, runtimes: ['monty'] }) > await ws.shell("python3 -c 'print(1 + 1)'") > ``` > [tab] YAML > > ```yaml theme={null} > mode: exec > runtimes: > - monty > mounts: > /data: > vfs: ram > ``` ## Memory Set `max_memory` to limit the Python program's memory per run, using a size such as `64M`: ```yaml theme={null} runtimes: - name: monty config: max_memory: 64M ``` A run that needs more raises `MemoryError`. A run also holds no more than its workspace's [`max_memory`](/home/core/output-limits#limit-a-workspaces-memory) has left, 96 MB by default. ## Python compatibility Support applies to both SDKs unless a row says otherwise. For Python syntax and standard-library coverage, see [Monty's limitations](https://pydantic.dev/docs/monty/limitations/). Examples assume a writable `/data` mount. Mount modes and permissions still apply. ### `open()` Modes and modifiers are listed separately; for example, `rb` combines `r` and `b`. | Mode or modifier | Support | | - | - | | `r` | ✓ | | `w` | ✓ | | `a` | ✓ | | `b` | ✓ | > [accordion] Example: append to a workspace file > > ```python theme={null} > with open("/data/log.txt", "a") as f: > f.write("Job completed.\n") > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `x` | Exclusive creation is not supported. | > | `+` | Read/write update modes (`r+`, `w+`, `a+`) are not supported. | ### File objects | API | Support | | - | - | | `f.read()` | ✓ | | `f.readline()` | ✓ | | `f.readlines()` | ✓ | | `f.seek()` | ✓ | | `f.tell()` | ✓ | | `f.write()` | ✓ | | `for line in f` | ✓ | > [accordion] Example: write and read lines > > ```python theme={null} > with open("/data/example.txt", "w") as f: > f.write("first\nsecond\n") > > with open("/data/example.txt", "r") as f: > print(f.readline()) # first > f.seek(0) > print(f.tell()) # 0 > print(f.readlines()) # ["first\n", "second\n"] > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | Reads and seeks | The whole file is loaded into memory; reads and seeks use that copy. | > | `f.truncate()` | ✗ | > | `f.fileno()` | ✗ | > | `f.write()` | Each call is written at once. | ### `os` The working directory and environment come from the Mirage session, not the host. #### File operations | API | Support | | - | - | | `os.remove()` | ✓ | | `os.unlink()` | ✓ | | `os.rename()` | ✓ | | `os.replace()` | ✓ | #### Directory operations | API | Support | | - | - | | `os.listdir()` | ✓ | | `os.scandir()` | ✓ | | `os.walk()` | ✓ | | `os.mkdir()` | ✓ | | `os.makedirs()` | ✓ | | `os.rmdir()` | ✓ | #### Metadata and links | API | Support | | - | - | | `os.stat()` | ✓ | #### Environment and working directory | API | Support | | - | - | | `os.getcwd()` | ✓ | | `os.chdir()` | Python SDK only | | `os.environ` | ✓ | | `os.getenv()` | ✓ | | `os.urandom()` | ✓ | > [accordion] Example: list a workspace directory > > ```python theme={null} > import os > > print(os.listdir("/data")) > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `os.open()` | ✗ | > | File descriptors | ✗ | > | `os.truncate()` | ✗ | > | `os.lstat()` | ✗ | > | `os.fstat()` | ✗ | > | `os.symlink()` | ✗ | > | `os.readlink()` | ✗ | > | `os.link()` | ✗ | > | `os.utime()` | ✗ | > | `os.chmod()` | ✗ | > | `os.getxattr()` | ✗ | > | `os.rename()`, `os.replace()` | Raises `OSError` across mounts. | > | `os.stat()` | In TypeScript, use named fields such as `st.st_size`. Whole-second timestamps may be integers. | > | `os.chdir()` | Lasts for the run. Raises `RuntimeError` in TypeScript. | > | `os.urandom()` | Up to 1 MiB per call. | ### `os.path` | API | Support | | - | - | | `os.path.exists()` | ✓ | | `os.path.isfile()` | ✓ | | `os.path.isdir()` | ✓ | | `os.path.islink()` | ✓ | | `os.path.getsize()` | Python SDK only | | `os.path.getmtime()` | Python SDK only | | `os.path.realpath()` | ✓ | | `os.path.join()`, `os.path.basename()`, `os.path.dirname()`, `os.path.splitext()` | ✓ | | `os.path.abspath()`, `os.path.relpath()`, `os.path.normpath()` | ✓ | > [accordion] Example: check a workspace path > > ```python theme={null} > import os > > path = os.path.join("/data", "input.txt") > print(os.path.exists(path), os.path.splitext(path)) > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `os.path.getsize()`, `os.path.getmtime()` | Raise `RuntimeError` in TypeScript. Use `os.stat(path).st_size` and `.st_mtime`. | ### `pathlib` `Path.cwd()` and relative path resolution use the shell's working directory. | API | Support | | - | - | | `Path.open()` | ✓ | | `Path.read_text()` | ✓ | | `Path.read_bytes()` | ✓ | | `Path.write_text()` | ✓ | | `Path.write_bytes()` | ✓ | | `Path.stat()` | ✓ | | `Path.exists()` | ✓ | | `Path.is_file()` | ✓ | | `Path.is_dir()` | ✓ | | `Path.is_symlink()` | ✓ | | `Path.iterdir()` | ✓ | | `Path.glob()` | ✓ | | `Path.rglob()` | ✓ | | `Path.walk()` | ✓ | | `Path.mkdir()` | ✓ | | `Path.rmdir()` | ✓ | | `Path.unlink()` | ✓ | | `Path.rename()` | ✓ | | `Path.cwd()` | ✓ | | `Path.resolve()` | ✓ | > [accordion] Example: create and inspect a workspace file > > ```python theme={null} > from pathlib import Path > > path = Path("/data/example.txt") > path.write_text("hello\n") > print(path.read_text()) > print(path.stat().st_size) > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `Path.touch()` | ✗ | > | `Path.stat()` | In TypeScript, use the named fields (`st.st_size`), not `st[6]`. | > | `Path.rename()` | Raises `OSError` across mounts. | ### `sys` Mirage passes command inputs through the [runtime globals](#runtime-globals). > [accordion] Example: use Mirage command inputs > > ```python theme={null} > print(argv[1:]) > print(stdin) > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `sys.argv` | Does not receive the invocation's arguments. Use `argv` instead. | > | `sys.stdin` | Not available. Use `stdin` for piped input. | ### `time` and `datetime` The clocks start at the workspace's [system time](/home/configuration#system-time) when it sets one, and files the program writes are stamped from the same clock. `time.monotonic()` and `time.perf_counter()` measure elapsed time. | API | Support | | - | - | | `time.time()`, `time.time_ns()` | ✓ | | `time.localtime()`, `time.gmtime()`, `time.strftime()` | ✓ | | `time.monotonic()`, `time.perf_counter()` | ✓ | | `datetime.datetime.now()` | ✓ | | `datetime.date.today()` | ✓ | > [accordion] Example: print today's date > > ```python theme={null} > import datetime > > print(datetime.date.today()) > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | Local times | The session's `TZ`, UTC without one. | ### `json` JSON parsing and serialization come from Monty; see its [`json` reference](https://pydantic.dev/docs/monty/limitations/json/). | API | Support | | - | - | | `json.load()` | ✓ | | `json.dump()` | ✓ | | `json.loads()` | ✓ | | `json.dumps()` | ✓ | > [accordion] Example: write and read workspace JSON > > ```python theme={null} > import json > > with open("/data/result.json", "w") as f: > json.dump({"status": "done"}, f) > > with open("/data/result.json") as f: > print(json.load(f)["status"]) > ``` ### `csv`, `tomllib` and `hashlib` These modules read and write workspace files through `open()`. | API | Support | | - | - | | `csv.reader()`, `csv.DictReader()` | ✓ | | `csv.writer()` | ✓ | | `tomllib.load()` | ✓ | | `hashlib` | ✓ | > [accordion] Example: read a workspace CSV > > ```python theme={null} > import csv > > with open("/data/orders.csv", newline="") as f: > for row in csv.DictReader(f): > print(row["id"], row["total"]) > ``` ### Runtime globals | API | Support | | - | - | | `argv` | ✓ | | `stdin` | ✓ | | `__file__` | ✓ | * `argv`: The invocation name and arguments. * `stdin`: The piped input. * `__file__`: The script's name under the starting directory. > [accordion] Example: read invocation inputs > > ```python theme={null} > print(argv) > print(stdin) > ``` ## Notes * A run starts in the shell's working directory. The script and every relative path pass the same mount and permission checks as `cat`: a rule protecting `/data/job.py` refuses `python3 job.py` from `/data`. * Script arguments follow shell expansion, including globs. * A console session takes the working directory on its first input and keeps its own after that. * `raise SystemExit` exits successfully. `raise SystemExit("message")` exits with status 1 and prints the message. ## Python subset Monty 1.4.0 implements a subset of Python, and Mirage never falls back to another interpreter. Monty maintains the details of its [standard-library modules](https://pydantic.dev/docs/monty/limitations/modules/) and [language limitations](https://pydantic.dev/docs/monty/limitations/language/). Those pages track upstream Monty; the integration tables above describe the version used by Mirage. Third-party imports are unavailable. ## Unsupported modules Common modules unavailable in Monty 1.4.0: * **Files:** `glob`, `io`, `shutil`, `tempfile`. * **Networking:** `http`, `socket`, `ssl`, `urllib`. * **Processes and concurrency:** `concurrent.futures`, `multiprocessing`, `queue`, `subprocess`, `threading`. * **Data formats and archives:** `array`, `pickle`, `struct`, `zipfile`, `zlib`. * **Numbers and hashing:** `fractions`, `hmac`, `uuid`. * **Language and introspection:** `abc`, `contextlib`, `ctypes`, `importlib`, `inspect`, `types`, `weakref`. * **CLI and diagnostics:** `argparse`, `logging`, `traceback`, `unittest`, `warnings`. * **Other utilities:** `enum`, `heapq`, `operator`, `string`. # Runtimes Source: https://docs.mirage.strukto.ai/home/setup/runtime/overview Choose where Python, JavaScript and other programs run and which files they can access. A runtime runs the programs in a line. Mirage's own commands (`grep`, `cat`, pipes, redirects) run in the workspace itself; `python3`, `node` and any other program go to the runtime that captures them. Each runtime reaches the workspace's files its own way. ![Monty, WASI, Pyodide and QuickJS access workspace files directly. Host programs use a FUSE folder. Machines connect through SSH or FUSE.](https://mintcdn.com/struktoai/DFcmqNyceJW-5m2z/images/runtime-light.svg?fit=max\&auto=format\&n=DFcmqNyceJW-5m2z\&q=85\&s=c80ddf8b7c3cda1efb8ec7e85c38d8f9) | Runtime | Runs | Where | SDK | | - | - | - | - | | `workspace` | Mirage's own commands | Mirage workspace | both | | [`monty`](/home/setup/runtime/monty) | `python3`, a Python subset | Mirage workspace | both | | [`wasi`](/home/setup/runtime/wasi) | `python3`, CPython in WebAssembly | Mirage workspace | Python | | [`pyodide`](/home/setup/runtime/pyodide) | `python3`, CPython in WebAssembly | Mirage workspace | TypeScript | | [`quickjs`](/home/setup/runtime/quickjs) | `node` and `js`, with Node.js's common APIs | Mirage workspace | both | | [`local`](/home/setup/runtime/local) | host programs such as `python3`, `node` or `tsx` | host | Python, Node | | [`machine`](/home/setup/machine/overview) | native programs | a [machine](/home/setup/machine/overview): a container, VM, cloud sandbox or SSH host | Python, Node; E2B also in the browser | | [`sandlock`](/home/setup/runtime/sandlock) | native programs | this Linux host, confined | Python, Node | ## Routing `runtimes` is an ordered list: the first runtime whose `captures` name a program runs it, and `workspace` takes the rest. Without the key, the list is `[workspace]` on every host, so `python3`, `node` and `js` answer `command not found` (exit 127) until an entry captures them. [Cloudflare Workers](/typescript/cloudflare-quickstart) runs no QuickJS. ```yaml theme={null} machines: box: provider: docker container: my-sandbox mount_type: ssh runtimes: - monty - name: remote machine: box - workspace ``` An entry is a name, or a mapping with `name`, `captures` and `config`; a `machine` entry names its `machine` instead of taking `config`. The name is a runtime Mirage ships, one you registered in code, or a `./file.py:Class` (Python) or `./file.mjs:Class` (TypeScript) reference to [your own runtime](/home/setup/runtime/custom). Config keys are snake\_case in YAML for both SDKs, and a runtime rejects a key it does not know. To choose a runtime for each command line, see [Route Runtime](/home/policy/route-runtime). ## Captures `captures` lists the programs a runtime takes: | Entry | Takes | | - | - | | A name, such as `python3` or `ffmpeg` | That program | | `@python`, `@js` | `python3` and `python`, or `node` and `js` | | `@external` | Every program Mirage does not have itself, such as `gcc`, `ffmpeg`, `perl` or a vendor CLI | | `@line` | The whole line, Mirage's own commands included (any runtime that runs a shell line) | | Runtime | Default `captures` | | - | - | | `monty`, `wasi`, `pyodide`, `local` | `@python` | | `quickjs` | `@js` | | `sandlock`, `machine` | `@external` | * Mirage's own commands (`cat`, `grep`, `sha1sum`), pipes and redirects stay in Mirage. Name `cat`, `grep`, `ps` or `kill` to run it on a runtime instead; `cd`, `export`, `echo`, `ln`, functions and installed CLIs stay in Mirage even when named. * `@external` does not take `python`, `python3`, `node` or `js`: Mirage has those itself and gives them to the Python or JavaScript runtime in the list. Name them, or `@python` or `@js`, to send them somewhere else. A tool such as `pip` is an ordinary program: capture it on the same runtime when packages must land there, as in `captures: ["@python", "pip", "pip3"]`. * `monty`, `wasi`, `pyodide` and `quickjs` take only their own interpreter's names; naming another program on one is refused when the workspace is built. `local`, `sandlock` and `machine` take any name. * Mirage matches the program each command really runs, after expanding its words, so `python3` is captured in `$P x`, `env python3 x`, `timeout 5 python3 x`, `sh -c 'python3 x'` and `xargs python3`. Each command on a line matches on its own, so `cat a.txt | python3 x` sends only `python3`. * `nice`, `nohup`, `stdbuf`, `ionice` and `setsid` run their program where it runs alone: `nice gcc x.c` where `gcc` is taken, `nice grep` in Mirage. On a runtime the wrapper goes with it, and permission rules and a `pre_command` route answer for the program. * An absolute path Mirage has no file for, such as `/usr/bin/ffmpeg`, goes to the `@external` runtime. A profile's `commands.allow` refuses it, since the list can only name what it can read. * Under `local`, `sandlock` and `machine`, a program a captured program starts runs there: `make` running `gcc`, or a script calling `subprocess`. Capture the launcher on the same runtime as the tool. A Pyodide script's `subprocess` calls go back through Mirage's routing like any other command. * An alias is captured as the word it expands to, once `shopt -s expand_aliases` is on and the alias was defined on an earlier line. * If two runtimes take the same name or group, the first wins and Mirage logs a warning. * A program no runtime takes exits 127, `command not found`. * A `workspace` entry with `captures` runs only those mount commands itself: another mount command, such as `ls`, exits 126, `no runtime accepted this line`, and an unknown program exits 127. The shell's own words (`cd`, `export`, `echo`) still run. * A name only `@external` takes has no file, so `which`, `command -v` and `type` report it missing; running it still works. * Globs expand against the workspace first (`python3 job.py *.csv` runs `python3 job.py a.csv b.csv`), and permission rules judge that argv. ```yaml theme={null} machines: box: provider: docker container: my-sandbox runtimes: - name: remote captures: ["@python", "@external"] machine: box ``` Here `python3 job.py | grep error` runs `python3` in the container and `grep` in Mirage, and `ffmpeg -i a.mp4 b.webm` runs in the container. ## Files | Where | Reaches the workspace through | Outside the workspace | | - | - | - | | Monty, WASI, QuickJS | directly | no host files or network | | Pyodide | directly | Browser programs retain JavaScript and network access; `init_module` enables host access. See [containment](/typescript/runtime/python#containment). | | `local`, Sandlock | a [FUSE folder](/home/setup/fuse) you mount | the host's disk and network; under Sandlock, only the paths you grant | | `machine` | SFTP and `sshfs` with `mount_type: ssh` (`docker`, `e2b`, `ssh`, `kubernetes`, `smolvm`, `apple_container`, `microsandbox`), or a Mirage inside the machine | that machine's disk and network | Mount modes, profiles and policies apply to every file call that reaches the workspace. A host runtime or a machine also has its own files and network, which they do not cover. Pyodide has its own containment limits; use a machine with a process and kernel boundary for hostile code. ### Verify workspace file access Run these lines inside Mirage's shell after configuring a writable `/data` mount visible to the runtime capturing `python3`. They check that Python can read a workspace file and write one back: ```bash theme={null} ( scratch=$(mktemp /data/mirage-check.XXXXXX) || exit trap 'rm -f -- "$scratch"' EXIT printf 'hello\n' > "$scratch" && MIRAGE_CHECK_FILE="$scratch" python3 -c 'import os; from pathlib import Path; path = Path(os.environ["MIRAGE_CHECK_FILE"]); text = path.read_text(); path.write_text(text.upper()); print(text, end="")' && cat "$scratch" ) # hello # HELLO ``` Monty, WASI, Pyodide and QuickJS access workspace files automatically. For `local` and Sandlock, first mount a [FUSE folder](/home/setup/fuse). For a machine, finish its provider page's **Connecting the workspace** steps first. ## Resource limits `command_limits` apply to a runtime's programs as to any command: a line past its `@line` entry's `timeout_seconds` exits 124 (`line: timed out after Ns`), and `max_bytes` and `max_lines` cap a program's output. ```yaml theme={null} command_limits: "@line": timeout_seconds: 30 ``` The deadline also stops the run in Monty, WASI, Pyodide, QuickJS, `local`, Sandlock and on a machine; see [machine timeouts](/home/setup/machine/overview#timeouts) for what a machine needs. If a host or remote runtime cannot enforce the session's file restrictions, Mirage refuses to launch the program as a policy refuses a command: `<runtime>: Permission denied`, exit 126. See [machine file permissions](/home/setup/machine/overview#ssh) for restrictions that affect runtime selection. # Pyodide Source: https://docs.mirage.strukto.ai/home/setup/runtime/pyodide Run Python and packages such as numpy in the TypeScript SDK, in Node and browsers. [Pyodide](https://pyodide.org) runs Python with packages such as numpy in Node and browsers. Workspace file access follows the same permissions as shell commands, and each command starts with fresh Python state. TypeScript SDK only. Pyodide does not provide isolation for hostile code. Host and network access depend on the environment and configuration; see [containment](/typescript/runtime/python#containment) before choosing it for untrusted programs. ## Installation ```bash Node theme={null} pnpm add @struktoai/mirage-node @struktoai/mirage-core pyodide ``` In a browser, install `@struktoai/mirage-browser` and `@struktoai/mirage-core` instead: Pyodide loads from its CDN or `home`, not the `pyodide` package. The page must be cross-origin isolated or registered with Mirage's service worker; see [worker and browser setup](/typescript/runtime/python#worker-and-browser-setup). ## Usage > [tab] TypeScript > > ```typescript theme={null} > import { MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node' > > const ws = new Workspace({ '/data': new RAMVFS() }, { mode: MountMode.EXEC, runtimes: ['pyodide'] }) > try { > const inline = await ws.shell("python3 -c 'print(1 + 1)'") > console.log(inline.stdoutText) // 2 > > await ws.shell(`echo 'import sys; print(sys.argv[1:])' > /data/hello.py`) > const script = await ws.shell('python3 /data/hello.py alice bob') > console.log(script.stdoutText) // ['alice', 'bob'] > > const piped = await ws.shell("echo 'print(1 + 1)' | python3") > console.log(piped.stdoutText) // 2 > } finally { > await ws.close() > } > ``` > [tab] YAML > > ```yaml theme={null} > mode: exec > runtimes: > - pyodide > mounts: > /data: > vfs: ram > ``` ## Packages [Pyodide's packages](https://pyodide.org/en/stable/usage/packages-in-pyodide.html), such as numpy, load when a program imports them. The first import downloads the package from the Pyodide CDN; Node keeps it beside the installed `pyodide` package for later runs. | Config key | What it does | | - | - | | `packages` | Load these when each interpreter starts, before the program runs. | | `auto_load_from_imports` | Load what a program imports. Default `true`; `false` loads only `packages`. | | `deny_packages` | Never download these for an import. An import still works when the package is reachable another way, such as through `sys_path`. | | `sys_path` | Mount paths to put first on `sys.path`: directories, globs, or pure-Python `.whl` files. | | `package_base_url` | Where packages download from; point it at your own copy to work offline. | > [tab] TypeScript > > ```typescript theme={null} > import { MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node' > import { PyodideRuntime } from '@struktoai/mirage-core/runtime/python/pyodide' > > const runtime = new PyodideRuntime({ > config: { > packages: ['numpy'], > denyPackages: ['requests'], > sysPath: ['/data/vendor', '/data/wheels/*.whl'], > }, > }) > const ws = new Workspace({ '/data': new RAMVFS() }, { mode: MountMode.EXEC, runtimes: [runtime] }) > ``` > [tab] YAML > > ```yaml theme={null} > mode: exec > runtimes: > - name: pyodide > config: > packages: [numpy] > deny_packages: [requests] > sys_path: [/data/vendor, /data/wheels/*.whl] > mounts: > /data: > vfs: ram > ``` A package from PyPI cannot be installed at run time: `micropip.install` fails. Put its pure-Python wheel on a mount and list it in `sys_path`. ## Memory `max_memory` caps the memory one run may grow to: ```yaml theme={null} runtimes: - name: pyodide config: max_memory: 256M ``` A run starts at about 50M. One that passes the cap fails with `MemoryError`, and the next run starts fresh. Node stops the run when it passes the cap; browsers check the cap when the run ends. Without its own `max_memory`, a run may grow by what its workspace's [`max_memory`](/home/core/output-limits#limit-a-workspaces-memory) has left, 96 MB by default, past what the interpreter and its packages take to start. ## Python compatibility Examples assume a writable `/data` mount. Mount modes and permissions still apply. ### `open()` Modes and modifiers are listed separately; for example, `rb` combines `r` and `b`. The file is read when it is opened. | Mode or modifier | Support | | - | - | | `r` | ✓ | | `w` | ✓ | | `a` | ✓ | | `x` | ✓ | | `b` | ✓ | | `t` | ✓ | | `+` | ✓ | > [accordion] Example: append to a workspace file > > ```python theme={null} > with open("/data/log.txt", "a") as f: > f.write("Job completed.\n") > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | File access | Writes to workspace files follow mount permissions. Files created outside the mounts stay in memory and are lost when the run ends. | ### File objects | API | Support | | - | - | | `f.read()` | ✓ | | `f.write()` | ✓ | | `f.truncate()` | ✓ | > [accordion] Example: write, read and truncate a file > > ```python theme={null} > with open("/data/example.txt", "w+") as f: > f.write("first\nsecond\n") > f.seek(0) > print(f.read(5)) # first > f.truncate(5) > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `f.write()` | Written at close, or at the next call that reaches a mount. | ### `os` #### File operations | API | Support | | - | - | | `os.open()` | ✓ | | `os.read()` | ✓ | | `os.pread()` | ✓ | | `os.write()` | ✓ | | `os.pwrite()` | ✓ | | `os.truncate()` | ✓ | | `os.remove()` | ✓ | | `os.unlink()` | ✓ | | `os.rename()` | ✓ | | `os.replace()` | ✓ | #### Directory operations | API | Support | | - | - | | `os.listdir()` | ✓ | | `os.scandir()` | ✓ | | `os.walk()` | ✓ | | `os.mkdir()` | ✓ | | `os.makedirs()` | ✓ | | `os.rmdir()` | ✓ | #### Metadata and links | API | Support | | - | - | | `os.stat()` | ✓ | | `os.lstat()` | ✓ | | `os.fstat()` | ✓ | | `os.symlink()` | ✓ | | `os.readlink()` | ✓ | | `os.utime()` | ✓ | | `os.chmod()` | ✓ | | `os.getxattr()` | ✓ | | `os.setxattr()` | ✓ | | `os.listxattr()` | ✓ | | `os.removexattr()` | ✓ | #### Environment and working directory | API | Support | | - | - | | `os.getcwd()` | ✓ | | `os.chdir()` | ✓ | | `os.environ` | ✓ | > [accordion] Example: list a workspace directory > > ```python theme={null} > import os > > print(os.listdir("/data")) > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `os.fsync()` | Accepted, but has no effect. | > | `os.link()` | Does not exist. | > | `os.open()` | The file is read when it is opened. | > | `os.write()`, `os.pwrite()` | Written at close, or at the next call that reaches a mount. | > | `os.rename()`, `os.replace()` | `EXDEV` across mounts, where `shutil.move` copies instead. | > | `os.getxattr()`, `os.setxattr()`, `os.listxattr()`, `os.removexattr()` | The same attributes as `getfattr` in the shell. | > | `os.getcwd()`, `os.chdir()` | The shell's working directory; a change lasts for the run. | > | `os.environ` | The session's environment, never the host's. | ### `os.path` | API | Support | | - | - | | `os.path` | ✓ | > [accordion] Example: check a workspace path > > ```python theme={null} > import os.path > > path = os.path.join("/data", "input.txt") > print(os.path.exists(path)) > ``` ### `pathlib` | API | Support | | - | - | | `Path.stat()` | ✓ | | `Path.glob()` | ✓ | | `Path.unlink()` | ✓ | | `Path.touch()` | ✓ | > [accordion] Example: create and inspect a workspace file > > ```python theme={null} > from pathlib import Path > > path = Path("/data/example.txt") > path.write_text("hello\n") > print(path.read_text()) > print(path.stat().st_size) > ``` ### `sys` | API | Support | | - | - | | `sys.argv` | ✓ | | `sys.stdin` | ✓ | > [accordion] Example: read arguments and piped input > > ```python theme={null} > import sys > > print(sys.argv[1:]) > print(sys.stdin.read()) > ``` ### `time` and `datetime` The clocks start at the workspace's [system time](/home/configuration#system-time) when it sets one, and files the program writes are stamped from the same clock. `time.monotonic()` and `time.perf_counter()` measure elapsed time. | API | Support | | - | - | | `time.time()`, `time.time_ns()` | ✓ | | `time.localtime()`, `time.gmtime()`, `time.strftime()` | ✓ | | `time.monotonic()`, `time.perf_counter()` | ✓ | | `datetime.datetime.now()` | ✓ | | `datetime.date.today()` | ✓ | > [accordion] Example: print today's date > > ```python theme={null} > import datetime > > print(datetime.date.today()) > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | Local times | The session's `TZ`, UTC without one. `time.tzname` spells a zone as its offset, such as `UTC+0900`. | ### `json` | API | Support | | - | - | | `json.load()` | ✓ | > [accordion] Example: write and read workspace JSON > > ```python theme={null} > import json > > with open("/data/result.json", "w") as f: > json.dump({"status": "done"}, f) > > with open("/data/result.json", "r") as f: > result = json.load(f) > print(result["status"]) # done > ``` ### `glob` | API | Support | | - | - | | `glob.glob()` | ✓ | > [accordion] Example: find workspace text files > > ```python theme={null} > import glob > > print(glob.glob("/data/*.txt")) > ``` ### `shutil` | API | Support | | - | - | | `shutil.rmtree()` | ✓ | | `shutil.move()` | ✓ | | `shutil.which()` | ✓ | * `shutil.which()`: Resolves executable names through Mirage's command lookup. > [accordion] Example: move a workspace file > > ```python theme={null} > import shutil > > with open("/data/draft.txt", "w") as f: > f.write("ready\n") > > shutil.move("/data/draft.txt", "/data/final.txt") > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `shutil.move()` | Copies instead when a rename would cross mounts (`EXDEV`). | ### `subprocess` | API | Support | | - | - | | `subprocess.run()` | ✓ | | `subprocess.Popen()` | ✓ | > [accordion] Example: run a Mirage command > > ```python theme={null} > import subprocess > > result = subprocess.run( > ["ls", "/data"], capture_output=True, text=True, check=True > ) > print(result.stdout) > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `subprocess.run()`, `subprocess.Popen()` | Runs commands inside Mirage. Pending file writes are saved before the command starts. | > | `Popen.send_signal()`, `terminate()`, `kill()` | Sends the signal as `kill` does. A command that ends on it reports a negative `returncode`. | ### Processes and signals | API | Support | | - | - | | `os.getpid()`, `os.getppid()` | ✓ | | `os.kill()`, `signal.raise_signal()` | ✓ | | `signal.signal()` | ✓ | > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `os.getpid()`, `os.getppid()` | Return the numbers `ps` and `$!` show. | > | `os.kill()` | Reaches the program itself and the commands it started. Any other pid raises `ProcessLookupError`. | > | `signal.signal()` | A handler runs when `kill` sends the signal. A program inside a file operation runs it when the operation ends. | ### `socket` Network connections are unavailable in this runtime. > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `socket` | Cannot connect (`ENETUNREACH`). | ### `mmap` Unavailable in this runtime. > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `mmap` | ✗ | ## Notes Files written outside the mounts stay in memory and are lost when the run ends. # QuickJS Source: https://docs.mirage.strukto.ai/home/setup/runtime/quickjs Run JavaScript scripts and pipe transforms in both Mirage SDKs. QuickJS runs `node` and `js` in both SDKs. It supports ES2023 for small scripts and pipe transforms, with access to workspace files under the same permissions as shell commands. Node.js's most used APIs are laid over the engine: `fs`, `path`, `process`, `Buffer`, `require`, the timers and Node's `console`. It has no npm packages and no network access. Both SDKs run the same engine, the WASI build of [quickjs-ng](https://github.com/quickjs-ng/quickjs), so a script answers the same in either. ## Installation Download `qjs-wasi.wasm` from a [quickjs-ng release](https://github.com/quickjs-ng/quickjs/releases) and point the runtime's `home`, or `MIRAGE_QUICKJS_HOME`, at its directory. > [tab] Python > > ```bash theme={null} > pip install 'mirage-ai[quickjs]' > ``` > [tab] TypeScript > > No package to add: each run executes in a worker. In a browser, `home` > is the URL of the folder holding `qjs-wasi.wasm`, and the page needs the > same [worker setup](/typescript/runtime/python#worker-and-browser-setup) > as Pyodide. > > QuickJS does not run on Cloudflare Workers: with no worker to stop it, > a script that never calls the host would hold the isolate, as the > [Cloudflare quickstart](/typescript/cloudflare-quickstart#run-a-workspace) > describes. ## Usage Name QuickJS in `runtimes` to run `node` on it once its engine is found: > [tab] Python > > ```python theme={null} > from mirage import RAMVFS, MountMode, Workspace > from mirage.runtime.js import QuickJsRuntime > > ws = Workspace( > {"/data": RAMVFS()}, > mode=MountMode.EXEC, > runtimes=[QuickJsRuntime(config={"home": "/path/to/quickjs"})], > ) > await ws.shell("node -e 'console.log(1 + 1)'") > ``` > [tab] TypeScript > > ```typescript theme={null} > import { buildRuntime, MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node' > > const ws = new Workspace( > { '/data': new RAMVFS() }, > { > mode: MountMode.EXEC, > runtimes: [buildRuntime('quickjs', { config: { home: '/path/to/quickjs' } })], > }, > ) > await ws.shell("node -e 'console.log(1 + 1)'") > ``` > [tab] YAML > > ```yaml theme={null} > mode: exec > runtimes: > - name: quickjs > config: > home: /path/to/quickjs > mounts: > /data: > vfs: ram > ``` ## Memory A run holds no more than its workspace's [`max_memory`](/home/core/output-limits#limit-a-workspaces-memory) has left, 96 MB by default. A program that needs more gets `InternalError: out of memory`. ## JavaScript compatibility `std` and `os` are globals, as `qjs --std` gives them. Examples assume a writable `/data` mount. Mount modes and permissions still apply. ### `std.open()` `std.open(path, mode, errorObj)` returns `null` on failure and sets `errorObj.errno`. A read-only mount refuses modes that write. The modes are `r`, `w`, `a` and `x`, with the `b` and `+` modifiers; for example, `rb` combines `r` and `b`. > [accordion] Example: append to a workspace file > > ```javascript theme={null} > const error = {}; > const file = std.open("/data/log.txt", "a", error); > if (file === null) { > throw new Error("Open failed: " + error.errno); > } > try { > file.puts("Job completed.\n"); > } finally { > file.close(); > } > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `x` | Exclusive-creation modifier: use `wx` or `ax`; `x` alone is not a valid mode. | > | Write modes | A read-only mount refuses modes that write. | ### File objects `readAsString()`, `read()`, `getline()`, `seek()`, `tell()`, `tello()`, `eof()`, `puts()`, `write()`, `printf()`, `flush()` and `close()`. > [accordion] Example: write, seek and read a file > > ```javascript theme={null} > const file = std.open("/data/example.txt", "w+"); > if (file === null) { > throw new Error("Could not open example.txt"); > } > try { > file.puts("hello\n"); > file.seek(0, std.SEEK_SET); > print(file.readAsString()); > } finally { > file.close(); > } > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `file.puts()`, `file.write()`, `file.flush()` | Reach the mount at `close`, or when the run ends; a write the mount refuses fails the `close`. | ### `std` `getenv()`, `setenv()`, `getenviron()`, `exit()`, `loadFile()`, `writeFile()`, `printf()`, `fdopen()`, `strerror()` and `Error`. Environment variables come from the Mirage session. `std.loadFile()` returns `null` when reading fails. > [accordion] Example: read a session environment variable > > ```javascript theme={null} > const jobId = std.getenv("JOB_ID"); > std.printf("Job: %s\n", jobId === undefined ? "unknown" : jobId); > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `std.popen()` | ✗ | > | `std.tmpfile()` | ✗ | ### Standard streams `std.in` receives the command's piped input as it arrives, and `std.in`, `std.out` and `std.err` are descriptors 0 to 2. > [accordion] Example: forward piped input > > ```javascript theme={null} > const input = std.in.readAsString(); > std.out.puts(input); > std.err.puts("Input forwarded.\n"); > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `std.out.printf()`, `std.err.printf()` | C format; return the UTF-8 bytes written. Unlike `printf` on an opened FILE. | ### `os` `readdir()`, `stat()`, `mkdir()`, `remove()`, `utimes()`, `rename()`, `getcwd()`, `chdir()`, `open()`, `read()`, `write()`, `seek()`, `close()`, `sleep()`, `setTimeout()` and `platform`. > [accordion] Example: list a workspace directory > > ```javascript theme={null} > const [names, errno] = os.readdir("/data"); > if (errno !== 0) { > throw new Error("Read directory failed: " + errno); > } > console.log(names); > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `os.lstat()` | ✗ | > | `os.symlink()` | ✗ | > | `os.readlink()` | ✗ | > | `os.realpath()` | ✗ | > | `os.exec()` | ✗ | > | `os.readdir()`, `os.stat()` | Return `[value, errno]`. `mode` from `os.stat()` has only the file type bits. | > | `os.remove()` | `os.remove` also removes an empty directory. | > | `os.rename()` | `-75` (`EXDEV`) across mounts. | > | `os.getcwd()`, `os.chdir()` | The shell's working directory; a change lasts for the run. | > | `os.platform` | `wasi`. | ### `Date` `Date.now()` and `new Date()` start at the workspace's [system time](/home/configuration#system-time) when it sets one, and files the program writes are stamped from the same clock. `performance.now()` and `os.now()` measure elapsed time. | API | Support | | - | - | | `Date.now()` | ✓ | | `new Date()` | ✓ | | `performance.now()`, `os.now()` | ✓ | > [accordion] Example: print the current time > > ```javascript theme={null} > print(new Date().toISOString()); > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | Local times | UTC. `TZ` does not change them. | ### `console` and printing `console.log()`, `console.info()` and `console.debug()` write to stdout, and `console.error()` and `console.warn()` to stderr. They format values as Node's `util.inspect()` does and take `util.format()` placeholders such as `%s`, `%d` and `%j`. `print()` writes the engine's own way. > [accordion] Example: print a result > > ```javascript theme={null} > console.log("Total:", 2 + 3, { items: [1, 2] }); > console.error("%d skipped", 1); > print("done"); > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `console.table()`, `console.time()`, `console.count()` | ✗ | > | Arrays of more than six items | One line, where Node groups them in columns | ### Node.js APIs `require()` returns these modules, with or without the `node:` prefix, and loads files by path: JavaScript as CommonJS, and JSON parsed. `process`, `Buffer`, `TextEncoder`, `TextDecoder`, `global`, the timers and a script's `__filename` and `__dirname` are globals. > [accordion] Example: filter a JSON file > > ```javascript theme={null} > const fs = require("fs"); > const path = require("path"); > > const file = path.join("/data", "issues.json"); > const open = JSON.parse(fs.readFileSync(file)).filter((i) => i.open); > fs.writeFileSync("/data/open.json", JSON.stringify(open)); > console.log(open.length, "open"); > ``` > [accordion] Example: read piped input by line > > ```javascript theme={null} > const rl = require("readline").createInterface({ input: process.stdin }); > rl.on("line", (line) => console.log(line.toUpperCase())); > ``` > [accordion] Support > > | Module or global | Support | > | - | - | > | `fs` | `readFileSync`, `writeFileSync`, `appendFileSync`, `copyFileSync`, `existsSync`, `accessSync`, `statSync`, `lstatSync`, `readdirSync` (with `withFileTypes`), `realpathSync`, `mkdirSync` (with `recursive`), `rmSync`, `rmdirSync`, `unlinkSync`, `renameSync`, each also as a callback, and `fs.constants`; errors carry Node's `code`, `syscall`, `path` and Linux `errno` | > | `fs/promises`, `fs.promises` | The same calls, as promises | > | `path` | POSIX: `join`, `resolve`, `normalize`, `dirname`, `basename`, `extname`, `relative`, `isAbsolute`, `parse`, `format`, `sep`, `delimiter` | > | `process` | `argv`, `env`, `cwd()`, `chdir()`, `exit()`, `nextTick()`, `stdout.write()`, `stderr.write()`, and `stdin` as events (`data`, `end`, `readable`), `read()` and `for await`, each chunk as it arrives | > | `readline` | `createInterface({ input: process.stdin })`, as `line` and `close` events (`on`, `once`, `off`) or `for await` | > | `buffer`, `Buffer` | `from`, `alloc`, `concat`, `isBuffer`, `byteLength`, `toString` in `utf8`, `base64`, `base64url`, `hex`, `latin1` and `ascii` | > | `util` | `format`, `inspect`, `promisify` | > | Timers | `setTimeout`, `setInterval`, `setImmediate` and their `clear` calls | > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | npm packages | ✗ | > | Other modules, such as `http`, `child_process` and `os` | ✗ | > | `import` of `node:` modules in an ES module | ✗; `require()` works in both modes | > | Streams, such as `fs.createReadStream()` | ✗ | > | `process.exitCode` at the end of a run | Read by `process.exit()` only | > | `process.nextTick()` | Runs in turn with promise jobs, not ahead of them | > | Waiting on stdin | Holds the engine until input arrives, so timers wait while a read does | > | Modules an ES module imports | Run before Node's globals are set, so they reach them in functions, not at their top level | > | Symbolic links | `lstatSync` follows them, as `statSync` does, so `unlinkSync` refuses a link to a directory; `rmSync` removes a link, never what it points at | ### Runtime globals `scriptArgs`, the invocation name and arguments, and `atob()`, `btoa()` and `queueMicrotask()`. > [accordion] Example: read arguments and encode text > > ```javascript theme={null} > print(scriptArgs.slice(1)); > const encoded = btoa("hello"); > print(encoded); > print(atob(encoded)); > ``` ### Unavailable host APIs Unavailable in this runtime. > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `fetch()` | ✗ | ## Notes * `-e <code>` runs the argument, a file runs a mounted script, and with neither, piped input is the program. A `.mjs` file runs as an ES module; `.js` and `-e` run as classic scripts, and `-m` forces module mode. * `console.log` and `print` add a newline; `std.out.puts` and `std.err.puts` write raw. * An error in async code fails the run. * QuickJS cannot reach host files or the network. `command_limits` bound its time and output. Run untrusted or heavy code on a [machine](/home/setup/machine/overview). # Sandlock Source: https://docs.mirage.strukto.ai/home/setup/runtime/sandlock Run captured programs on this Linux host, confined by Landlock and seccomp. `sandlock` runs captured programs on this host through [Sandlock](https://github.com/multikernel/sandlock), which confines each process with Landlock and seccomp: it reads only the paths you grant and writes only the ones you allow. Linux only, in the Python SDK and Node. ## Installation Install the `sandlock` CLI on `PATH`. The full ruleset needs Linux 6.12 or later. ## Usage `captures` defaults to [`@external`](/home/setup/runtime/overview#captures): every program Mirage does not have itself. Name `@python` to run the host's `python3` under Sandlock too. > [tab] Python > > ```python theme={null} > from mirage import RAMVFS, MountMode, Workspace > from mirage.runtime.sandlock import SandlockRuntime > > runtime = SandlockRuntime( > captures=["@python", "@external"], > config={"fs_readable": ["/opt/tools"], "fs_writable": ["/tmp/work"]}, > ) > ws = Workspace({"/data": RAMVFS()}, mode=MountMode.EXEC, runtimes=[runtime]) > await ws.shell("python3 -c 'print(1 + 1)'") > ``` > [tab] TypeScript > > ```typescript theme={null} > import { MountMode, RAMVFS, SandlockRuntime, Workspace } from '@struktoai/mirage-node' > > const runtime = new SandlockRuntime({ > captures: ['@python', '@external'], > config: { fsReadable: ['/opt/tools'], fsWritable: ['/tmp/work'] }, > }) > const ws = new Workspace({ '/data': new RAMVFS() }, { mode: MountMode.EXEC, runtimes: [runtime] }) > await ws.shell("python3 -c 'print(1 + 1)'") > ``` > [tab] YAML > > ```yaml theme={null} > mode: exec > runtimes: > - name: sandlock > captures: ["@python", "@external"] > config: > fs_readable: [/opt/tools] > fs_writable: [/tmp/work] > max_memory: 512M > mounts: > /data: > vfs: ram > ``` ## Connecting the workspace A Sandlock program opens host paths, not the workspace's. To give it workspace files, expose a mount as a [FUSE folder](/home/setup/fuse) and grant it in `fs_writable`, or `fs_readable` for read only: ```yaml theme={null} mounts: /data: vfs: s3 config: bucket: my-bucket backend: fuse mountpoint: /data runtimes: - name: sandlock captures: ["@python", "@external"] config: fs_writable: [/data] ``` After the folder is mounted and granted, run the shared [workspace file check](/home/setup/runtime/overview#verify-workspace-file-access). * Put the folder at the mount's own path when you can, so a path typed in the shell names the same file in the program. * Calls into the folder follow mount modes and policies. A folder added in code with a session, `add_fuse_mount(prefix, mountpoint, session_id)` or `addFuseMount(prefix, mountpoint, sessionId)`, also follows that session's permissions. ## Runtime behavior | Capability | On this host | | - | - | | Command | The captured program and its words, as argv | | Piped input | stdin | | Environment | The session's, over the config `env`; none of the host's | | Working directory | The shell's | | Files it can read | `/usr`, `/lib`, `/lib64`, `/bin`, `/etc`, `/proc`, `/dev`, and `fs_readable` | | Files it can write | `fs_writable` only | | Memory | Capped at `max_memory`, when set | | Workspace files | Only through a FUSE folder you grant; see [above](#connecting-the-workspace) | ## Notes * Under a [`system_time`](/home/configuration#system-time), programs see that time through libfaketime when it is installed, and the host's clock without it. * An interpreter installed outside the system paths needs an `fs_readable` grant. * Host credentials are not passed to the program. * A workspace whose [`network`](/home/configuration#network) limits anything, or whose policies judge connections, runs nothing here: the program connects from this host, around both. It answers `Permission denied`, exit 126. * The runtime does not create the FUSE folder or bind it to a session. * Program lookup uses the sandbox's `PATH`, with the CLI's system default when the session does not set one. Add directories such as `/usr/local/bin` to the session's `PATH` when required. Missing-program diagnostics come from Sandlock. * A working directory absent from the host refuses the command with exit 126. * A [timeout](/home/core/output-limits#limit-a-lines-time) kills the program. # WASI Source: https://docs.mirage.strukto.ai/home/setup/runtime/wasi Run Python in WebAssembly with access to workspace files, in the Python SDK. `wasi` runs CPython in WebAssembly, with the standard library available subject to the restrictions below. Programs can access workspace files under the same permissions as shell commands, but cannot access host files or the network. Python SDK only. ## Installation ```bash theme={null} pip install 'mirage-ai[wasi]' ``` Download and unzip a release from [cpython-wasi-build](https://github.com/brettcannon/cpython-wasi-build/releases). Point `home`, or `MIRAGE_WASI_HOME`, at the unzipped directory. ## Usage > [tab] Python > > ```python theme={null} > from mirage import RAMVFS, MountMode, Workspace > from mirage.runtime.python import WasiRuntime > > ws = Workspace( > {"/data": RAMVFS()}, > mode=MountMode.EXEC, > runtimes=[WasiRuntime(config={"home": "/path/to/build"})], > ) > await ws.shell("python3 -c 'print(1 + 1)'") > ``` > [tab] YAML > > ```yaml theme={null} > mode: exec > runtimes: > - name: wasi > config: > home: /path/to/build > mounts: > /data: > vfs: ram > ``` ## Memory `max_memory` caps the memory one run may grow to: ```yaml theme={null} runtimes: - name: wasi config: home: /path/to/build max_memory: 256M ``` A run that needs more raises `MemoryError`. CPython starts at about 40M, so a cap below that fails every run. There is no cap by default. ## Python compatibility Examples assume a writable `/data` mount. Mount modes and permissions still apply. ### `open()` Modes and modifiers are listed separately; for example, `rb` combines `r` and `b`. | Mode or modifier | Support | | - | - | | `r` | ✓ | | `w` | ✓ | | `a` | ✓ | | `x` | ✓ | | `b` | ✓ | | `t` | ✓ | | `+` | ✓ | > [accordion] Example: append to a workspace file > > ```python theme={null} > with open("/data/log.txt", "a") as f: > f.write("Job completed.\n") > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | File access | Writes to workspace files follow mount permissions. Paths outside the mounts expose the CPython build read-only. | ### File objects Reads fetch ranges from the mount as the program asks for them. | API | Support | | - | - | | `f.read()` | ✓ | | `f.write()` | ✓ | | `f.truncate()` | ✓ | > [accordion] Example: write, read and truncate a file > > ```python theme={null} > with open("/data/example.txt", "w+") as f: > f.write("first\nsecond\n") > f.seek(0) > print(f.read(5)) # first > f.truncate(5) > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `f.write()` | Written at close or `os.fsync`. | ### `os` #### File operations `os.read()` and `os.pread()` fetch ranges from the mount as the program asks. | API | Support | | - | - | | `os.open()` | ✓ | | `os.read()` | ✓ | | `os.pread()` | ✓ | | `os.write()` | ✓ | | `os.pwrite()` | ✓ | | `os.fsync()` | ✓ | | `os.truncate()` | ✓ | | `os.remove()` | ✓ | | `os.unlink()` | ✓ | | `os.rename()` | ✓ | | `os.replace()` | ✓ | #### Directory operations | API | Support | | - | - | | `os.listdir()` | ✓ | | `os.scandir()` | ✓ | | `os.walk()` | ✓ | | `os.mkdir()` | ✓ | | `os.makedirs()` | ✓ | | `os.rmdir()` | ✓ | #### Metadata and links | API | Support | | - | - | | `os.stat()` | ✓ | | `os.lstat()` | ✓ | | `os.fstat()` | ✓ | | `os.symlink()` | ✓ | | `os.readlink()` | ✓ | | `os.utime()` | ✓ | #### Environment and working directory | API | Support | | - | - | | `os.getcwd()` | ✓ | | `os.chdir()` | ✓ | | `os.environ` | ✓ | > [accordion] Example: list a workspace directory > > ```python theme={null} > import os > > print(os.listdir("/data")) > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `os.chmod()` | Accepted, but has no effect. | > | `os.link()` | Raises `PermissionError`. | > | `os.getxattr()` | ✗ | > | `os.setxattr()` | ✗ | > | `os.listxattr()` | ✗ | > | `os.removexattr()` | ✗ | > | `os.write()`, `os.pwrite()` | Written at close or `os.fsync`. | > | `os.rename()`, `os.replace()` | `EXDEV` across mounts, where `shutil.move` copies instead. | > | `os.stat()`, `os.lstat()`, `os.fstat()` | `st_mode` has only the file type bits. | > | `os.getcwd()`, `os.chdir()` | The shell's working directory; a change lasts for the run. | > | `os.environ` | The session's environment, never the host's. | ### `os.path` | API | Support | | - | - | | `os.path` | ✓ | > [accordion] Example: check a workspace path > > ```python theme={null} > import os.path > > path = os.path.join("/data", "input.txt") > print(os.path.exists(path)) > ``` ### `pathlib` | API | Support | | - | - | | `Path.stat()` | ✓ | | `Path.glob()` | ✓ | | `Path.unlink()` | ✓ | | `Path.touch()` | ✓ | > [accordion] Example: create and inspect a workspace file > > ```python theme={null} > from pathlib import Path > > path = Path("/data/example.txt") > path.write_text("hello\n") > print(path.read_text()) > print(path.stat().st_size) > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `Path.stat()` | `st_mode` has only the file type bits. | ### `sys` | API | Support | | - | - | | `sys.argv` | ✓ | | `sys.stdin` | ✓ | > [accordion] Example: read arguments and piped input > > ```python theme={null} > import sys > > print(sys.argv[1:]) > print(sys.stdin.read()) > ``` ### `time` and `datetime` The clocks start at the workspace's [system time](/home/configuration#system-time) when it sets one, and files the program writes are stamped from the same clock. `time.monotonic()` and `time.perf_counter()` measure elapsed time. | API | Support | | - | - | | `time.time()`, `time.time_ns()` | ✓ | | `time.localtime()`, `time.gmtime()`, `time.strftime()` | ✓ | | `time.monotonic()`, `time.perf_counter()` | ✓ | | `datetime.datetime.now()` | ✓ | | `datetime.date.today()` | ✓ | > [accordion] Example: print today's date > > ```python theme={null} > import datetime > > print(datetime.date.today()) > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | Local times | UTC. `TZ` does not change them. | ### `json` | API | Support | | - | - | | `json.load()` | ✓ | > [accordion] Example: write and read workspace JSON > > ```python theme={null} > import json > > with open("/data/result.json", "w") as f: > json.dump({"status": "done"}, f) > > with open("/data/result.json", "r") as f: > result = json.load(f) > print(result["status"]) # done > ``` ### `glob` | API | Support | | - | - | | `glob.glob()` | ✓ | > [accordion] Example: find workspace text files > > ```python theme={null} > import glob > > print(glob.glob("/data/*.txt")) > ``` ### `shutil` | API | Support | | - | - | | `shutil.rmtree()` | ✓ | | `shutil.move()` | ✓ | > [accordion] Example: move a workspace file > > ```python theme={null} > import shutil > > with open("/data/draft.txt", "w") as f: > f.write("ready\n") > > shutil.move("/data/draft.txt", "/data/final.txt") > ``` > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `shutil.move()` | Copies instead when a rename would cross mounts (`EXDEV`). | ### `subprocess` Process creation is unavailable in this runtime. > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `subprocess` | Raises `OSError` (errno 58). | ### `socket` Network connections are unavailable in this runtime. > [accordion] Limitations > > | API or behavior | Limitation | > | - | - | > | `socket` | Raises `OSError` (errno 58). | ## Notes * Each command starts with fresh Python state. Files saved to workspace mounts persist between commands. * Exit codes are limited to 0–255. * Empty-path behavior depends on the Python build. Use `.` for the current directory. * A workspace mount at `/lib` or any path starting with `/lib/python` makes `python3` exit 126 to protect the interpreter's standard library. Other paths under `/lib`, such as `/lib/app`, are fine. # S3 Source: https://docs.mirage.strukto.ai/home/setup/s3 Set up AWS S3 credentials for the S3 VFS. ## Credentials The S3 VFS needs an AWS access key pair with read (and optionally write) access to your bucket. ### 1. Create an IAM User 1. Go to [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 2. **Users** -> **Create user** 3. Attach the `AmazonS3ReadOnlyAccess` policy (or `AmazonS3FullAccess` for write) 4. **Security credentials** -> **Create access key** -> **Application running outside AWS** 5. Copy the **Access key ID** and **Secret access key** ### 2. Set Environment Variables ```bash theme={null} # .env.development AWS_S3_BUCKET=my-bucket AWS_DEFAULT_REGION=us-east-1 AWS_ACCESS_KEY_ID=AKIA... AWS_SECRET_ACCESS_KEY=wJal... ``` ### Alternative: AWS Profile If you have `~/.aws/credentials` configured, you can use a profile name instead of explicit access keys. For the Python VFS API, see the [S3 VFS doc](/python/vfs/s3). ## Scoping a VFS to a key prefix Both runtimes support a key prefix option that transparently scopes every operation to a subpath of the bucket, so agents see clean paths while the underlying S3 keys carry the full prefix. ```ts TypeScript theme={null} const s3 = new S3VFS({ bucket: 'app-data', region: 'eu-west-1', keyPrefix: `users/${userId}/`, }) ``` ```python Python theme={null} S3VFS(S3Config( bucket="app-data", region="eu-west-1", key_prefix=f"users/{user_id}/", )) ``` Leading slashes are stripped and a trailing slash is added automatically. `None` / `undefined` and empty strings both mean "no prefix." For browser security considerations, see the [TypeScript S3 setup doc](/typescript/setup/s3). ## Content type of uploads A write carries no content type of its own, so the mount decides what S3 stores and serves back. Set `default_content_type` (`defaultContentType` in TypeScript) to stamp every upload with it. Unset, S3 picks its own default, and the browser's presigned PUT, which has to sign a type, sends `application/octet-stream`. # Scaleway Source: https://docs.mirage.strukto.ai/home/setup/scaleway Set up Scaleway Object Storage credentials for the Scaleway VFS. ## Credentials ### 1. Create an API key 1. Sign in to the [Scaleway console](https://console.scaleway.com/) 2. Go to **IAM** -> **API Keys** -> **Generate API Key** 3. Copy the **Access Key** and **Secret Key** 4. Note your bucket's **region** (e.g. `fr-par`) and **bucket** name The endpoint is derived from `region` as `s3.<region>.scw.cloud`. ### 2. Set environment variables ```bash theme={null} # .env.development SCW_BUCKET=my-bucket SCW_REGION=fr-par SCW_ACCESS_KEY=... SCW_SECRET_KEY=... ``` For SDK guides, see [Scaleway (Python)](/python/vfs/scaleway) and [Scaleway (TypeScript)](/typescript/setup/scaleway). # SeaweedFS Source: https://docs.mirage.strukto.ai/home/setup/seaweedfs Set up SeaweedFS credentials for the SeaweedFS VFS. ## Credentials SeaweedFS serves an S3-compatible gateway (the `weed s3` command, default port `8333`). Access keys are defined in the gateway's S3 config (`-s3.config`), or the gateway can run without authentication for local development. ### 1. Get an access key 1. Start the S3 gateway, e.g. `weed server -s3` or `weed s3 -filer=localhost:8888` 2. If you configured `-s3.config`, copy an identity's **accessKey** and **secretKey** 3. Note your gateway **endpoint** (e.g. `http://localhost:8333`) and **bucket** name SeaweedFS uses path-style addressing, so the `endpoint_url` is required. ### 2. Set environment variables ```bash theme={null} # .env.development SEAWEEDFS_BUCKET=my-bucket SEAWEEDFS_ENDPOINT=http://localhost:8333 SEAWEEDFS_ACCESS_KEY=... SEAWEEDFS_SECRET_KEY=... ``` > [!TIP] > > Blaxel Agent Drive is backed by SeaweedFS. Use the drive's `s3Url` as the > endpoint and a drive access token's credentials to mount it as a SeaweedFS > VFS. For SDK guides, see [SeaweedFS (Python)](/python/vfs/seaweedfs) and [SeaweedFS (TypeScript)](/typescript/setup/seaweedfs). # SharePoint Source: https://docs.mirage.strukto.ai/home/setup/sharepoint Get a Microsoft Graph access token for the SharePoint VFS. The SharePoint VFS talks to Microsoft SharePoint Online through the [Microsoft Graph API](https://learn.microsoft.com/en-us/graph/). It authenticates with an OAuth2 **bearer access token**. Unlike OneDrive, you do **not** need a drive id: the VFS discovers sites and document libraries for you, so a token with the right SharePoint permissions is all it needs. ## Credentials You only need an **access token**. Pick whichever path fits. ### Option A: App-only (client credentials) Best for scripted, automated, and CI runs. There is no signed-in user, and it works for SharePoint because the VFS uses `/sites` and `/sites/{id}/drives` (no `/me` context required). 1. In the [Microsoft Entra admin center](https://entra.microsoft.com), go to **Identity** -> **Applications** -> **App registrations** -> **New registration**. 2. Under **API permissions** -> **Microsoft Graph** -> **Application permissions**, add `Sites.Read.All` for read-only, or `Sites.ReadWrite.All` (plus `Files.ReadWrite.All` for writes) for full access. Click **Grant admin consent**. 3. Under **Certificates & secrets**, create a **client secret**. 4. Request a token with the client-credentials flow: ```bash theme={null} TENANT_ID="<your tenant id>" CLIENT_ID="<your app client id>" CLIENT_SECRET="<your client secret>" curl -s -X POST "https://login.microsoftonline.com/$TENANT_ID/oauth2/v2.0/token" \ -d "client_id=$CLIENT_ID" \ -d "client_secret=$CLIENT_SECRET" \ -d "scope=https://graph.microsoft.com/.default" \ -d "grant_type=client_credentials" | jq -r .access_token ``` ### Option B: Delegated (Graph Explorer) Fastest way to try it as yourself. The token lasts about an hour, which is plenty for a test run. 1. Open [Graph Explorer](https://developer.microsoft.com/graph/graph-explorer) and **Sign in**. 2. Run any SharePoint query (for example `GET /sites?search=*`) and consent when prompted. 3. Open the **Access token** tab and copy the token. This is a **delegated** token scoped to your own SharePoint access. > [!NOTE] > > A static token is short-lived (about 60 minutes). For long-running mounts, pass > a `Callable[[], str]` provider as `access_token` instead of a string. The > VFS refreshes on `401`, so the mount survives token expiry. ### Verify access With your token exported as `TOKEN`: ```bash theme={null} # list sites you can see (name + id) curl -s -H "Authorization: Bearer $TOKEN" \ "https://graph.microsoft.com/v1.0/sites?search=*" | jq '.value[] | {displayName, id}' # list the document libraries (drives) in a site curl -s -H "Authorization: Bearer $TOKEN" \ "https://graph.microsoft.com/v1.0/sites/{site-id}/drives" | jq '.value[] | {name, id}' ``` ### Set environment variables ```bash theme={null} # .env.development MS_GRAPH_DRIVE_TOKEN=<token> ``` > [!NOTE] > > Snapshots and version pinning rely on SharePoint **version history**, which is > on by default. Older versions are only readable while the library retains them > (the version cap is configurable, and an admin can disable versioning). For SDK guides, see [SharePoint (Python)](/python/vfs/sharepoint) and [SharePoint (TypeScript)](/typescript/setup/sharepoint). # Slack Source: https://docs.mirage.strukto.ai/home/setup/slack Set up a Slack Bot Token for the Slack VFS. ## Credentials ### 1. Create a Slack App 1. Go to [https://api.slack.com/apps](https://api.slack.com/apps) 2. **Create New App** -> **From scratch** 3. Name it (e.g., "Mirage") and select your workspace ### 2. Configure Bot Permissions 1. **OAuth & Permissions** in the left sidebar 2. Under **Bot Token Scopes**, add: * `channels:history` - read messages in public channels * `channels:read` - list public channels * `groups:history`, `groups:read` - private channels (optional) * `im:history`, `im:read` - direct messages (optional) * `mpim:history`, `mpim:read` - group direct messages (optional) * `users:read` - the VFS `users/` directory Add `chat:write` only for the CLI `send-message` command, and `files:write` for `upload-file`. The mount never posts. ### 3. Install to Workspace 1. **Install App** in the left sidebar -> **Install to Workspace** 2. Authorize the requested permissions 3. Copy the **Bot User OAuth Token** (`xoxb-...`) ### 4. Optional: Enable Workspace Search Slack's `search.messages` API does not accept bot tokens. To use `slack search` or workspace-level search push-down: 1. Add `search:read` under **User Token Scopes**. For `grep` and `rg`, also add `channels:read`, `groups:read`, `im:read` and `mpim:read`, so Mirage can see which channels and DMs that user's search covers. 2. Reinstall or reauthorize the app. 3. Copy the resulting **User OAuth Token** (`xoxp-...`). Keep using the bot token for normal reads and writes. Mirage uses the optional user token only for Slack search endpoints. ### 5. Set Environment Variables ```bash theme={null} # .env.development SLACK_BOT_TOKEN=xoxb-xxxx... SLACK_USER_TOKEN=xoxp-xxxx... # optional, only needed for workspace search ``` ### 6. Invite the Bot The bot must be invited to channels it needs to read; a channel it is not in answers `Permission denied`: ``` /invite @Mirage ``` For SDK guides, see [Slack (Python)](/python/vfs/slack) and [Slack (TypeScript)](/typescript/setup/slack). # SQL Source: https://docs.mirage.strukto.ai/home/setup/sql Store workspace files in SQL tables. SQL stores workspace files in a database's tables, laid out as [AgentFS](https://github.com/tursodatabase/agentfs)'s. The files last as long as the database does. One database holds one filesystem. ## Configuration For Python or Node, set `path` to the SQLite file. Leave it out to keep the database in memory: ```yaml theme={null} mounts: /data: vfs: sql mode: write config: path: ./workspace.db ``` A Postgres server, a Durable Object's storage or a D1 database mounts from code, through its driver. See the SDK guides. Add `capacity: 100MB` under `config` to cap the bytes the files hold. See [capacity](/home/configuration#capacity). ## SDK guides * [Python SQL VFS](/python/vfs/sql) * [TypeScript SQL setup](/typescript/setup/sql) # SSH Source: https://docs.mirage.strukto.ai/home/setup/ssh Access a remote directory as workspace files over SFTP. SSH mounts a directory from a remote server. You need an SSH account with access to that directory and an SFTP-enabled server. Available in Python and Node. ## Configuration Set the server, username, key and remote directory: ```yaml theme={null} mounts: /remote: vfs: ssh mode: read config: host: server.example.com username: deploy identity_file: ~/.ssh/id_ed25519 root: /srv/data ``` `ls /remote` lists the remote directory. Set `mode: write` to allow changes, subject to the SSH account's permissions. `private_key` takes the key's own text in place of `identity_file`'s path, so a [credential pointer](/home/authentication#pointer-fields) can read it from a secret store. To run programs on the server, use the [SSH runtime](/home/setup/machine/ssh). ## SDK guides * [Python SSH VFS](/python/vfs/ssh) * [TypeScript SSH setup](/typescript/setup/ssh) # Supabase Storage Source: https://docs.mirage.strukto.ai/home/setup/supabase Set up Supabase Storage credentials for the Supabase VFS. ## Credentials Supabase Storage exposes an S3-compatible API at `https://<project-ref>.storage.supabase.co/storage/v1/s3`, signed with **S3 Access Keys** scoped to a Supabase project (not your `anon` or `service_role` JWT). ### 1. Create an S3 access key 1. Open the [Supabase dashboard](https://supabase.com/dashboard) and pick your project. 2. **Storage** -> **Settings** -> **S3 Access Keys**. 3. **New access key** -> scope to the bucket(s) you want Mirage to mount. 4. Copy the **Access key ID** and **Secret access key**, the secret is shown once. ### 2. Note the project reference and region * **Project reference** is in the dashboard URL: `https://supabase.com/dashboard/project/<project-ref>`. * **Region** is the region you selected when creating the project. Supabase requires a region string for SigV4 signing even though it is metadata only. ### 3. Set Environment Variables ```bash theme={null} # .env.development SUPABASE_BUCKET=my-bucket SUPABASE_REGION=us-east-1 SUPABASE_PROJECT_REF=abcdefghijklmnop SUPABASE_ACCESS_KEY_ID=... SUPABASE_SECRET_ACCESS_KEY=... ``` > [!TIP] > > Supabase requires **path-style** S3 URLs. The Mirage VFS uses them by default in both SDKs. For SDK guides, see [Supabase Storage (Python)](/python/vfs/supabase) and [Supabase Storage (TypeScript)](/typescript/setup/supabase). # Tencent COS Source: https://docs.mirage.strukto.ai/home/setup/tencent Set up Tencent Cloud Object Storage (COS) credentials for the Tencent VFS. ## Credentials ### 1. Create an API key 1. Sign in to the [Tencent Cloud console](https://console.cloud.tencent.com/) 2. Go to **Access Management** -> **API Keys** -> **Create Key** 3. Copy the **SecretId** (access key id) and **SecretKey** (secret access key) 4. Note your bucket's **region** (e.g. `ap-guangzhou`) and the full **bucket** name including the APPID suffix (e.g. `my-bucket-1250000000`) The endpoint is derived from `region` as `cos.<region>.myqcloud.com`. > [!NOTE] > > Tencent COS bucket names always include the APPID suffix. Use the full name > (with the suffix) for `COS_BUCKET`. ### 2. Set environment variables ```bash theme={null} # .env.development COS_BUCKET=my-bucket-1250000000 COS_REGION=ap-guangzhou COS_SECRET_ID=... COS_SECRET_KEY=... ``` For SDK guides, see [Tencent COS (Python)](/python/vfs/tencent) and [Tencent COS (TypeScript)](/typescript/setup/tencent). # TiDB Cloud Filesystem Source: https://docs.mirage.strukto.ai/home/setup/tidb Set up a TiDB Cloud Filesystem token for the tidb_filesystem VFS. ## Credentials The VFS reaches a file system through its REST API with a file system token. No extra package is needed in Python or TypeScript. 1. Create a file system in the [TiDB Cloud console](https://tidbcloud.com/) or with `ti fs`, and note its region. 2. Take its owner token, shown once when the file system is created, or create a scoped token under **File Systems**, your file system, **Access Tokens**, **Create Token**. See [Manage File System Tokens](https://docs.pingcap.com/tidbcloud-filesystem/manage-filesystem-tokens/). 3. Set `host` to the endpoint of the file system's region. A token works only against its own region. | Region | `host` | | - | - | | `aws-us-east-1` | `https://aws-us-east-1.drive9.ai` | | `aws-us-west-2` | `https://aws-us-west-2.drive9.ai` | | `aws-ap-southeast-1` | `https://aws-ap-southeast-1.drive9.ai` | | `gcp-us-east1` | `https://gcp-us-east1.drive9.ai` | | `azure-centralus` | `https://azure-centralus.drive9.ai` | | `alicloud-ap-southeast-1` | `https://alicloud-ap-southeast-1.drive9.ai` | Your application passes both to the VFS, for example from its environment: ```bash theme={null} TIDB_FILESYSTEM_HOST=https://aws-us-east-1.drive9.ai TIDB_FILESYSTEM_TOKEN=... ``` ### Scoped tokens A scoped token reaches only the path it was created for, and only with the operations it allows (read, list, search, write, delete). Mount it with `root_path` set to that path, since it cannot list the file system's root. ## Self-hosted drive9 TiDB Cloud Filesystem runs on the open-source [drive9](https://github.com/mem9-ai/drive9) server, and the same VFS mounts a drive9 server you run yourself: set `host` to its origin and `token` to an API key it issued. See the [Python TiDB Cloud Filesystem VFS](/python/vfs/tidb_filesystem) or [TypeScript TiDB Cloud Filesystem VFS](/typescript/setup/tidb_filesystem) page for configuration and examples. # Trello Source: https://docs.mirage.strukto.ai/home/setup/trello Set up Trello API credentials for the Trello VFS and CLI. ## Credentials ### 1. Get an API Key 1. Go to [https://trello.com/power-ups/admin](https://trello.com/power-ups/admin) 2. Create a new Power-Up (or use an existing one) 3. Copy the **API Key** from the Power-Up's API Key page ### 2. Generate a Token Open the following URL in your browser, replacing `YOUR_API_KEY`: ``` https://trello.com/1/authorize?expiration=never&scope=read,write&response_type=token&key=YOUR_API_KEY ``` Click **Allow** and copy the token string. ### 3. Set Environment Variables ```bash theme={null} # .env.development TRELLO_API_KEY=your-api-key TRELLO_API_TOKEN=your-api-token ``` For SDK guides, see [Trello (Python)](/python/vfs/trello) and [Trello (TypeScript)](/typescript/setup/trello). The same key and token register the [Trello CLI](/home/setup/cli/trello). # VFS Source: https://docs.mirage.strukto.ai/home/setup/vfs Mount S3, Slack, databases and other services as files in Mirage. Mirage turns your data sources into one unified virtual filesystem. Each source is a VFS mounted under its own folder, such as S3 under `/s3`, Slack under `/slack` and PostgreSQL under `/pg`, and an agent reads them all with `ls`, `cat`, `grep` and `find`. Each VFS turns its service into files and folders. An S3 object is a file, a Slack channel is a folder with one `chat.jsonl` per day, and a PostgreSQL table is a folder with its rows in `rows.jsonl`. [RAM](/home/setup/ram) needs no credentials, so start there to try it. ## Example: Slack Mount Slack under `/slack` with a [bot token](/home/setup/slack), plus a user token for search: > [tab] Python > > ```python theme={null} > import os > > from mirage import MountMode, Workspace > from mirage.vfs.slack import SlackConfig, SlackVFS > > slack = SlackVFS( > config=SlackConfig( > token=os.environ["SLACK_BOT_TOKEN"], > search_token=os.environ["SLACK_USER_TOKEN"], > ) > ) > ws = Workspace({"/slack": slack}, mode=MountMode.READ) > ``` > [tab] TypeScript > > ```typescript theme={null} > import { MountMode, SlackVFS, Workspace } from '@struktoai/mirage-node' > > const slack = new SlackVFS({ > token: process.env.SLACK_BOT_TOKEN!, > searchToken: process.env.SLACK_USER_TOKEN, > }) > const ws = new Workspace({ '/slack': slack }, { mode: MountMode.READ }) > ``` > [tab] YAML > > ```yaml theme={null} > mounts: > /slack: > vfs: slack > mode: read > config: > token: ${SLACK_BOT_TOKEN} > search_token: ${SLACK_USER_TOKEN} > ``` Slack becomes: ```text theme={null} /slack/ channels/ general__C04KEPWF6V7/ 2026-04-05/ chat.jsonl files/ roadmap__F07AB12CD.pdf dms/ alice__D0AQDJ5FP9V/ 2026-04-05/ chat.jsonl users/ alice__U12345678.json ``` Each channel and DM has one folder per day for the last 90 days, and a day's `chat.jsonl` holds one message per line. A name ends with its Slack ID after `__`, so two channels with the same name stay apart. ```bash theme={null} ls /slack/channels/ head -1 /slack/channels/general__C04KEPWF6V7/2026-04-05/chat.jsonl grep -rw refund /slack/channels/ ``` The `head` prints: ```json theme={null} {"type":"message","user":"U12345678","text":"PR #326 is up for review","ts":"1775383200.000100"} ``` The `grep` uses Slack's own search: it asks Slack which days mention `refund` and reads only those, not every day of every channel. That takes the `search_token` (a user token with `search:read`) and `-w`, since Slack matches whole words. Without them, or when Slack's search cannot answer, `grep` reads the files. Slack searches message text, file names and reactions, and finds a new message only once it has indexed it. Attachments under `files/` are always read. ## Supported VFS A ✓ means the VFS runs there. In a browser, some need a proxy or CORS: [Redis](/typescript/setup/redis#browser) uses an HTTP endpoint, [PostgreSQL](/typescript/setup/postgres) uses Neon and [MongoDB](/typescript/setup/mongodb) an HTTP bridge. ### Local and infrastructure | VFS | Python | Node.js | Browser | | - | - | - | - | | [RAM](/home/setup/ram) | ✓ | ✓ | ✓ | | [Disk](/home/setup/disk) | ✓ | ✓ | — | | [OPFS](/home/setup/opfs) | — | — | ✓ | | [Redis](/home/setup/redis) | ✓ | ✓ | ✓ | | [SSH](/home/setup/ssh) | ✓ | ✓ | — | ### Object storage | VFS | Python | Node.js | Browser | | - | - | - | - | | [Amazon S3](/home/setup/s3) | ✓ | ✓ | ✓ | | [Cloudflare R2](/home/setup/r2) | ✓ | ✓ | ✓ | | [Google Cloud Storage](/home/setup/gcs) | ✓ | ✓ | ✓ | | [Oracle Cloud Storage](/home/setup/oci) | ✓ | ✓ | ✓ | | [Supabase Storage](/home/setup/supabase) | ✓ | ✓ | ✓ | | [MinIO](/home/setup/minio) | ✓ | ✓ | ✓ | | [Ceph](/home/setup/ceph) | ✓ | ✓ | ✓ | | [SeaweedFS](/home/setup/seaweedfs) | ✓ | ✓ | ✓ | | [Wasabi](/home/setup/wasabi) | ✓ | ✓ | ✓ | | [Backblaze B2](/home/setup/backblaze) | ✓ | ✓ | ✓ | | [DigitalOcean Spaces](/home/setup/digitalocean) | ✓ | ✓ | ✓ | | [Tencent COS](/home/setup/tencent) | ✓ | ✓ | ✓ | | [Alibaba OSS](/home/setup/aliyun) | ✓ | ✓ | ✓ | | [Scaleway](/home/setup/scaleway) | ✓ | ✓ | ✓ | | [QingStor](/home/setup/qingstor) | ✓ | ✓ | ✓ | | [Hugging Face Buckets](/home/setup/hf_buckets) | ✓ | ✓ | — | ### Cloud files and Google Workspace | VFS | Python | Node.js | Browser | | - | - | - | - | | [Google Drive](/home/setup/google) | ✓ | ✓ | ✓ | | [Google Docs](/home/setup/google) | ✓ | ✓ | ✓ | | [Google Sheets](/home/setup/google) | ✓ | ✓ | ✓ | | [Google Slides](/home/setup/google) | ✓ | ✓ | ✓ | | [Google Calendar](/home/setup/gcal) | ✓ | ✓ | ✓ | | [Gmail](/home/setup/google) | ✓ | ✓ | ✓ | | [OneDrive](/home/setup/onedrive) | ✓ | ✓ | ✓ | | [SharePoint](/home/setup/sharepoint) | ✓ | ✓ | ✓ | | [Dropbox](/home/setup/dropbox) | ✓ | ✓ | ✓ | | [Box](/home/setup/box) | ✓ | ✓ | ✓ | | [Nextcloud](/home/setup/nextcloud) | ✓ | ✓ | — | | [Databricks Volumes](/home/setup/databricks) | ✓ | ✓ | — | | [TiDB Cloud Filesystem](/home/setup/tidb) | ✓ | ✓ | — | ### Development, collaboration and messaging | VFS | Python | Node.js | Browser | | - | - | - | - | | [GitHub](/home/setup/github) | ✓ | ✓ | ✓ | | [Hugging Face Spaces](/home/setup/hf_spaces) | ✓ | ✓ | — | | [Slack](/home/setup/slack) | ✓ | ✓ | ✓ | | [Discord](/home/setup/discord) | ✓ | ✓ | ✓ | | [Email](/home/setup/email) | ✓ | ✓ | — | | [Linear](/home/setup/linear) | ✓ | ✓ | ✓ | | [Notion](/home/setup/notion) | ✓ | ✓ | ✓ | | [Trello](/home/setup/trello) | ✓ | ✓ | ✓ | ### Data and AI | VFS | Python | Node.js | Browser | | - | - | - | - | | [PostgreSQL](/home/setup/postgres) | ✓ | ✓ | ✓ | | [MongoDB](/home/setup/mongodb) | ✓ | ✓ | ✓ | | [GridFS](/home/setup/gridfs) | ✓ | ✓ | — | | [Airtable](/home/setup/airtable) | ✓ | ✓ | ✓ | | [Chroma](/home/setup/chroma) | ✓ | ✓ | ✓ | | [LanceDB](/home/setup/lancedb) | ✓ | ✓ | — | | [Qdrant](/home/setup/qdrant) | ✓ | ✓ | ✓ | | [Dify](/home/setup/dify) | ✓ | ✓ | ✓ | | [Mem0](/home/setup/mem0) | ✓ | ✓ | ✓ | | [Hugging Face Datasets](/home/setup/hf_datasets) | ✓ | ✓ | — | | [Hugging Face Models](/home/setup/hf_models) | ✓ | ✓ | — | ### Observability | VFS | Python | Node.js | Browser | | - | - | - | - | | [Weights & Biases](/home/setup/wandb) | ✓ | ✓ | ✓ | | [Langfuse](/home/setup/langfuse) | ✓ | ✓ | ✓ | | [Jaeger](/home/setup/jaeger) | ✓ | ✓ | — | ## Add your own VFS To mount a service Mirage does not ship, [write a custom VFS](/home/setup/custom-vfs). # VFS.md and SKILL.md Source: https://docs.mirage.strukto.ai/home/setup/vfs-md Two Markdown files that tell an agent what is mounted and which commands it can run. A workspace describes itself to an agent in two Markdown files, in the [VFS.md](https://agentvfs.org/vfs) format: * **VFS.md**: every mounted path, its layout and which Unix commands work there. * **SKILL.md**: the registered CLIs, with each one's top-level help. A subcommand's usage is one `--help` away. Both are built from the live workspace and follow the session's [profile](/home/policy/overview): a command the profile denies, or a path it hides, is never mentioned. Each VFS page shows its VFS.md, such as [Gmail](/python/vfs/gmail). ## Get them > [tab] Python > > ```python theme={null} > vfs_md = await ws.vfs_md() > skill_md = await ws.skill_md(session_id="agent") > preview = await ws.vfs_md(profile="reader") > await ws.vfs_md("/VFS.md") > ``` > [tab] TypeScript > > ```typescript theme={null} > const vfsMd = await ws.vfsMd() > const skillMd = await ws.skillMd(undefined, { sessionId: 'agent' }) > const preview = await ws.vfsMd(undefined, { profile: 'reader' }) > await ws.vfsMd('/VFS.md') > ``` > [tab] HTTP > > ```bash theme={null} > curl http://127.0.0.1:8765/v1/workspaces/demo/vfs-md \ > -H "Authorization: Bearer $MIRAGE_AUTH_TOKEN" > > curl http://127.0.0.1:8765/v1/workspaces/demo/sessions/agent/skill-md \ > -H "Authorization: Bearer $MIRAGE_AUTH_TOKEN" > > curl -X PUT http://127.0.0.1:8765/v1/workspaces/demo/vfs-md \ > -H "Authorization: Bearer $MIRAGE_AUTH_TOKEN" \ > -H 'Content-Type: application/json' \ > -d '{"path":"/VFS.md"}' > ``` > [tab] CLI > > ```bash theme={null} > mirage workspace vfs-md demo > mirage workspace skill-md demo --session agent > mirage workspace vfs-md demo --path /VFS.md > ``` * **No session or profile**: what the workspace's default profile allows. * **A session**: what that session's agent sees. * **A profile**: a preview of what a session with that profile would see. * **A path**: the file appears in the workspace, read-only and always current, so the agent runs `cat /VFS.md`. Each session reads its own version. ## What VFS.md says about each path * **VFS**: its name, for a VFS with its own layout or its own search, such as Google Drive. Plain files, on `s3` or `ram` for example, show only the mode: which VFS holds them changes nothing an agent does. * **Mode**: `read`, `write` or `exec`. A path whose VFS cannot change files shows `read`, whatever mode it is mounted with. * **Layout**: how its files are organized and what they hold, for a VFS that has one. A VFS sets it with [`vfs_md`](/home/setup/custom-vfs#attributes). * **Supported commands**: the Unix commands that work there, and which of them ask the service which files may match. CLIs such as [`search`](/home/setup/cli/search) are in SKILL.md, not here. * **Limitations**: where it differs from a local filesystem, such as being read only, or the [`walk_limit`](/home/integration/search#walk_limit) on large folders. Which commands can change files depends on the methods the VFS implements; [Custom VFS](/home/setup/custom-vfs) lists them. # Weights & Biases Source: https://docs.mirage.strukto.ai/home/setup/wandb Read experiment runs, configuration, summaries, history, and run files. ## Credentials Create a key in [W\&B User Settings](https://wandb.ai/settings) and store it in `WANDB_API_KEY`. Set `entities` to the username or team segment from a project URL; Mirage does not discover entities from the key. ```python theme={null} import os from mirage import Workspace, MountMode from mirage.vfs.wandb import WandbConfig, WandbVFS ws = Workspace({ "/wandb": WandbVFS(WandbConfig( entities=["my-team"], api_key=os.environ["WANDB_API_KEY"], )), }, mode=MountMode.READ) ``` After mounting, `find /wandb/my-team -maxdepth 3 -name run.json` discovers available run paths. The mount exposes `/<entity>/<project>/<run-id>/` with `run.json`, `config.json`, `summary.json`, `history.jsonl`, and `files/`. Configure one or more entities explicitly; project and run listings are fetched on demand and follow service pagination. Run IDs identify directories; duplicate display names remain separate runs. For SDK guides, see [Weights & Biases (Python)](/python/vfs/wandb) and [Weights & Biases (TypeScript)](/typescript/setup/wandb). ## Run data reference `run.json` contains the run metadata exposed by the supported W\&B API fields: | Fields | Contents | | - | - | | `entity`, `project`, `run`, `path` | Run identity and its `entity/project/run-id` path | | `storage_id`, `display_name`, `state` | W\&B's opaque storage ID, display name, and reported state | | `tags`, `sweep_name`, `group`, `job_type` | Experiment organization | | `commit`, `created_at`, `heartbeat_at` | Source revision, creation time, and last heartbeat | | `description`, `notes`, `user` | Run description, notes, and creator's `id`/`name`/`username`/`email` | | `read_only` | W\&B's reported edit permission; the Mirage mount remains read-only | | `system_metrics` | Latest system metrics decoded as JSON, retaining nested values | | `history_line_count`, `history_keys`, `file_count` | History row count, metric-key metadata including the last step, and file count | For example, the synthetic integration fixture renders this complete `run.json`: ```json theme={null} { "entity": "lab", "project": "experiments", "run": "run-a", "path": "lab/experiments/run-a", "storage_id": "synthetic-storage-id-a", "display_name": "duplicate", "state": "finished", "tags": [ "baseline", "café" ], "sweep_name": "sweep-01", "group": "ablation", "job_type": "train", "commit": "0123456789abcdef0123456789abcdef01234567", "read_only": false, "created_at": "2026-01-01T00:00:00Z", "heartbeat_at": "2026-01-01T00:05:00Z", "description": "Synthetic experiment metadata", "notes": "First line\nSecond line: café", "user": { "id": "synthetic-user-id-bob", "name": "Bob Example", "username": "bob", "email": "bob@example.com" }, "system_metrics": { "cpu": 0, "gpu.0.memoryAllocated": 128.5, "nested": { "missing": null } }, "history_line_count": 4, "history_keys": { "lastStep": 5, "keys": { "score": { "type": "number", "count": 3 }, "train_step": { "type": "number", "count": 4 } } }, "file_count": 4 } ``` Unavailable metadata is `null`; empty tags, zero counts, false permissions, and original timestamp strings are preserved. These fields are fetched only when reading `run.json`, in one run query. Listing and stat do not fetch them. The `user` is the run's creator, not the identity associated with the API key. When the creator exists, `user` has `id`, `name`, `username`, and `email`; W\&B requires the creator's ID and name, while username/email may be null. A missing creator is `user: null`. Reading these fields does not query the authenticated viewer or discover teams. Machine/runtime details are available at `files/wandb-metadata.json` when uploaded; reading `run.json` does not download that file. `config.json` unwraps W\&B's configuration `value` envelopes. `summary.json` contains the stored summary, which may differ from the best value in history. These documents have run-defined keys rather than a fixed Mirage field list. Nested objects, arrays, metric names containing `/` or `.`, and null values remain intact. For this fixture, they are `{"lr": 0.01, "label": "café"}` and `{"score": 0.4}`. `history.jsonl` scans full history in `_step` windows using the public SDK's unsampled scan protocol. It retains row order, missing keys, nulls, and logged training-step fields. `_step` and a training-step metric are separate values. An empty window does not end a scan. The last step is captured when a read begins; rows appended later are visible on a subsequent read. One-step query windows are widened to two steps to avoid a live API edge case; results are filtered to the original range without duplicates or later rows. Run files retain their relative paths and are downloaded as raw bytes. Listing and stat do not download histories or files. Rendered JSON and history have unknown sizes; raw file sizes come from W\&B's file metadata. Directory metadata uses Mirage's index cache (600 seconds by default). A project listing also establishes its runs' existence; a file catalog populates all nested directories, so traversing them reuses the same metadata. Config, summary, and history reads request their own fields. Downloads resolve the exact filename for a fresh URL on each read. File content and download URLs are not cached in the index. Reads and downloads stream, so `head` can stop before fetching the entire history. `page_size` defaults to 100 (maximum 1000); `max_pages` defaults to 10000. Exhausting a page budget raises an error instead of returning a complete-looking partial result. Recursive `du` is capped at 1000 entries; glob expansion uses Mirage's standard traversal limit. API keys use host configuration and are redacted from VFS state. No write operations or W\&B CLI are registered. # Wasabi Source: https://docs.mirage.strukto.ai/home/setup/wasabi Set up Wasabi credentials for the Wasabi VFS. ## Credentials ### 1. Create an access key 1. Sign in to the [Wasabi console](https://console.wasabisys.com/) 2. Go to **Access Keys** -> **Create New Access Key** 3. Copy the **Access Key** and **Secret Key** 4. Note your bucket's **region** (e.g. `us-east-2`) and **bucket** name The endpoint is derived from `region` as `s3.<region>.wasabisys.com` (`s3.wasabisys.com` for `us-east-1`). ### 2. Set environment variables ```bash theme={null} # .env.development WASABI_BUCKET=my-bucket WASABI_REGION=us-east-2 WASABI_ACCESS_KEY_ID=... WASABI_SECRET_ACCESS_KEY=... ``` For SDK guides, see [Wasabi (Python)](/python/vfs/wasabi) and [Wasabi (TypeScript)](/typescript/setup/wasabi). # Windows Source: https://docs.mirage.strukto.ai/home/setup/windows Install WinFsp for Mirage's FUSE mounts (Python, experimental). Windows has no native FUSE. Mirage's Python FUSE mounts run on [WinFsp](https://winfsp.dev/), a Windows file system driver with a FUSE layer. Support is experimental, and the TypeScript SDK has no Windows FUSE support. **1. Install WinFsp** Needs Windows 10 (1809 or later) or Windows 11. No restart is needed. > [tab] winget > > ```powershell theme={null} > winget install -e --id WinFsp.WinFsp > ``` > [tab] Chocolatey > > ```powershell theme={null} > choco install winfsp -y > ``` > [tab] Installer > > Download the MSI from the [WinFsp releases page](https://winfsp.dev/rel/) > and run it. **2. Verify** ```powershell theme={null} pip install "mirage-ai[fuse]" python -c "import mfusepy; print('WinFsp FUSE loaded')" ``` If the import succeeds, the driver is reachable. ## How it differs | | Windows | macOS and Linux | | - | - | - | | Unmount | When the process exits; closing the workspace does not unmount | Closing the workspace unmounts | | File owner | The user who mounted it, for every file | The backend's owner, where it has one | | A file whose size is unknown | Size fetched on its first `stat` | Size 0 until first opened | | Mounts per process | Several | Several on Linux, one on macOS | # Troubleshooting Source: https://docs.mirage.strukto.ai/home/troubleshooting Fix installation, connection and file-access problems. ## Python import errors Run your script in the environment where Mirage is installed. For a uv project, use `uv run python your_script.py`. Some VFS types need an extra package: ```bash theme={null} uv add "mirage-ai[s3]" # S3 and compatible stores uv add "mirage-ai[redis]" # Redis ``` See [Python installation](/python/install) for the available extras. If a workspace that names `monty` or `quickjs` fails because its extra is missing, install that extra: ```bash theme={null} uv add "mirage-ai[monty]" # python3 on the Monty runtime uv add "mirage-ai[quickjs]" # node and js on the QuickJS runtime ``` QuickJS also needs a `qjs-wasi.wasm` module; see [QuickJS installation](/home/setup/runtime/quickjs#installation). ## TypeScript import errors Use the package for your environment: | Environment | Package | | - | - | | Node.js | `@struktoai/mirage-node` | | Browser | `@struktoai/mirage-browser` | | Shared types and primitives | `@struktoai/mirage-core` | If a browser build complains about Node built-ins, check for imports from `@struktoai/mirage-node`. Use the browser package and a [browser-supported VFS](/home/setup/vfs#supported-vfs) instead. For missing optional dependencies such as `redis` or `pg`, follow [TypeScript installation](/typescript/install#optional-peer-dependencies). ## Credentials or connection errors * Set credentials in the environment of the process running Mirage. * Check the service URL, account permissions and required token scopes. * Follow the setup guide for your [VFS](/home/setup/vfs#supported-vfs). ## Missing files or empty output Inspect paths inside Mirage. Replace `YOUR_WORKSPACE_ID` with your workspace ID: ```bash theme={null} mirage shell -w YOUR_WORKSPACE_ID -c 'mount' mirage shell -w YOUR_WORKSPACE_ID -c 'ls /' mirage shell -w YOUR_WORKSPACE_ID -c 'ls /your-mount/' mirage shell -w YOUR_WORKSPACE_ID -c 'stat /your-mount/path/to/file' ``` Use the exact path shown by the listing. Confirm that the connected account can access the file. In SDK code, inspect the command's exit code and stderr as well as stdout. ## Writes are refused Check that the VFS supports the operation and that the mount has `write` or `exec` mode. A read-only backend stays read-only even on a writable mount. Session [policies](/home/policy/overview) can also restrict access. ## FUSE does not mount FUSE is optional; `ws.shell(...)` works without an OS mount. If you need a mounted folder, follow the [macOS](/home/setup/macos) or [Linux](/home/setup/linux) setup, then install the binding for your SDK: * Python: `uv add "mirage-ai[fuse]"`. * TypeScript: follow the [FUSE setup](/typescript/setup/fuse), including its native dependency installation steps. ## Still stuck? [Open an issue](https://github.com/strukto-ai/mirage/issues) with your Mirage version, operating system, SDK, error message and a minimal example. Remove credentials from logs and configuration before sharing them. You can also ask in [Discord](https://discord.gg/u8BPQ65KsS) or [book a troubleshooting call](https://cal.com/strukto/30min). # In-app Source: https://docs.mirage.strukto.ai/python/access/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](/home/policy/overview) a session can be created under. **profile** `str` The profile a session gets when it names none. **policies** `list[Policy]` [Policies](/home/policy/overview) 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](/home/configuration#cache-index-and-store): symlinks and file attributes, command history, 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](/home/configuration) 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 processes runtimes 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](/home/policy/policies#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](/home/policy/overview), 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](/home/policy/policies#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, runtime=None, stream=False, ) -> 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. **runtime** `str` Run the line on this workspace [runtime](/home/setup/runtime/overview) entry, by name, instead of the one routing picks. **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](/home/policy/explain). ```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](/home/policy/explain#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](/python/agents/index) 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) ``` # Server Source: https://docs.mirage.strukto.ai/python/access/server The Mirage server in Python, a FastAPI app that holds workspaces and serves HTTP, MCP, RPC and SSH. The Mirage server is a FastAPI app. It holds workspaces and serves them over the [HTTP](/home/access/http) routes, [MCP](/home/access/mcp) and [RPC](/home/access/rpc), and over [SSH](/home/access/ssh), on its own port when `ssh_port` is set and through its HTTP port either way. The TypeScript server speaks the same protocol, so a client of one works against the other. ## Install ```bash pip theme={null} pip install mirage-ai ``` ```bash with SSH theme={null} pip install 'mirage-ai[ssh]' ``` The `ssh` extra adds [asyncssh](https://asyncssh.readthedocs.io), needed only for the SSH server. ## Run it `build_app` returns the app. Run it with any ASGI server; it serves until you stop it. ```python theme={null} import uvicorn from mirage.server.app import build_app app = build_app() uvicorn.run(app, host="127.0.0.1", port=8765) ``` | Argument | Default | Meaning | | - | - | - | | `auth_config` | from `MIRAGE_AUTH_MODE` | Token or JWT [configuration](/home/access/http#configure-authentication). | | `allowed_hosts` | `MIRAGE_ALLOWED_HOSTS`, else loopback | `Host` names the app answers. `["*"]` turns the check off, safe only behind a trusted proxy. Browser requests from another origin are refused either way. | | `max_workspaces` | `MIRAGE_MAX_WORKSPACES`, else the `max_workspaces` key, else no cap | The most workspaces the app holds at once. A create, clone or load past it answers 503, and the ones it holds keep running. | | `policies` | none | The server's own [policies](/home/access/http#server-policies): each answers `pre_workspace` before a workspace is built, and is registered on every workspace the app builds. | | `policy_file` | `MIRAGE_POLICY_FILE`, else the `policy_file` key, else none | A file of policy programs that answer the same way. | | `max_sessions` | `MIRAGE_MAX_SESSIONS`, else the `max_sessions` key, else `16` | The most sessions each workspace holds, its default session among them. A new session past it, over HTTP or SSH, answers 429. | | `max_memory` | `MIRAGE_MAX_MEMORY`, else the `max_memory` key, else none | The most any workspace's `max_memory` reaches, as a [size](/home/configuration#sizes). A workspace that sets more, or lifts its cap, gets this. | | `max_processes` | `MIRAGE_MAX_PROCESSES`, else the `max_processes` key, else none | The most any session's `processes.max` reaches, whatever a config or profile sets. | | `max_line_seconds` | `MIRAGE_MAX_LINE_SECONDS`, else the `max_line_seconds` key, else none | The most seconds any line runs, whatever `@line` a config or profile sets. A line past it exits 124. | | `max_env` | `MIRAGE_MAX_ENV`, else the `max_env` key, else none | The most any workspace's `max_env` reaches, as a [size](/home/configuration#sizes). | | `rate_limits` | `MIRAGE_RATE_LIMITS`, else the `rate_limits` key, else `ip=1000/minute` | A list of `RateLimit(key, rate)`; an empty list disables limits. See [Rate limits](/home/access/http#rate-limits). | | `forwarded_allow_ips` | `MIRAGE_FORWARDED_ALLOW_IPS`, else the `forwarded_allow_ips` key, else none | The proxies, addresses or networks, whose `X-Forwarded-For` names the client. `["*"]` believes any. | | `graceful_timeout` | `MIRAGE_GRACEFUL_TIMEOUT`, else the `graceful_timeout` key, else `0` | Seconds running lines get to finish on SIGTERM or SIGINT before they are cancelled. New work is refused meanwhile. | | `ssh_config` | from the `ssh_*` settings | The SSH server, opened with the app; off unless a port is set. | | `snapshot_store` | `None` | An `S3Config`: the store a snapshot request may name a key in. Without one, a snapshot only goes back to the caller; the server never writes one to its own disk. | | `state_root` | under `$MIRAGE_HOME` | Where live state is kept. | | `on_idle_exit` | `None` | Called when the last workspace has been gone `idle_grace_seconds` (30), or on `POST /v1/daemon/shutdown`. `None` keeps serving. | | `pid_file` | `None` | A file that holds the process id while the app runs. | ## Workers By default the daemon is one process, and one thread holds every workspace. With `workers` above 1 (`MIRAGE_WORKERS`, or the `workers` key), it runs that many workers, each the whole server on a Unix socket of its own, and its own server passes each request to the worker holding the workspace. A new workspace goes to a worker at random. The workspaces on one worker share its event loop, and the OS spreads the workers over the CPUs. `worker_type` (`MIRAGE_WORKER_TYPE`, or the `worker_type` key) is `thread` or `process`. TypeScript defaults to threads. Python defaults to threads on an interpreter without the GIL (3.14t) and to processes otherwise, since threads under the GIL take turns. The daemon answers `/v1/health` and `/v1/daemon/ready` itself, merges their `GET /v1/workspaces` lists, and holds `max_workspaces` across the workers. A worker that exits stays gone, and so do its workspaces. Each worker counts its own rate limits, so a limit keyed on the address or the account allows that many requests per worker. The SSH port is one server's, so it does not combine with workers yet. ## Started by the CLI The CLI runs the same app as a daemon, `mirage.server.daemon:app`, on `127.0.0.1:8765` in local auth mode, logging to `~/.mirage/daemon.log`. That entry adds the daemon behaviors: it writes `$MIRAGE_HOME/daemon.pid` for `mirage daemon stop` and `kill`, exits 30 seconds (`MIRAGE_IDLE_GRACE_SECONDS`) after its last running workspace stops or is deleted, and tunes the interpreter as it starts. It collects and freezes what startup made, so a full collection no longer scans it, raises the young collection threshold to 10,000, and sets the GIL switch interval to 1 ms. These settings are process-wide, so an app you run with `build_app` keeps its own. Make them yourself to get the same fairness: a busy line yields its workspace's loop every two GIL switch intervals, so under Python's default 5 ms a line in another session waits on 10 ms turns, and under 1 ms on 2 ms turns. ```python theme={null} import gc import sys gc.collect() gc.freeze() gc.set_threshold(10_000, *gc.get_threshold()[1:]) sys.setswitchinterval(0.001) ``` Its other settings are on the [CLI page](/home/access/cli#daemon-config). ## Beside your own event loop `WorkspaceRunner` pins a [workspace](/python/access/in-app) to a thread and event loop of its own. A line waiting on I/O then never stalls your app's loop, and workspaces in one process never wait on each other's I/O. CPU-bound work still shares the GIL with every other thread in the process. The Mirage server hosts every workspace this way. ```python theme={null} from mirage.workspace.runner import WorkspaceRunner runner = WorkspaceRunner(ws) result = await runner.call(runner.ws.shell("ls /")) await runner.stop() ``` `call` runs a coroutine on the workspace's loop and is safe from any other loop; cancelling the caller cancels the coroutine. `stop` closes the workspace (`delete=True` also deletes its state), then stops the loop and refuses new calls. ## MCP and RPC on their own The [MCP](/home/access/mcp) and [RPC](/home/access/rpc) servers are classes you can run over a transport of your own, without the Mirage server. Both serve one session of a [workspace](/python/access/in-app). ```python theme={null} from mcp.server.stdio import stdio_server from mirage.server.mcp import MirageMcpServer server = MirageMcpServer(ws, session_id="agent").server async with stdio_server() as (read, write): options = server.create_initialization_options() await server.run(read, write, options) ``` `MirageMcpServer(workspace, stale_write_protection=True, name="mirage", version=..., session_id=None, operations=None, all_calls=False)`. Its `server` is the MCP SDK's low-level `Server`. `all_calls=True` adds the [VFS calls and explain](/home/access/mcp#vfs-calls). ```python theme={null} from mirage.server.rpc import MirageRpcServer server = MirageRpcServer(ws, session_id="agent") answer = await server.handle({ "jsonrpc": "2.0", "id": 1, "method": "vfs/readdir", "params": {"path": "/"}, }) ``` `MirageRpcServer(workspace, session_id=None, operations=None, name="mirage", version=...)`. `handle(message)` answers one message, and `None` for a notification. `serve(read_line, write_line)` answers newline-delimited messages until `read_line` returns `""`. ## What is particular to this server The protocol is the same on both servers. These are the differences in how this one serves it: * **Legacy `scp -O`.** The SCP protocol is served, as well as SFTP. * **`authorized_keys` options.** asyncssh enforces OpenSSH's options (`from=`, `command=`, ...), and `command=` forces the line that runs. `mirage-profile` binds the key to a [profile](/home/access/ssh#auth-optional) and `mirage-account` opens only that [account](/home/access/http#accounts)'s workspaces. * **Terminal line limit.** 1024 characters. * **A thread per workspace.** Each workspace runs on its own thread and event loop through a [`WorkspaceRunner`](#beside-your-own-event-loop), so a busy workspace does not hold up another or the HTTP server. ## Code map | Path | What | | - | - | | [`mirage/server/app.py`](https://github.com/strukto-ai/mirage/blob/main/python/mirage/server/app.py) | `build_app`: routers, MCP and RPC endpoints, the SSH lifespan. | | [`mirage/server/daemon.py`](https://github.com/strukto-ai/mirage/blob/main/python/mirage/server/daemon.py) | The daemon entry the CLI starts. | | [`mirage/server/routers/`](https://github.com/strukto-ai/mirage/tree/main/python/mirage/server/routers) | The HTTP routes: workspaces, sessions, shell, tools, jobs, asks. | | [`mirage/server/mcp/`](https://github.com/strukto-ai/mirage/tree/main/python/mirage/server/mcp) | `MirageMcpServer`, the `/mcp` endpoint, and the stdio relay `mirage mcp` runs. | | [`mirage/server/rpc/`](https://github.com/strukto-ai/mirage/tree/main/python/mirage/server/rpc) | `MirageRpcServer`, the `/rpc` endpoint, and the stdio relay `mirage rpc` runs. | | [`mirage/server/ssh/`](https://github.com/strukto-ai/mirage/tree/main/python/mirage/server/ssh) | The SSH server: shell, exec, SFTP and SCP. | | [`mirage/workspace/tools/`](https://github.com/strukto-ai/mirage/tree/main/python/mirage/workspace/tools) | The agent tool table behind `session.tools`, which every interface calls. | | [`mirage/cli/`](https://github.com/strukto-ai/mirage/tree/main/python/mirage/cli) | The `mirage` CLI, one module per verb. | ## Custom VFS calls and streaming reads `POST /v1/workspaces/{id}/vfs/{name}` dispatches a registered VFS operation with JSON `{ "path": "/data/item", "kwargs": {} }` and returns its result as JSON. It uses the authenticated request's session and the ordinary dispatcher; callers cannot override session or admission fields. Binary values use the server's base64 JSON representation. `POST /v1/workspaces/{id}/vfs/read` with `{ "path": "/data/item", "stream": true }` streams `application/octet-stream`. It uses the same authentication and file policy as other VFS routes, with bounded reads and cancellation cleanup. # Agno Source: https://docs.mirage.strukto.ai/python/agents/agno Give Agno agents shell-based filesystem access to any Mirage workspace using MirageToolkit. [Agno](https://github.com/agno-agi/agno) is an agent framework that groups related tools into `Toolkit` classes. Mirage ships `MirageToolkit`, a toolkit that runs Mirage's seven tools in a workspace instead of on the host. ## Install ```bash theme={null} uv add 'mirage-ai[agno]' ``` ## Usage ```python theme={null} import asyncio from agno.agent import Agent from agno.models.openai import OpenAIChat from mirage import MountMode, RAMVFS, Workspace from mirage.agents.agno import MirageToolkit ws = Workspace({"/data": RAMVFS()}, mode=MountMode.WRITE) agent = Agent( model=OpenAIChat(id="gpt-5.4-mini"), tools=[MirageToolkit(ws)], instructions=("You have access to a virtual filesystem via shell " "tools. Use them to explore and read files."), markdown=True, ) async def main() -> None: await ws.shell('echo "hello from mirage" | tee /data/hello.txt') await agent.aprint_response( "List all files under /data and show the contents of each one.") asyncio.run(main()) ``` ## Tools The toolkit serves the session's seven tools, [`session.tools`](/python/access/in-app#session-tools), as far as the session's profile leaves them (`session.tools.names()`), each as a sync and async pair under one name: Agno calls the async one in `arun` and `aprint_response`, and the sync one otherwise. ## Exports | Symbol | Purpose | | - | - | | `MirageToolkit` | Agno toolkit backed by a Mirage Workspace. | | `MIRAGE_SYSTEM_PROMPT` | The default system prompt: how the Mirage filesystem differs from a plain one. | | `build_system_prompt` | Build a system prompt with optional mount info and extra instructions. | ## Examples * [`examples/python/agents/agno/agno_example.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/agents/agno/agno_example.py), `Agent` with `MirageToolkit` over a RAM workspace, sync and async. # Claude Agent SDK Source: https://docs.mirage.strukto.ai/python/agents/claude-agent-sdk Run Anthropic's Claude Agent SDK against a Mirage workspace through an in-process MCP server of Mirage's tools. The [Claude Agent SDK](https://code.claude.com/docs/en/agent-sdk/) builds agents on Claude. Mirage exposes any `Workspace` to the SDK as an in-process MCP server, so every file and shell operation the agent runs is routed through Mirage instead of the host filesystem. This is distinct from [Claude Code](/home/agents/claude-code), the `claude` CLI run as it is on a workspace. Use this SDK integration when you build your own agent with `claude_agent_sdk.query()` and want Mirage tools rather than the built-in file tools. ## Install ```bash theme={null} uv add 'mirage-ai[claude-agent-sdk]' ``` ## Usage `build_options` wires a workspace into a ready-to-use `ClaudeAgentOptions`: it registers the Mirage MCP server, restricts the agent to Mirage's tools, and injects a system prompt describing the mounted paths. ```python theme={null} import asyncio from claude_agent_sdk import query from mirage import MountMode, RAMVFS, Workspace from mirage.agents.claude_agent_sdk import build_options async def main() -> None: ws = Workspace({"/": RAMVFS()}, mode=MountMode.WRITE) try: async for msg in query( prompt="Write 'hi from mirage' to /hello.txt, then cat it.", options=await build_options(ws), ): print(msg) finally: await ws.close() asyncio.run(main()) ``` ## Composing with other MCP servers Inside `main`, use `MirageServer` directly to combine Mirage with other servers: ```python theme={null} from claude_agent_sdk import ClaudeAgentOptions from mirage.agents.claude_agent_sdk import MirageServer, build_system_prompt options = ClaudeAgentOptions( mcp_servers={"mirage": MirageServer(ws), "github": github_server}, allowed_tools=["mcp__mirage__*", "mcp__github__*"], tools=[], system_prompt=await build_system_prompt(workspace=ws), ) ``` ## Shell To keep Claude's own Bash tool and run it in a workspace, point the SDK at `mirage-bash`, as for [Claude Code](/home/agents/claude-code#shell), and give it Mirage's other tools over [`mirage mcp`](/home/access/mcp) in place of Claude's file tools. Both reach one workspace that the Mirage daemon serves: ```bash theme={null} mirage workspace create workspace.yaml --id demo ``` ```python theme={null} import shutil from claude_agent_sdk import ClaudeAgentOptions options = ClaudeAgentOptions( cwd="/Users/me/project", env={ "CLAUDE_CODE_SHELL": shutil.which("mirage-bash"), "MIRAGE_WORKSPACE": "demo", }, mcp_servers={ "mirage": {"type": "stdio", "command": "mirage", "args": ["mcp", "-w", "demo"]}, }, allowed_tools=["Bash", "mcp__mirage__*"], disallowed_tools=["Read", "Edit", "Write", "Glob", "Grep", "mcp__mirage__shell"], ) ``` * Bash runs in the workspace, and Mirage's `read`, `write`, `edit`, `ls`, `grep` and `glob` take the place of Claude's Read, Edit, Write, Glob and Grep, so every file the agent touches goes through Mirage. * Mount the project and `/tmp` at their own paths, as the [Claude Code page](/home/agents/claude-code#shell) shows, so `cd` carries over. * To run under a [profile](/home/profiles), create a session with `mirage workspace session create -w demo -s agent -p reviewer`, then set `MIRAGE_SESSION` to `agent` and add `-s agent` to the `mirage mcp` arguments. ## Tools The server serves the session's seven tools, [`session.tools`](/python/access/in-app#session-tools): `shell`, `read`, `write`, `edit`, `ls`, `grep` and `glob`, named `mcp__mirage__<tool>` in the SDK. It carries the ones the session's profile leaves it (`session.tools.names()`). ## Exports | Symbol | Purpose | | - | - | | `MirageServer` | Create an in-process Mirage server for the Claude Agent SDK, with the tools the session's profile leaves it. | | `build_options` | Build ClaudeAgentOptions backed by a Mirage Workspace. | | `MIRAGE_SYSTEM_PROMPT` | The default system prompt: how the Mirage filesystem differs from a plain one. | | `build_system_prompt` | Build a system prompt with optional mount info and extra instructions. | # Claude Managed Agents Source: https://docs.mirage.strukto.ai/python/agents/claude-managed-agents Make a Mirage workspace the self-hosted environment of an agent on Claude Managed Agents. [Claude Managed Agents](https://platform.claude.com/docs/en/managed-agents/overview) runs the agent on Anthropic's servers. In a [self-hosted environment](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes), a worker you run answers its `bash`, `read`, `write`, `edit`, `glob` and `grep` calls. `mirage_tools(ws)` gives that worker Mirage's versions, so every call runs in the workspace, under its profile, mounts and policies. The worker only connects out to Anthropic, so it can run inside your own server. ## Install ```bash theme={null} uv add 'mirage-ai[claude-managed-agents]' ``` ## Run a worker The workspace here keeps its files in Redis next to RAM, which needs a Redis server and the `redis` extra: ```bash theme={null} docker run -d -p 6379:6379 redis uv add 'mirage-ai[redis]' ``` Create a self-hosted environment and an agent with the `agent_toolset_20260401` toolset as [Anthropic's guide](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes) shows, then serve its sessions from the workspace: ```python theme={null} import asyncio import os from anthropic import AsyncAnthropic from mirage import MountMode, Workspace from mirage.agents.claude_managed_agents import mirage_tools from mirage.vfs.ram import RAMVFS from mirage.vfs.redis import RedisVFS ws = Workspace( {"/workspace": RAMVFS(), "/redis": RedisVFS(url="redis://localhost:6379/0")}, mode=MountMode.WRITE, ) worker = AsyncAnthropic().beta.environments.work.worker( environment_id=os.environ["ANTHROPIC_ENVIRONMENT_ID"], environment_key=os.environ["ANTHROPIC_ENVIRONMENT_KEY"], tools=mirage_tools(ws), ) asyncio.run(worker.run()) ``` ## How it behaves * The tools keep the toolset's names. One the session's [profile](/home/policy/overview) would always refuse is left out: a read-only workspace gets no `write` or `edit`. * `bash` runs Mirage's shell, so a line sees the workspace's mounts and commands, not the worker's machine. A `restart` is refused, since the session keeps its directory and variables. A relative path resolves against the session's working directory, which `cd` moves. * `write` overwrites a file only after the agent read all of it, and `write` and `edit` refuse a file that changed since the agent read it. `stale_write_protection=False` turns that off. * `session_id=` runs the tools as another session, with its profile. * `web_search` and `web_fetch` still run on Anthropic's servers. Turn them off in the agent's toolset to keep the agent to the workspace. ## Example [`examples/python/agents/claude_managed_agents/redis_report.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/agents/claude_managed_agents/redis_report.py) creates the agent and a session, serves the session from a RAM and Redis workspace, asks the agent to total `/workspace/orders.csv` into `/redis/report.md`, and prints the report from Redis. # Haystack Source: https://docs.mirage.strukto.ai/python/agents/haystack Give a Haystack Agent a bash tool over a Mirage workspace via MirageShellTool. [Haystack](https://haystack.deepset.ai) is deepset's framework for building LLM applications and agents. The integration is maintained by deepset and lives in their [haystack-core-integrations](https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/mirage) repository, so it installs as its own package rather than as a `mirage-ai` extra. ## Install ```bash theme={null} uv add mirage-haystack ``` > [!NOTE] > > `mirage-haystack` pins an exact `mirage-ai` version rather than tracking the latest, because Mirage is pre-1.0. Check the [integration's `pyproject.toml`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/mirage/pyproject.toml) for which one, since installing it may move an existing `mirage-ai` in your environment. ## Usage Describe the mounts, wrap the workspace in a tool, hand the tool to an `Agent`. ```python theme={null} from haystack.components.agents import Agent from haystack.components.generators.chat import OpenAIChatGenerator from haystack.dataclasses import ChatMessage from haystack_integrations.tools.mirage import ( MirageMount, MirageShellTool, MirageWorkspace, ) workspace = MirageWorkspace([ MirageMount(path="/data", vfs="ram"), MirageMount(path="/s3", vfs="s3", config={"bucket": "my-bucket"}, read_only=True), ]) tool = MirageShellTool( workspace, allowed_commands=["ls", "cat", "grep", "head", "wc", "cp"], ) agent = Agent(chat_generator=OpenAIChatGenerator(model="gpt-4o-mini"), tools=[tool]) result = agent.run(messages=[ ChatMessage.from_user("How many lines in /s3/log.txt mention 'alert'?"), ]) print(result["messages"][-1].text) ``` The tool exposes a single `command` parameter, so the model writes ordinary bash and pipes across mounts. Its description is generated from the mount tree, so the model is told which paths exist without you writing a prompt for it. ## Guarding what the agent can do Two controls, and they are not interchangeable. `read_only=True` on a mount is the write boundary. Mirage refuses every write to that mount whatever command is used, so this is what prevents modification and deletion. `allowed_commands` restricts which command names may run. It is checked against every command Mirage would execute, including ones nested in `$(...)`, backticks and subshells, so `ls "$(rm x)"` is rejected unless `rm` is allowed too. Treat it as steering, not a sandbox: allowing a command that runs other commands (`eval`, `bash`, `sh`, `source`, `xargs`) effectively allows anything. Commands never reach the host shell either way. Mirage interprets them itself, so the blast radius is the mounts you attached. ## Exports | Symbol | Purpose | | - | - | | `MirageWorkspace` | Declares the mount tree, and runs commands against it with `run` / `run_async`. Serializable with `to_dict` / `from_dict`. | | `MirageMount` | One mount: `path`, `vfs`, `config`, `read_only`. | | `MirageShellTool` | The Haystack `Tool` that gives an `Agent` the bash surface. | | `MirageError` | Base error, with `MirageConfigError` and `MirageCommandNotAllowedError`. | ## Links * [Integration page](https://haystack.deepset.ai/integrations/mirage) on haystack.deepset.ai. * [Source and README](https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/mirage) in `haystack-core-integrations`. * [`mirage-haystack`](https://pypi.org/project/mirage-haystack) on PyPI. # Overview Source: https://docs.mirage.strukto.ai/python/agents/index Connect a coding agent or an agent framework to a Mirage workspace. ## Coding Agents Claude Code, Codex and Grok Build run as they are, on a workspace the `mirage` CLI creates, whatever language you build in. Their guides are under [Agents](/home/agents#coding-agents). ## Agent SDKs Your program holds the workspace and hands it to the framework. | Framework | Hand it | The agent gets | | - | - | - | | [Claude Agent SDK](/python/agents/claude-agent-sdk) | `MirageServer(ws)` | Mirage's seven tools | | [Agno](/python/agents/agno) | `MirageToolkit(ws)` | Mirage's seven tools | | [OpenAI Agents](/python/agents/openai-agents) | `MirageShellExecutor(ws)`, `MirageEditor(ws)`, `MirageSandboxClient(ws)` | its shell, patch and sandbox tools, run in Mirage | | [LangChain Deep Agents](/python/agents/langchain) | `LangchainWorkspace(ws)` | its file and shell tools, run in Mirage | | [Pydantic AI](/python/agents/pydantic-ai) | `MirageWorkspace(ws)` | its workspace, so every file and shell tool runs in Mirage | | [Haystack](/python/agents/haystack) | `MirageShellTool(...)` | a bash tool | Mirage's seven tools are the session's [`session.tools`](/python/access/in-app#session-tools): `shell`, `read`, `write`, `edit`, `ls`, `grep` and `glob`. A session gets the ones its [profile](/home/policy/explain#which-tools-the-agent-gets) leaves it (`session.tools.names()`), so an agent is never offered a tool every call of which would be refused. Each framework is an extra: `claude-agent-sdk`, `agno`, `openai`, `deepagents` or `pydantic-ai`. ```bash theme={null} uv add 'mirage-ai[agno]' ``` Haystack installs as `mirage-haystack`, which deepset maintains. ## API & Environment The provider runs the agent, and the workspace is its environment: its own shell and file tools run in Mirage. | API | Hand it | The agent gets | | - | - | - | | [OpenAI Agents API](/python/agents/openai-agents-api) | a `self_hosted` environment, through [exec-server forward](/home/agents/codex#exec-server-forward) | its shell, file and patch tools, run in Mirage | | [Claude Managed Agents](/python/agents/claude-managed-agents) | `mirage_tools(ws)`, in an `EnvironmentWorker` | its `bash`, `read`, `write`, `edit`, `glob` and `grep`, run in Mirage | # LangChain (Deep Agents) Source: https://docs.mirage.strukto.ai/python/agents/langchain Back Deep Agents with a Mirage workspace via LangchainWorkspace. [Deep Agents](https://github.com/langchain-ai/deepagents) is LangChain's framework for long-horizon coding agents. It accepts a pluggable `backend` for filesystem and shell operations, and Mirage ships one. ## Install ```bash theme={null} uv add 'mirage-ai[deepagents]' langchain-anthropic ``` Bring your own LangChain chat model, such as `langchain-anthropic` or `langchain-openai`. ## Usage ```python theme={null} import asyncio from deepagents import create_deep_agent from langchain_anthropic import ChatAnthropic from mirage import MountMode, Workspace from mirage.agents.langchain import ( LangchainWorkspace, build_system_prompt, extract_text, ) from mirage.vfs.ram import RAMVFS ws = Workspace({"/": RAMVFS()}, mode=MountMode.WRITE) async def main() -> None: agent = create_deep_agent( model=ChatAnthropic(model="claude-sonnet-4-20250514"), system_prompt=await build_system_prompt( mount_info={"/": "In-memory filesystem (read/write)"}, ), backend=LangchainWorkspace(ws), ) result = await agent.ainvoke({ "messages": [{"role": "user", "content": "Create /report.md and summarize."}], }) for text in extract_text(result["messages"][-1:]): print(text) asyncio.run(main()) ``` ## Multimodal files `read_file` can pass images, PDFs, audio, video, PPT, and PPTX files from a Mirage mount to a model as multimodal content. The selected model and provider must support the corresponding input type. Text files continue to use line-based pagination. ## Exports | Symbol | Purpose | | - | - | | `LangchainWorkspace` | Deep Agents backend backed by a Mirage Workspace. | | `MIRAGE_SYSTEM_PROMPT` | The default system prompt: how the Mirage filesystem differs from a plain one. | | `build_system_prompt` | Build a system prompt with optional mount info and extra instructions. | | `extract_text` | Extract text content from LangGraph messages. | ## Examples * [`examples/python/agents/langchain/ram_pdf_deepagent.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/agents/langchain/ram_pdf_deepagent.py), RAM-backed PDF reading with no external storage credentials. * [`examples/python/agents/langchain/ram_deepagent.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/agents/langchain/ram_deepagent.py), RAM-only sandbox. * [`examples/python/agents/langchain/s3_deepagent.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/agents/langchain/s3_deepagent.py), read-only S3 exploration. * [`examples/python/agents/langchain/databricks_volume_deepagent.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/agents/langchain/databricks_volume_deepagent.py), Databricks volume exploration with an explicit workspace host and access token. # OpenAI Agents SDK Source: https://docs.mirage.strukto.ai/python/agents/openai-agents Run openai-agents against a Mirage workspace using MirageShellExecutor, MirageEditor, MirageSandboxClient, and MirageCapability. The OpenAI Agents Python SDK ([openai-agents](https://github.com/openai/openai-agents-python)) ships built-in `ShellTool` and `ApplyPatchTool` primitives, plus the newer `SandboxAgent`. Mirage provides drop-in replacements that route every shell command, patch, and sandbox call through your `Workspace` instead of the host. ## Install ```bash theme={null} uv add 'mirage-ai[openai]' ``` ## Tools (`ShellTool` + `ApplyPatchTool`) ```python theme={null} import asyncio from agents import Agent, ApplyPatchTool, Runner, ShellTool from mirage import MountMode, Workspace from mirage.agents.openai_agents import ( MirageEditor, MirageShellExecutor, build_system_prompt, ) from mirage.vfs.ram import RAMVFS ws = Workspace({"/": RAMVFS()}, mode=MountMode.WRITE) async def main() -> None: agent = Agent( name="Mirage RAM Agent", model="gpt-5.5-mini", instructions=await build_system_prompt( mount_info={"/": "In-memory filesystem (read/write)"}, ), tools=[ ShellTool(executor=MirageShellExecutor(ws)), ApplyPatchTool(editor=MirageEditor(ws)), ], ) result = await Runner.run(agent, "Create /hello.txt with 'hi' and cat it.") print(result.final_output) asyncio.run(main()) ``` ## Sandbox Agent `SandboxAgent` runs the SDK's own `exec_command`, `apply_patch` and `view_image` tools against a sandbox session. `MirageSandboxClient` makes that session a Mirage workspace, and `MirageCapability` adds the workspace's mounts (backend, mode, commands) to the agent's instructions: ```python theme={null} from agents import Runner from agents.run import RunConfig from agents.sandbox import SandboxAgent, SandboxRunConfig from agents.sandbox.capabilities import Capabilities from mirage.agents.openai_agents import MirageCapability, MirageSandboxClient agent = SandboxAgent( name="Mirage Sandbox Agent", model="gpt-5.5", capabilities=[*Capabilities.default(), MirageCapability()], ) result = await Runner.run( agent, "Summarize /data/report.csv into /notes.md.", run_config=RunConfig(sandbox=SandboxRunConfig( client=MirageSandboxClient(ws))), ) ``` How the session behaves: * Every command starts at the manifest root, `/` unless you configure a `Manifest`, and a `cd` or `export` ends with its command, as in the SDK's other sandboxes. Commands see the manifest's environment. Each sandbox session has its own Mirage session. Its commands run in it side by side, so one left running in the background does not hold up the next. * A command still running after `exec_command`'s yield time keeps running. The model polls it with `write_stdin` and stops it with Ctrl-C (`\u0003`). A direct `exec(..., timeout=...)` raises `ExecTimeoutError`. * Relative paths resolve against the manifest root, and writes create missing parent directories. * A run paused for tool approval resumes on the same workspace and keeps the files the agent wrote. * `exec("ls", "-la", path, shell=False)` quotes each argument. A single string with `shell=False` is one program name, as in the SDK's other sandboxes. ## Exports | Symbol | Purpose | | - | - | | `MirageCapability` | Tell a SandboxAgent's model which Mirage mounts it is working in. | | `MirageEditor` | ApplyPatchEditor backed by a Mirage Workspace. | | `MirageRunner` | Run OpenAI agents with mirage-resolved multimodal attachments. | | `MirageSandboxClient` | The OpenAI Agents SDK sandbox client over an in-process Mirage workspace. | | `MirageSandboxSession` | One SDK sandbox session, backed by its own Mirage shell session. | | `MirageShellExecutor` | ShellTool executor backed by a Mirage Workspace. | | `MIRAGE_SYSTEM_PROMPT` | The default system prompt: how the Mirage filesystem differs from a plain one. | | `build_system_prompt` | Build a system prompt with optional mount info and extra instructions. | ## Examples * [`examples/python/agents/openai_agents/ram_agent.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/agents/openai_agents/ram_agent.py), RAM-only sandbox. * [`examples/python/agents/openai_agents/sandbox_agent.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/agents/openai_agents/sandbox_agent.py), `SandboxAgent` over RAM + S3 + Slack. * [`examples/python/agents/openai_agents/multi_vfs_agent.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/agents/openai_agents/multi_vfs_agent.py), RAM + S3 mounts. * [`examples/python/agents/openai_agents/snapshot.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/agents/openai_agents/snapshot.py), branch & roll back agent state. # OpenAI Agents API Source: https://docs.mirage.strukto.ai/python/agents/openai-agents-api Make a Mirage workspace the self-hosted environment of an agent on OpenAI's Agents API. OpenAI's [Agents API](https://developers.openai.com/api/docs/guides/agents-api/overview) runs the agent on OpenAI's servers. With a `self_hosted` environment, its shell commands, file reads and patches run in a Mirage workspace, under the workspace's profile and mount modes. No sandbox holds the files. The workspace connects through Codex's exec-server relay, set up on the [Codex page](/home/agents/codex#exec-server-forward). The Agents API is in beta. ## Install ```bash theme={null} uv tool install 'mirage-ai[ssh]' uv add openai ``` ## Workspace `/workspace`, where OpenAI's examples work, is scratch space in memory. `/redis` keeps what the agent saves there after the workspace closes, which needs a Redis server and the `redis` extra: ```yaml workspace.yaml theme={null} mode: write mounts: /workspace: vfs: ram /redis: vfs: redis config: url: redis://localhost:6379/0 ``` ```bash theme={null} docker run -d -p 6379:6379 redis uv tool install 'mirage-ai[ssh,redis]' mirage workspace create workspace.yaml --id demo printf 'customer,item,amount\nacme,widget,120\nglobex,gadget,75\nacme,gizmo,30\ninitech,widget,60\nglobex,widget,45\n' \ | mirage shell -w demo -c 'cat > /workspace/orders.csv' ``` ## Create a session ```python theme={null} from openai import OpenAI client = OpenAI() session = client.beta.agents.sessions.create( agent={"model": "gpt-6-luna"}, environment={"type": "self_hosted", "workspace_directory": "/workspace"}, ) print(session.environment.id, session.environment.remote_url) ``` ## Connect the workspace Hand the session's `environment.id` and `environment.remote_url`, with an [environment key](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#authentication), to [`codex exec-server forward`](/home/agents/codex#exec-server-forward) pointed at workspace `demo`. The agent's commands then run in the workspace, and what it writes lands in its mounts. ## Run a task Open the session's event stream, then send the task. The agent's reply streams back while its commands run in the workspace: ```python theme={null} import uuid with client.beta.agents.sessions.events.stream(session.id) as stream: client.beta.agents.sessions.events.create( session.id, events=[ { "type": "agent.session.input.message", "input": [ { "role": "user", "content": [{"type": "input_text", "text": "Total the amount per customer in /workspace/orders.csv and save the totals as a markdown table to /redis/report.md."}], } ], } ], idempotency_key=str(uuid.uuid4()), ) for event in stream: if event.type == "agent.session.turn.output_text.delta": print(event.delta, end="") elif event.type in ("agent.session.turn.completed", "agent.session.turn.failed"): break ``` The report stays in Redis after the session ends: ```bash theme={null} mirage shell -w demo -c 'cat /redis/report.md' ``` ## Example [`examples/python/agents/openai_agents_api/redis_report.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/agents/openai_agents_api/redis_report.py) runs the whole flow: it seeds `/workspace/orders.csv`, starts `mirage codex-exec` and `codex exec-server forward`, sends the task and prints the report. # Pydantic AI Source: https://docs.mirage.strukto.ai/python/agents/pydantic-ai Give Pydantic AI runs a Mirage session as their workspace, so every file and shell tool runs in Mirage. [Pydantic AI](https://github.com/pydantic/pydantic-ai) gives every run a [workspace](https://ai.pydantic.dev/workspace/): the environment its tools reach through `ctx.workspace`. Mirage's `MirageWorkspace` capability supplies a Mirage session as that workspace, so file and shell tools, such as [`pydantic-ai-backend`](https://pypi.org/project/pydantic-ai-backend/)'s `ConsoleCapability`, read, write and run commands across every mount. ## Install ```bash theme={null} uv add 'mirage-ai[pydantic-ai]' 'pydantic-ai-slim[openai]' ``` The extra brings Pydantic AI and the console tools without a model provider; add the provider your agent uses (`openai`, `anthropic`, ...). ## Usage ```python theme={null} import asyncio from pydantic_ai import Agent from pydantic_ai_backends import PERMISSIVE_RULESET, ConsoleCapability from mirage import MountMode, Workspace from mirage.agents.pydantic_ai import MirageWorkspace, build_system_prompt from mirage.vfs.ram import RAMVFS ws = Workspace({"/": RAMVFS()}, mode=MountMode.WRITE) async def main() -> None: agent = Agent( "openai:gpt-4.1", system_prompt=await build_system_prompt( mount_info={"/": "In-memory filesystem (read/write)"}, ), capabilities=[ MirageWorkspace(ws), ConsoleCapability(permissions=PERMISSIVE_RULESET), ], ) result = await agent.run("Create /hello.txt with 'hi' and cat it.") print(result.output) asyncio.run(main()) ``` `ConsoleCapability`'s default ruleset asks before every write and command. Mirage already judges each call through the session's mount modes and profile, so the example allows them in the console and leaves the policy to Mirage. ## Exports | Symbol | Purpose | | - | - | | `MirageWorkspace` | Give runs a Mirage session as their workspace. | | `MirageWorkspaceBackend` | A Mirage session as the environment a Pydantic AI run works in. | | `MIRAGE_SYSTEM_PROMPT` | The default system prompt: how the Mirage filesystem differs from a plain one. | | `build_system_prompt` | Build a system prompt with optional mount info and extra instructions. | `MirageWorkspace(ws, session_id="agent")` acts as that session, so its profile judges every call. Commands run in Mirage's shell, each in a clone of the session at its working directory, as a subshell does: a `cd` or an `export` in one command does not reach the next. Files go through the session's `ws.vfs`, and symlinks resolve through the namespace. The run's `WorkspaceRef` names the session; a ref in message history that names any other session is declined. The backend passes Pydantic AI's workspace conformance suite, except the rules that need POSIX processes (`mkfifo`) or mode bits: Mirage's permissions are the session profile, not `chmod`. ## Examples * [`examples/python/agents/pydantic_ai/s3_agent.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/agents/pydantic_ai/s3_agent.py), read-only S3 exploration. * [`examples/python/agents/pydantic_ai/s3_pdf_agent.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/agents/pydantic_ai/s3_pdf_agent.py), native PDF input from S3. * [`examples/python/agents/pydantic_ai/slack_pdf_agent.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/agents/pydantic_ai/slack_pdf_agent.py), native image and PDF reads from Slack. # airtable Source: https://docs.mirage.strukto.ai/python/cli/airtable Supported Airtable commands for querying and changing records and comments. Query Airtable bases, tables, records and comments, and create, update or delete records. Mirage defines this command tree over the [Airtable Web API](https://airtable.com/developers/web/api/introduction). ## Setup Create a token with the scopes in [Airtable setup](/home/setup/airtable). Reads need record and schema read scopes; writes and comments need their corresponding write scopes. ```python theme={null} from mirage import Workspace from mirage.commands.cli.builtin.airtable import AIRTABLE from mirage.core.airtable.config import AirtableConfig config = AirtableConfig(token="pat_...") ws = Workspace({}) ws.register_cli("airtable", AIRTABLE, config) ``` No service mount is required. For YAML and multiple accounts, see the [CLI overview](/python/cli/index#register-a-cli). ## Supported commands Run `airtable <command> --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `airtable base list` | List the bases the token reaches as JSON | | `airtable base get` | Get one base and its tables (base.json) | | `airtable table get` | Get one table's fields and views (table.json) | | `airtable record list` | List records as JSONL (records.jsonl) | | `airtable record get` | Get one record as a JSONL line | | `airtable record create` | Create records from --fields or stdin | | `airtable record update` | Update records' cells (PATCH) from RECORD --fields or stdin | | `airtable record delete` | Delete records by RECORD or from stdin | | `airtable comment list` | List a record's comments, newest first | | `airtable comment add` | Comment on a record | ## Read and filter records ```bash theme={null} airtable base list airtable table get --base appRoadmapBase001 Features airtable record list --base appRoadmapBase001 --table tblFeatures000001 --formula "{Status} = 'Done'" airtable record get --base appRoadmapBase001 --table tblFeatures000001 recFeat0000000003 airtable comment list --base appRoadmapBase001 --table tblFeatures000001 recFeat0000000003 ``` `--base` takes a base ID. `--table` takes a table ID or name. Find these in API output or in the VFS's `name__id` directory names; record lines carry `record_id` explicitly. `--formula` and `--view` filter on the server. `base list` and `comment list` return JSON arrays. `base get` and `table get` return the same schema objects as the mount. Record commands return JSONL. ## Write records ```bash theme={null} airtable record create --base appRoadmapBase001 --table tblFeatures000001 --fields '{"Name":"Search"}' airtable record update --base appRoadmapBase001 --table tblFeatures000001 recFeat0000000003 --fields '{"Status":"Done"}' airtable record delete --base appRoadmapBase001 --table tblFeatures000001 recFeat0000000003 echo 'Ready to ship' | airtable comment add --base appRoadmapBase001 --table tblFeatures000001 recFeat0000000003 ``` For bulk writes, pipe record JSONL into `record create`, `record update` or `record delete` without the single-record arguments: ```bash theme={null} jq -c 'select(.fields.Status == "Todo") | .fields.Status = "Done"' /work/records.jsonl \ | airtable record update --base appRoadmapBase001 --table tblFeatures000001 ``` | Operation | Required fields in each stdin line | | - | - | | `record create` | `fields`; existing `record_id` and `created_time` are ignored | | `record update` | `record_id` and `fields`; omitted fields remain unchanged | | `record delete` | `record_id` | Each line may contain only `record_id`, `created_time` and `fields`. Mirage validates every line before the first request, drops computed fields from stdin writes, and sends batches of at most ten records. Inline `--fields` is sent as given. Use `--typecast` to allow Airtable's type conversion. ## VFS and limits The optional [Airtable VFS](/python/vfs/airtable) exposes bases and tables as files. Record output uses the same JSONL shape, so mounted records can feed the CLI through stdin. The CLI uses its own account config and needs no Airtable mount. * `base_ids` restricts accessible bases, including writes; an excluded base is refused before a request. * Without `--max-records`, a list exceeding `max_read_records` fails with exit 1. An explicit `--max-records N` sets the requested cap. * Bad flags, malformed JSON and invalid stdin lines exit 2. API failures exit 1. A partial write prints the completed records and exits 1; it does not roll them back. * Requests use the config's per-base rate limit. Reads retry `429`, `502` and `503`; writes retry only `429`, to avoid repeating a write that may already have succeeded. The service is reached by IDs and the CLI's config. Input files such as `/work/records.jsonl` enter through shell stdin; they can live on any readable workspace mount. This is Mirage's Apache-2.0 command implementation for the Web API. No compatibility with a separate Airtable CLI is claimed; the API link documents the service rather than an upstream CLI implementation. See [compatibility and licenses](/home/setup/clis#compatibility-and-licenses). # Customize CLI Source: https://docs.mirage.strukto.ai/python/cli/custom Define a typed or script CLI with shared parsing, account config and VFS access. Define a custom CLI when an agent needs service operations with a stable command grammar. Use a typed `CLI` for parsed commands and generated help, or a script CLI when the program should parse its own arguments. Shell builtins and CLIs keep separate catalogs and dispatch. Both use `CommandSpec` for argument parsing. ## Define a typed command Each handler receives `(accessor, paths, texts, ctx)`, the shape a shell command takes: the installation's accessor, the operands, and the same `Context`. The install builds the accessor once from its validated config (`CLI.accessor`, default `NOOPAccessor`, which only holds the config at `accessor.config`) and the workspace closes it when the install goes. The example below shows the registration and parsing contract; the runnable [pager example](https://github.com/strukto-ai/mirage/blob/main/examples/python/cli/pager.py) adds a mutable incident service and shared cross-language coverage. ```python theme={null} from typing import Literal from pydantic import BaseModel, ConfigDict from mirage import (Argument, CLI, CLIHandler, CommandSpec, Context, FlagView, PathSpec, Workspace) from mirage.accessor import NOOPAccessor from mirage.io import IOResult class PagerConfig(BaseModel): model_config = ConfigDict(extra="forbid") account: Literal["engineering", "support"] async def acknowledge( accessor: NOOPAccessor, paths: list[PathSpec], texts: list[str], ctx: Context, ) -> tuple[bytes, IOResult]: incident_id = texts[0] by = FlagView(ctx.flags, ctx.spec).as_str("by") account = accessor.config.account return f"[{account}] acknowledged {incident_id} by {by}\n".encode(), IOResult() PAGER = CLI( spec=CommandSpec( name="pager", subcommands=(CommandSpec( name="ack", arguments=( Argument("INCIDENT_ID"), Argument("--by", required=True), ), ),), ), handlers={"ack": CLIHandler(fn=acknowledge, write=True)}, config_model=PagerConfig, ) ws = Workspace({}) ws.register_cli("pager-eng", PAGER, {"account": "engineering"}) ws.register_cli("pager-support", PAGER, {"account": "support"}) ``` The same CLI can be installed for multiple accounts. Service IDs use textual operands; file operands use `type="path"`. Read flags through `FlagView(ctx.flags, ctx.spec)` so a read of an undeclared option fails rather than looking like an omitted flag. ## Choose the command shape | Node | Declares | Handler input | | - | - | - | | Leaf | `CommandSpec.arguments`, a `CLIHandler` binding | Paths and text as arguments, parsed flags on `ctx` | | Group | `subcommands`, optional inherited options | Dispatches to a leaf | | Script CLI | `CLI.script`, optional runtime | Raw argv, stdin and environment | A typed node is a leaf or a group. Names and aliases are single words; child names and aliases share one namespace. Options cannot collide across ancestors and descendants. Construction validates the tree and compiles the grammar; do not repeat parser validation in every handler. `CommandSpec.arguments` holds options and positional arguments: a dashed name such as `--by` declares an option; a bare name declares a positional. `CLI.handlers` maps canonical paths below the root to `CLIHandler` bindings, such as `"ack"`, `"incident ack"`, or `""` for a single-command program. Declare `config_model` on the account `CLI`. Registration validates each installation, and the default `NOOPAccessor` holds that account's settings at `accessor.config`. Without a config model, a typed CLI accepts no config and `accessor.config` is `None`. Mark mutating `CLIHandler` bindings `write=True`. This classifies the command for policy and cache invalidation; it does not grant permission or perform the mutation. Policy reads it as `CommandContext.write`, so one `pre_command` method can refuse every writing verb. Descriptions, options and operands supply `--help` and `man` at every level. ## Register the program Installing a CLI directly is the shortest path: ```python theme={null} ws.register_cli("pager-eng", PAGER, {"account": "engineering"}) ``` The installed name is the dispatch key and does not have to equal the spec's root name. This is what makes one tree usable for several accounts. To resolve a bare name from workspace YAML, register the CLI before loading the workspace: ```python theme={null} from mirage import register_cli_spec register_cli_spec(PAGER) ``` ```yaml theme={null} clis: pager-eng: cli: pager config: account: engineering ``` `cli:` may instead point directly at `module:ATTR` or `./file.py:ATTR`. Relative files resolve next to the YAML file. A packaged Python CLI can publish the same CLI without import side effects: ```toml theme={null} [project.entry-points."mirage.clis"] pager = "my_package.cli:PAGER" ``` Registered names and builtins win over direct references and entry points. Registering a name already held by another explicit registration or builtin fails; an explicit registration may intentionally shadow an entry point. Registration and installation are host-side lifecycle operations. There is no shell `install` or `uninstall` command, so an agent can use a CLI it was given but cannot remove it. A deployment that must pin the head word should enforce that with policy; shell functions can otherwise shadow it like they do in bash. ## Serve a CLI on a mount Registered on a mount, a typed CLI serves its verbs there as a command tree. Its leaves get the mount's accessor, so the tree declares no `config_model`, `accessor`, `script` or `runtime`: ```python theme={null} from mirage import MountMode, RAMVFS from mirage.accessor.ram import RAMAccessor async def tag(accessor: RAMAccessor, paths: list[PathSpec], texts: list[str], ctx: Context) -> tuple[None, IOResult]: accessor.store.files["/" + paths[0].vfs_path] = " ".join(texts).encode() return None, IOResult() NOTES = CLI( spec=CommandSpec(name="notes", subcommands=(CommandSpec( name="tag", arguments=(Argument("note", type="path"), Argument("tags", nargs="+")), ),)), handlers={"tag": CLIHandler(fn=tag, write=True)}, ) ws = Workspace({"/notes/": RAMVFS()}, mode=MountMode.WRITE) ws.mount("/notes/").register_commands([NOTES]) ``` `notes tag /notes/a.md draft` walks, helps and refuses like an installed CLI's line, and runs on the working directory's mount when it serves `notes`. Otherwise a writing leaf selects the only writable matching mount; several writable matches produce an ambiguity error. Use `cd` to select the target. Read-only leaves keep the first matching mount, with a debug log when several match. Help remains available without selecting a write destination. A VFS hands the same tree to every mount of it with `commands=[NOTES]`. Its leaves reach the backend past the dispatcher. Mutating leaves must declare `write=True`, run only when the mount is writable, and clear cached mount listings on return. ## Use workspace files Build the service client in the CLI's accessor (`CLI.accessor`), from the install's config, so one install keeps one client for every call; the workspace closes it when the install goes. A CLI should not find a matching VFS to obtain credentials or a backend accessor. Reuse core service functions and accessor classes between CLI and VFS implementations where their behavior is the same. For file arguments such as uploads or attachments, use `ctx`: | Field | Purpose | | - | - | | `vfs` | The session's files, the same API as `session.vfs`: `read`, `write`, `stat`, `readdir`, `symlink`, `readlink` and the rest, with workspace policy and mount modes applied | | `session` | Live, gated session reads and writes; `ctx.env` is the frozen invocation snapshot | `vfs.stat(path, nofollow=True)` reports a link itself. `vfs.mount_of(path)` names the mount serving a path, `vfs.is_mount(path)` says whether a path is a mount root, and `vfs.submounts(path)` lists the mounts below a folder. A mount the session hides is listed as the nearest folder above it that the session sees, so a CLI that removes a folder can refuse without learning the hidden name. A CLI that prints paths from its own data, as git prints its index, hands its output over as rows instead of bytes: each row names the path it shows, and the command prints none of it itself. The workspace drops the rows the session hides, then calls the renderer with the rest, so no line, count, total or column width stands for a hidden path: ```python theme={null} from dataclasses import dataclass from mirage import Context, PathSpec from mirage.accessor import NOOPAccessor from mirage.io.types import IOResult, Rows @dataclass(frozen=True) class Entry: path: PathSpec size: int async def render(shown: list[Entry]) -> bytes: lines = [f"{entry.path.virtual} {entry.size}\n" for entry in shown] return "".join([*lines, f"{len(shown)} files\n"]).encode() async def tracked( accessor: NOOPAccessor, paths: list[PathSpec], texts: list[str], ctx: Context, ) -> tuple[None, IOResult]: # The CLI's own record of the files it tracks. kept = {"/data/a.txt": 1, "/data/b.txt": 3} entries = [Entry(PathSpec.from_str_path(p), n) for p, n in kept.items()] return None, IOResult(rows=Rows(entries, render)) ``` The renderer runs inside the command's timeout. A handler hands over rows or stdout, never both. Declare file options and operands with `type="path"`; preserve the resulting `PathSpec` values when calling `ctx.vfs`. Use `PathSpec.from_str_path(value, cwd=ctx.cwd)` for a path string from config, and derive paths with `join` and `parent`. Do not convert them to plain strings before filesystem access. Direct handler callers may leave `ctx.vfs` unset; a handler requiring files must refuse when it is absent. Account CLI writes, including failed writes that may have reached the service, expire mounted caches. Config-free filesystem CLIs rely on the dispatcher's per-path invalidation. A script marked as a write also expires caches because its config and service access are opaque. An install's accessor decides which mounts that is: override `Accessor.reaches(peer)` to answer False for a mount's accessor its writes cannot change. The default reaches every mount. ## Snapshots and credentials A named typed CLI is saved by spec name. Fields declared as Pydantic secrets in `config_model` are redacted. Loading that snapshot must provide fresh install config through `clis=`; Mirage refuses to restore redacted credentials as if they were usable values. The loading process must also make the spec name resolvable, or pass `(cli, config)` as that install's `clis=` override. A tree installed directly in live code survives `Workspace.copy`, which carries the live CLI and revealed config together. A script CLI is different: the script source is embedded in the snapshot and its opaque config is serialized verbatim because there is no config model to identify secrets. Keep credentials in the environment, or provide fresh script config through `clis=` when loading. ## Script CLIs Use `script:` when the program should own its grammar or should have no Mirage imports: ```yaml theme={null} clis: pager: script: ./cli/pager.py runtime: monty config: width: 80 ``` The file is embedded at load. Words after the head arrive as argv, piped input arrives on stdin, and config arrives as JSON in `MIRAGE_CLI_CONFIG`. The program's stdout, stderr, and exit status become the shell result. A script CLI cannot declare `config_model`, subcommands, or function handlers; it parses and documents its own options, including `--help`. Slot 0 is the installed name on every runtime, so two installs can identify themselves and user-facing errors can name the invoked program. Arguments begin at index 1. A YAML script declares no Mirage grammar, so every option reaches the program unchanged. A script CLI constructed in code may supply a `CommandSpec` to opt into Mirage parsing and generated help. Runtime argument spellings differ: | Runtime | Arguments | Standard input | | - | - | - | | monty | `argv` global | `stdin` global | | wasi, local | `sys.argv` | `sys.stdin` | | quickjs | `scriptArgs` | `std.in` | The sandboxed runtimes provide files plus compute, not arbitrary networking or third-party packages. `runtime: local` selects the host interpreter when that broader authority is intentional. ## Authoring reference The public constructors document exact types and defaults: [`CLI` and `CLIHandler`](https://github.com/strukto-ai/mirage/blob/main/python/mirage/commands/cli/types.py), and [`CommandSpec` and `Argument`](https://github.com/strukto-ai/mirage/blob/main/python/mirage/commands/spec/types.py). ### `CLI` and `CLIHandler` | Field | Authoring meaning | | - | - | | `CLI.spec` | Root `CommandSpec` describing the program's grammar. | | `CLI.handlers` | Canonical leaf paths mapped to `CLIHandler` bindings. | | `CLI.config_model` | Pydantic model for per-install account validation. | | `CLI.accessor` | Builds the install's accessor from its validated config, once per install; closed when the install goes. Default `NOOPAccessor`. | | `CLI.script`, `CLI.runtime` | Embedded script and optional runtime; used instead of typed handlers. | | `CLIHandler.fn` | Leaf handler, called as `fn(accessor, paths, texts, ctx)`. | | `CLIHandler.write`, `CLIHandler.limit` | Mutation classification and optional execution-limit category. | ### `CommandSpec` | Field | Authoring meaning | | - | - | | `name`, `aliases` | Command word and alternate subcommand words. | | `subcommands` | Child nodes for a group. | | `arguments` | Options and positional arguments; group options are inherited by leaves. | | `description`, `epilog` | Help text and trailing help text. | | `usage_style` | Root help and refusal dialect: argparse, Git, clap or Cobra. Cobra keeps standard help and option errors; handlers own missing positional refusals. | | `allow_abbrev` | Whether unique long-option prefixes are accepted. | ### `Argument` | Field | Authoring meaning | | - | - | | Names | One positional name, or one or more dashed option spellings. | | `type` | `str` (default), `int`, `float`, or virtual `path`. | | `action` | `store` (default), `store_true`, `count`, `append`, or `extend`. | | `nargs` | One value by default; `?` for optional or an integer for fixed arity. Positionals also accept `*`, `+`, or `REMAINDER`. | | `choices` | Allowed values, validated by the parser. | | `required` | Require an option; positional arity comes from `nargs`. | | `default`, `env` | Option fallbacks; an environment value counts as supplied. | | `help`, `metavar` | Help description and displayed value name. | This follows argparse's naming conventions and supports a subset of its features. Positional defaults and variadic options are unsupported; `append` collects single option values, while `extend` flattens fixed groups. ### Handler arguments and `Context` | Argument or field | Handler view | | - | - | | `accessor` | The install's accessor. The default `NOOPAccessor` holds the validated config at `accessor.config` (`None` without a config model). | | `paths` | Cwd-resolved path operands. | | `texts` | Textual and numeric operands in declaration order. | | `ctx.argv` | Verbatim words after the installed head word, including subcommands. | | `ctx.flags` | Group and leaf flags keyed by normalized kwarg name. | | `ctx.spec` | The resolved leaf grammar. | | `ctx.stdin` | Piped bytes or an async byte source, or `None`. | | `ctx.cwd` | The session's working directory. | | `ctx.env` | Frozen environment snapshot for this invocation. | | `ctx.vfs`, `ctx.session` | The session's files and live session, for verbs that need them; `None` outside a workspace. | ## Verify a custom CLI Check help, successful execution, a refusal and isolation between two account installations. Exercise VFS access with path and mount policy, and verify snapshot restoration with credentials supplied again. Keep service request construction and internal edge cases in unit tests; put observable shell results in shared integration cases when both hosts implement the program. The shared grammar also serves shell commands. Prefer its existing argparse and POSIX concepts; keep a program-specific rule in its handler, or use a script when the whole program needs to own parsing. # discord Source: https://docs.mirage.strukto.ai/python/cli/discord Supported Discord commands for messages, threads, polls and guild information. Read and send Discord messages, edit or delete messages, add reactions, create threads and polls, and inspect guilds. The action names follow [OpenClaw](https://github.com/openclaw/openclaw); `members` and `server-info` are Mirage extensions. ## Setup Configure a bot token and its permissions with [Discord setup](/home/setup/discord). ```python theme={null} from mirage import Workspace from mirage.commands.cli.builtin.discord import DISCORD from mirage.core.discord.config import DiscordConfig config = DiscordConfig(token="bot-token") ws = Workspace({}) ws.register_cli("discord", DISCORD, config) ``` No service mount is required. For YAML and multiple accounts, see the [CLI overview](/python/cli/index#register-a-cli). ## Supported commands Run `discord <command> --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `discord send` | Send a message to a channel | | `discord read` | Read the most recent messages of a channel | | `discord edit` | Edit a message the bot authored | | `discord delete` | Delete a message | | `discord react` | Add an emoji reaction to a message | | `discord reactions` | List the reactions on a message | | `discord pin-message` | Pin a message to its channel | | `discord unpin-message` | Remove a pin from a message | | `discord list-pins` | List a channel's pinned messages | | `discord search` | Search a guild's messages by content | | `discord thread-create` | Create a thread, standalone or from a message | | `discord poll` | Post a poll message to a channel | | `discord members` | List a guild's members, optionally filtered | | `discord server-info` | Fetch a guild's metadata | ## Messages ```bash theme={null} discord read --channel 1256522563555819574 --limit 20 discord send --channel 1256522563555819574 --text "Release is ready" discord send --channel 1256522563555819574 --text "A reply" --reply-to 1489887688978075769 discord send --channel 1256522563555819574 --text "Spoken reply" --file /data/reply.wav discord edit --channel 1256522563555819574 --message 1489887688978075769 --text "Updated" discord delete --channel 1256522563555819574 --message 1489887688978075769 ``` `edit` works only on messages authored by the bot. Channel, guild and message arguments are Discord snowflake IDs; `send --file` reads a workspace path and attaches it. ## Threads, polls and search ```bash theme={null} discord react --channel 1256522563555819574 --message 1489887688978075769 --emoji "👍" discord reactions --channel 1256522563555819574 --message 1293847561029384756 discord pin-message --channel 1256522563555819574 --message 1293847561029384756 discord list-pins --channel 1256522563555819574 discord unpin-message --channel 1256522563555819574 --message 1293847561029384756 discord thread-create --channel 1256522563555819574 --message 1489887688978075769 --name "Release review" discord poll --channel 1256522563555819574 --question "Ship today?" --answer Yes --answer Tomorrow --duration 24 discord server-info --guild 1256522563555819574 discord members --guild 1256522563555819574 --query alice discord search --guild 1256522563555819574 --query deploy --channel 1256522563555819574 ``` Omit `--message` on `thread-create` to create a standalone thread. Repeat `--answer` for each poll option; `--multiselect` allows multiple choices. Responses are JSON. ## VFS and limits The optional [Discord VFS](/python/vfs/discord) exposes the guild's channels and messages as files. Use the IDs in its `name__id` path segments with the CLI. Registration remains independent of the mount, and command policy controls service writes. Only the listed actions are implemented. OpenClaw's source uses the [MIT license](https://github.com/openclaw/openclaw/blob/main/LICENSE). Mirage's command implementation is Apache-2.0; see [compatibility and licenses](/home/setup/clis#compatibility-and-licenses). # gh Source: https://docs.mirage.strukto.ai/python/cli/gh Supported GitHub commands for repositories, issues, pull requests, Actions and API calls. Work with GitHub repositories, issues, pull requests, releases and Actions, or call REST and GraphQL directly. Mirage implements the supported subset below of the [GitHub CLI (`gh`)](https://github.com/cli/cli), with workspace files and configured account credentials. ## Setup Use [GitHub setup](/home/setup/github) for token permissions. No GitHub mount or local checkout is required. ```python theme={null} from mirage import Workspace from mirage.commands.cli.builtin.gh import GH from mirage.core.github.config import GhConfig ws = Workspace({}) ws.register_cli("gh", GH, GhConfig(token="ghp_...", repo="acme/tools")) ``` `repo` is the default repository and `branch` the current branch, as a checkout would give them to a host `gh`: `branch` fills the API's `{branch}` placeholder, names the pull request a `pr` command acts on when given none, and is the head `pr create` opens from. `base_url` (`baseUrl` in TypeScript) selects an API host. An Enterprise REST base ending in `/api/v3` uses `/api/graphql` for GraphQL; other bases use `/graphql` beneath that base. For YAML and multiple accounts, see [registration](/python/cli/index#register-a-cli). ## Supported commands Run `gh <command> --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `gh auth status` | Check the configured token | | `gh auth token` | Token display is unavailable in Mirage | | `gh help` | Help about any command | | `gh version` | Show the Mirage GitHub CLI implementation version. Aliases: `--version`. | | `gh api` | Make an authenticated GitHub API request | | `gh issue list` | List issues. Aliases: `ls`. | | `gh issue view` | View an issue | | `gh issue create` | Create an issue. Aliases: `new`. | | `gh issue edit` | Edit an issue | | `gh issue close` | Close an issue | | `gh issue reopen` | Reopen an issue | | `gh issue comment` | Add a comment to an issue | | `gh issue delete` | Delete issue | | `gh issue lock` | Lock issue conversation | | `gh issue pin` | Pin an issue to a repository | | `gh issue status` | Show status of relevant issues | | `gh issue transfer` | Transfer issue to another repository | | `gh issue unlock` | Unlock issue conversation | | `gh issue unpin` | Unpin an issue from a repository | | `gh pr list` | List pull requests. Aliases: `ls`. | | `gh pr view` | View a pull request | | `gh pr create` | Create a pull request. Aliases: `new`. | | `gh pr edit` | Edit a pull request | | `gh pr merge` | Merge a pull request | | `gh pr close` | Close a pull request | | `gh pr reopen` | Reopen a pull request | | `gh pr comment` | Add a comment to a pull request | | `gh pr diff` | View changes in a pull request | | `gh pr checks` | Show CI checks for a pull request | | `gh pr lock` | Lock pull request conversation | | `gh pr ready` | Mark a pull request as ready for review | | `gh pr revert` | Revert a pull request | | `gh pr review` | Add a review to a pull request | | `gh pr status` | Show status of relevant pull requests | | `gh pr unlock` | Unlock pull request conversation | | `gh pr update-branch` | Update a pull request branch with latest changes of the base branch | | `gh repo list` | List repositories. Aliases: `ls`. | | `gh repo clone` | Clone a repository locally | | `gh repo view` | View a repository | | `gh repo create` | Create a repository | | `gh repo fork` | Create a fork of a repository | | `gh repo rename` | Rename a repository | | `gh repo edit` | Edit repository settings | | `gh repo delete` | Delete a repository | | `gh repo archive` | Archive a GitHub repository | | `gh repo sync` | Sync destination repository from source repository | | `gh repo unarchive` | Unarchive a GitHub repository | | `gh repo autolink create` | Create a new autolink reference for a repository. Aliases: `new`. | | `gh repo autolink delete` | Delete an autolink reference for a repository | | `gh repo autolink list` | Gets all autolink references that are configured for a repository. Aliases: `ls`. | | `gh repo autolink view` | View an autolink reference for a repository | | `gh repo deploy-key add` | Add a deploy key to a GitHub repository | | `gh repo deploy-key delete` | Delete a deploy key from a GitHub repository | | `gh repo deploy-key list` | List deploy keys in a GitHub repository. Aliases: `ls`. | | `gh repo gitignore list` | List available repository gitignore templates. Aliases: `ls`. | | `gh repo gitignore view` | View an available repository `.gitignore` template | | `gh repo license list` | List common repository licenses. Aliases: `ls`. | | `gh repo license view` | View a specific repository license by license key or SPDX ID | | `gh release list` | List releases. Aliases: `ls`. | | `gh release view` | View a release | | `gh release create` | Create a release | | `gh release delete` | Delete a release | | `gh release delete-asset` | Delete an asset from a release | | `gh release edit` | Edit a release | | `gh run list` | List workflow runs. Aliases: `ls`. | | `gh run view` | View a workflow run | | `gh run rerun` | Rerun a workflow run | | `gh run cancel` | Cancel a workflow run | | `gh run delete` | Delete a workflow run | | `gh workflow list` | List workflows. Aliases: `ls`. | | `gh workflow view` | View a workflow | | `gh workflow run` | Run a workflow | | `gh workflow disable` | Disable a workflow, preventing it from running or showing up when listing workflows | | `gh workflow enable` | Enable a workflow, allowing it to be run and show up when listing workflows | | `gh search issues` | Search for issues | | `gh search prs` | Search for prs | | `gh search repos` | Search for repos | | `gh search code` | Search for code | | `gh search commits` | Search for commits | | `gh cache delete` | Delete GitHub Actions caches | | `gh cache list` | List GitHub Actions caches. Aliases: `ls`. | | `gh gist create` | Create a new GitHub gist with given contents. Aliases: `new`. | | `gh gist delete` | Delete a GitHub gist | | `gh gist edit` | Edit one of your gists | | `gh gist list` | List gists from your user account. Aliases: `ls`. | | `gh gist rename` | Rename a file in the given gist ID / URL | | `gh gist view` | View the given gist or select from recent gists | | `gh gist clone` | Clone a GitHub gist locally | | `gh label clone` | Clones labels from a source repository to a destination repository on GitHub | | `gh label create` | Create a new label on GitHub, or update an existing one with `--force` | | `gh label delete` | Delete a label from a repository | | `gh label edit` | Update a label on GitHub | | `gh label list` | Display labels in a GitHub repository. Aliases: `ls`. | | `gh org list` | List organizations for the authenticated user. Aliases: `ls`. | | `gh ruleset check` | View information about GitHub rules that apply to a given branch | | `gh ruleset list` | List GitHub rulesets for a repository or organization. Aliases: `ls`. | | `gh ruleset view` | View information about a GitHub ruleset | | `gh secret delete` | Delete a secret on one of the following levels:. Aliases: `remove`. | | `gh secret list` | List secrets on one of the following levels:. Aliases: `ls`. | | `gh variable delete` | Delete a variable on one of the following levels:. Aliases: `remove`. | | `gh variable get` | Get a variable on one of the following levels: | | `gh variable list` | List variables on one of the following levels:. Aliases: `ls`. | | `gh variable set` | Set a value for a variable on one of the following levels: | ## Issues, pull requests and Actions ```bash theme={null} gh auth status gh issue list --state open --label bug --limit 20 gh issue view 42 --json number,title,labels,url --jq '.url' gh pr view 17 --json files,commits,reviews --jq '.files[].path' gh pr checks 17 --json name,bucket,state gh run list --workflow ci.yml --json databaseId,status,conclusion gh run view 123456 --log-failed gh workflow view ci.yml --yaml --ref release ``` Use `-R/--repo [HOST/]OWNER/REPO` where supported to override the configured repository. Typed `--jq` requires `--json`. List commands paginate up to `-L/--limit`. Typed `--json` fields follow upstream's for each command, except `jobs` on `run view`; use `gh api` for additional data. ```bash theme={null} gh issue create --title 'Broken build' --body-file /work/issue.md --label bug gh issue comment 42 --body-file - < /work/comment.md gh issue edit 42 --add-label confirmed --remove-assignee octocat gh pr create --title 'Fix build' --head fix-build --base main --body-file /work/pr.md gh pr merge 17 --squash --subject 'Fix build' gh release create v1.2.0 --title '1.2.0' --notes-file /work/notes.md gh workflow run ci.yml --ref main -f mode=full gh run rerun 123456 --failed ``` Commands are noninteractive: supply titles, bodies, branches and confirmation flags explicitly. Body/notes files and `--input` files use the workspace VFS; `-` selects stdin. Workflow YAML is read at the selected ref. Run logs are available only after completion; `--log-failed` selects failed steps. ## Repositories ```bash theme={null} gh repo view --json nameWithOwner,defaultBranchRef,url gh repo list acme --limit 50 gh repo clone acme/tools /work/tools -- --branch dev gh repo create acme/tools-next --private --add-readme gh repo fork acme/tools --fork-name tools-patched gh repo rename tools-v2 -R acme/tools gh repo edit acme/tools --enable-wiki=false --add-topic cli,agents gh repo edit acme/tools --visibility private --accept-visibility-change-consequences gh repo delete acme/tools-old --yes ``` `repo clone` uses Mirage's Git implementation and needs a writable destination mount. The token travels in the HTTP authorization header, not in the command line, output or `.git/config`, and only to the configured GitHub origin: `https://github.com` for GitHub's own API (`base_url` unset or `https://api.github.com`), else the scheme, host and port `base_url` names. Git clones any other URL on the line without it. Fork clones do not add an `upstream` remote. `repo rename` takes the **new name** as its operand; `-R` selects the repository to rename. `repo edit` changes only the named settings, and bare boolean settings can be disabled with `=false`. Deletion needs both a repository name and `--yes`. Repository URLs and `[HOST/]OWNER/REPO` are accepted, but the host must match the configured API host; use a separate install for another host. ## REST and GraphQL API ```bash theme={null} gh api /user gh api 'repos/{owner}/{repo}/issues' -f title='Bug' -f body='Steps to reproduce' gh api repos/acme/tools/issues -F 'labels[]=bug' -F 'metadata[agent]=worker' gh api repos/acme/tools/issues --input /work/issue.json --silent gh api 'repos/acme/tools/issues?per_page=50' --paginate --slurp gh api repos/acme/tools/pulls/17 -H 'Accept: application/vnd.github.v3.diff' gh api graphql -f query='{viewer{login}}' ``` | Option or input | Behavior | | - | - | | No fields | GET by default; no request body | | `-f` / `--raw-field` | String field; supplying fields selects POST unless `-X` overrides it | | `-F` / `--field` | Typed booleans, null and integers; `@FILE` reads a workspace file and `@-` reads stdin | | `-X` / `--method` | Explicit method; GET fields become query parameters, other methods use JSON | | `key[nested]`, `key[]` | Nested objects and arrays | | `--input FILE` | Request body from a file or `-`, sent as raw bytes; additional fields move to the query string | | `-H` / `--header` | Add or replace a header | | `--paginate` | Follow REST Link headers, joining array pages, or a GraphQL query's `endCursor` | | `--slurp` | Wrap pages in an array; cannot be combined with `--jq` | | `-i` / `--include` | Print status and headers for each response, including failures | | `--silent` | Suppress the response body; `--include` still prints headers | | `-q` / `--jq` | Filter API output in process; unlike typed commands, needs no `--json` | Quote endpoints containing `{owner}`, `{repo}` or `{branch}`. These expand from config in endpoints and `-F` values, but not `-f` values. Other brace pairs remain unchanged. A leading endpoint slash is optional. Unfiltered output preserves the server's response bytes. Typed `--json` output is compact JSON followed by a newline. `--jq` prints strings raw, null as an empty line, and objects/arrays as compact JSON. A jq error exits 1 and can leave earlier output on stdout. Connection failures and HTTP 500 responses are not retried. ## VFS and limits A [GitHub VFS](/python/vfs/github) can expose the same remote repository as files, independently of the CLI. The configured `repo` and `branch` supply context that a host `gh` would infer from a checkout. CLI service writes invalidate mounted caches; read API methods leave them intact. | Boundary | Mirage behavior | | - | - | | Authentication | `auth status` checks the token; `auth token` refuses to print it. No login/logout flow. | | Interactive tools | No editor, browser, extension manager, codespace or host-checkout workflow. | | Pull-request creation | Requires a title and a body or body file. `--head` defaults to `branch` and `--base` to the repository's default branch. | | Forks | `--clone` is refused; `--remote` without a repository is refused. | | Repository operations | No `repo set-default`. `repo sync` acts on a repository on GitHub, never a local checkout. | | Release assets and live runs | `release upload`, `release download`, `run watch` and `run download` are absent. | | Raw API | REST pagination only; no verbose, cache, hostname, preview or template flags. | | Help topics | `environment` and `exit-codes` are supported, alongside command help. | | HTTP display | `--include` prints HTTP/1.1 rather than upstream's HTTP/2.0 display. | | jq compatibility | Uses jq rather than gojq: builtin error wording and floating-point edge cases can differ. Numbers above 2^53 can lose precision; NaN, infinities and negative zero follow jq's values. | The original GitHub CLI uses the [MIT license](https://github.com/cli/cli/blob/trunk/LICENSE). Mirage's command implementation is Apache-2.0; the listed subset and differences define its compatibility scope. See [compatibility and licenses](/home/setup/clis#compatibility-and-licenses). # git Source: https://docs.mirage.strukto.ai/python/cli/git Supported Git commands for repositories and working trees on Mirage mounts. Inspect and modify repositories using a subset of the [Git command line](https://git-scm.com/docs/git). Mirage routes repository files through the workspace dispatcher, so the same commands can operate on RAM, disk or another backend with the required filesystem operations. The Python implementation uses [Dulwich](https://github.com/jelmer/dulwich); the TypeScript implementation uses [isomorphic-git](https://github.com/isomorphic-git/isomorphic-git). Mirage supplies the command grammar, output and VFS integration on both hosts. The compatibility target is native Git's supported behavior, with the [differences below](#limits-and-intentional-differences). These libraries are implementation dependencies; their own command interfaces do not define Mirage's supported commands. ## Setup `git` has no account config. It needs an existing repository to inspect, or a writable mount on which to initialize or clone one. ```python theme={null} from mirage import MountMode, Workspace from mirage.commands.cli.builtin.git import GIT from mirage.vfs.ram import RAMVFS ws = Workspace({"/repo": RAMVFS()}, mode=MountMode.WRITE) ws.register_cli("git", GIT) await ws.shell("git -C /repo init -b main") ``` For YAML registration, see the [CLI overview](/python/cli/index#register-a-cli). ## Supported commands Run `git <command> --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `git reflog` | Show reference history | | `git for-each-ref` | List references with a format | | `git cat-file` | Provide contents or details of repository objects | | `git hash-object` | Compute object ID and optionally create an object from a file | | `git grep` | Search tracked files in the working tree, index or named trees | | `git ls-tree` | List the contents of a tree object | | `git ls-files` | Show files in the index | | `git fetch` | Download objects and refs from another repository | | `git clone` | Clone a repository into a new directory | | `git help` | Show command help | | `git init` | Create an empty Git repository or reinitialize an existing one | | `git fsck` | Verify object hashes and connectivity | | `git stash list` | List stashed changes | | `git stash show` | Show stashed changes | | `git version` | Show the Mirage Git implementation version. Aliases: `--version`, `-v`. | | `git remote` | List remotes and inspect their URLs | | `git config` | Read repository configuration | | `git merge-base` | Find best common ancestors of commits | | `git show-ref` | List references | | `git symbolic-ref` | Read, change or delete a symbolic ref | | `git shortlog` | Summarize commit history | | `git rev-parse` | Resolve revisions | | `git rev-list` | List reachable commits | | `git diff-tree` | Compare a commit with its parent, or two trees | | `git diff-files` | Compare the index with the working tree | | `git diff-index` | Compare a tree with the working tree or index | | `git check-ref-format` | Check that a ref name is well formed | | `git ls-remote` | List the refs another repository publishes | | `git check-ignore` | Show which paths the ignore rules cover | | `git describe` | Name a commit after the nearest tag | | `git status` | Show the working tree status | | `git log` | Show commit logs | | `git show` | Show a commit and its diff | | `git diff` | Show changes between commits | | `git branch` | List, create or delete branches | | `git add` | Stage working tree content | | `git reset` | Unstage, putting the index back to HEAD | | `git commit` | Record the index as a new commit | | `git checkout` | Switch branches | | `git switch` | Switch branches | | `git restore` | Restore working tree files | | `git rm` | Remove files from the working tree and the index | | `git mv` | Move or rename a file, a directory, or a symlink | | `git tag` | Create, list or delete a tag | ## Create and inspect a repository ```bash theme={null} git -C /repo init -b main echo hello > /repo/hello.txt git -C /repo add hello.txt git -C /repo commit -m 'Initial commit' git -C /repo status --short git -C /repo log --oneline -5 git -C /repo show HEAD git -C /repo diff git -C /repo diff --cached git -C /repo grep -n hello git -C /repo ls-files --stage git -C /repo fsck ``` `-C` selects a workspace directory and defaults to the session's working directory. Repository discovery walks upward, so commands also work from subdirectories. Loose objects, packs, refs, the index and working files all use the same VFS operations as the shell. `init` supports `-b`, `--bare` and reinitialization. The default branch is `master` unless `-b` chooses another. `commit` requires `-m` and records `mirage <mirage@localhost>` unless `--author 'Name <email>'` overrides it. `fsck` checks the object database without modifying it. ## Stage and change files Continue from the initial commit above. Record a second version before using `HEAD~1` to restore the original: ```bash theme={null} echo updated > /repo/hello.txt git -C /repo commit -am 'Update greeting' git -C /repo add -A git -C /repo reset -- hello.txt git -C /repo restore -- hello.txt git -C /repo restore --staged -- hello.txt git -C /repo restore --source HEAD~1 -- hello.txt git -C /repo commit -am 'Restore original greeting' git -C /repo mv hello.txt greeting.txt git -C /repo commit -m 'Rename greeting' git -C /repo rm greeting.txt git -C /repo commit -am 'Remove greeting' ``` | Command | Behavior | | - | - | | `add` | `-A` stages all changes, `-u` tracked changes, `-f` allows ignored paths | | `reset` | Mixed reset from HEAD, optionally limited by paths; no revision operand or hard reset | | `restore` | Worktree by default, `--staged` for the index, `-SW` for both; `--source` accepts a tree-ish | | `rm` | Refuses uncommitted changes unless `-f`; `--cached` keeps working files; `-r` allows directories | | `mv` | Files or directories; supports force, dry-run, verbose and skip-failure modes; cannot cross mounts | | `commit` | Commits the whole index; `-a` restages tracked files, `--allow-empty` permits an empty change | `restore` can discard changes in the selected destination. Use `--` before a path beginning with `-`. Permission and read-only refusals go through the workspace dispatcher and are reported in Git's command-specific wording. ## Branches, tags and history ```bash theme={null} git -C /repo branch topic git -C /repo switch topic git -C /repo switch -c experiment git -C /repo checkout --detach HEAD~1 git -C /repo branch --contains HEAD git -C /repo tag v1.0 git -C /repo tag -a v1.1 -m 'Release' git -C /repo for-each-ref --format='%(refname:short)' refs/heads git -C /repo reflog git -C /repo stash list ``` Annotated tags need `-m`; lightweight tags can point to any object. Revision expressions include parent/ancestor operators (`^`, `~`), typed peels such as `HEAD^{tree}`, and paths such as `HEAD:hello.txt`. Operators apply left to right. Invalid suffixes are refused as part of the whole revision. `log`, `show`, `rev-list`, `diff-tree`, `shortlog`, `cat-file`, `hash-object` and `ls-tree` provide inspection without a host Git process. Run each command's `--help` for supported formatting, filtering, path and diff options. ## Clone, fetch and repository configuration ```bash theme={null} git clone /repo /work/copy git clone https://github.com/acme/tools.git /work/tools git -C /work/tools fetch origin git -C /work/tools remote -v git -C /work/tools config --get remote.origin.url git --git-dir=/repo/.git --work-tree=/repo status --short ``` Clone and fetch can read another workspace repository or a smart-HTTP remote. Destinations must be writable mounts. There is no push or pull command. A path git refuses to check out is refused by `checkout`, `switch`, `restore` and `reset` as git refuses it; `git clone` then exits 128 and keeps the repository with an empty work tree. Reading the entries of a tree that holds an entry with an empty name exits 128 with git's `empty filename in tree entry`. For authenticated GitHub clones, `gh repo clone` supplies its configured token, and only to its configured GitHub origin. `--git-dir` and `--work-tree` override `GIT_DIR` and `GIT_WORK_TREE` and resolve against `-C`. Repository `core.worktree` and `core.bare` affect discovery; linked worktrees use their recorded layout. Working-tree commands refuse bare repositories. No repository operation opens a host path behind the VFS. ## Limits and intentional differences * Only the listed command subset is implemented. Merge, rebase, push, pull, `reset --hard` and `switch -` are absent; stash supports inspection only. * Commits accept no path operands and do not create merge commits. An unmerged index blocks commits and branch moves. `checkout` is stricter than Git about staged changes; `switch` can carry compatible staged changes but refuses file/directory collisions that would discard them. * Host templates, hooks, editors and Git's initial-branch advisory are absent. Per-worktree `config.worktree` is not read. With conflicting `core.bare` and `core.worktree`, Mirage keeps the repository bare without Git's warning. * Working-tree replacements preserve executable modes and symlink semantics. They do not follow a symlink out of a directory being replaced. Nested mounts block removals or replacements that would consume their contents; destinations are checked before writes begin. Renames preserve namespace metadata and cannot cross mount boundaries at either end. * Gitlinks create or retain directory placeholders. Mirage does not check out submodule content or compare a submodule's HEAD; files inside a submodule directory can still appear as untracked. Removing a nonempty gitlink directory warns and leaves it in place. * Diff hunk bodies and diffstat counts can differ from native Git because the line-diff algorithm differs from xdiff. Headers, ordering and supported formatting match Git. Pretty formats `email`, `mboxrd` and `reference` are refused. * History searches use ASCII case folding. `--since` and `--until` accept ISO-8601 or epoch seconds; relative date phrases are refused. * `tag -l`/`-d` conflict wording uses a fixed option order. Tag deletion uses a ref transaction: duplicate updates are refused atomically, while missing names are reported and skipped. These boundaries are exercised by the shared Git integration corpus on RAM and disk mounts. The VFS determines which filesystem operations are available; registering `git` does not make a read-only mount writable. ## Upstream and dependency licenses | Project | Role in Mirage | License | | - | - | - | | [Git](https://github.com/git/git) | Command behavior and repository-format reference; Mirage's CLI does not launch the native Git executable | [GPL-2.0, with the qualifications in Git's COPYING file](https://github.com/git/git/blob/master/COPYING) | | [Dulwich](https://github.com/jelmer/dulwich) | Python Git implementation dependency | [Apache-2.0 OR GPL-2.0-or-later](https://github.com/jelmer/dulwich/blob/main/COPYING) | | [isomorphic-git](https://github.com/isomorphic-git/isomorphic-git) | TypeScript Git implementation dependency | [MIT](https://github.com/isomorphic-git/isomorphic-git/blob/main/LICENSE.md) | | [Mirage](https://github.com/strukto-ai/mirage) | Command layer and VFS adapters | [Apache-2.0](https://github.com/strukto-ai/mirage/blob/main/LICENSE) | Dulwich offers an Apache-2.0 option; using it does not require choosing its GPL alternative. Matching Git behavior does not relicense Git, Dulwich or isomorphic-git. Copied or ported source and redistributed dependencies still carry their applicable terms and notices; see [compatibility and licenses](/home/setup/clis#compatibility-and-licenses). # GWS Source: https://docs.mirage.strukto.ai/python/cli/gws Supported Google Workspace API methods and helpers for seven services. Use Google Drive, Sheets, Docs, Slides, Calendar, Forms and Gmail through one command tree. Mirage implements a subset of the [Google Workspace CLI (`gws`)](https://github.com/googleworkspace/cli), with selected API methods and helpers for mail, spreadsheet ranges and document text. ## Setup Use [Google Workspace setup](/home/setup/google) to obtain OAuth credentials and the scopes needed by each service. ```python theme={null} from mirage import Workspace from mirage.commands.cli.builtin.gws import GWS from mirage.core.google.config import GoogleConfig config = GoogleConfig(client_id="...", client_secret="...", refresh_token="...") ws = Workspace({}) ws.register_cli("gws", GWS, config) ``` No service mount is required. For YAML and multiple accounts, see the [CLI overview](/python/cli/index#register-a-cli). ## Supported commands Run `gws <command> --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `gws drive files list` | GET /files (Google drive API passthrough) | | `gws drive files get` | GET /files/\{fileId} (Google drive API passthrough) | | `gws drive files create` | POST /files (Google drive API passthrough) | | `gws drive files update` | PATCH /files/\{fileId} (Google drive API passthrough) | | `gws drive files copy` | POST /files/\{fileId}/copy (Google drive API passthrough) | | `gws drive files delete` | DELETE /files/\{fileId} (Google drive API passthrough) | | `gws drive files export` | GET /files/\{fileId}/export (Google drive API passthrough) | | `gws drive permissions create` | POST /files/\{fileId}/permissions (Google drive API passthrough) | | `gws drive permissions list` | GET /files/\{fileId}/permissions (Google drive API passthrough) | | `gws drive permissions delete` | DELETE /files/\{fileId}/permissions/\{permissionId} (Google drive API passthrough) | | `gws sheets spreadsheets get` | GET /spreadsheets/\{spreadsheetId} (Google sheets API passthrough) | | `gws sheets spreadsheets create` | POST /spreadsheets (Google sheets API passthrough) | | `gws sheets spreadsheets batchUpdate` | POST /spreadsheets/\{spreadsheetId}:batchUpdate (Google sheets API passthrough) | | `gws sheets read` | Read a cell range. Aliases: `+read`. | | `gws sheets write` | Overwrite a range with 2D values | | `gws sheets append` | Append rows after a range. Aliases: `+append`. | | `gws docs documents get` | GET /documents/\{documentId} (Google docs API passthrough) | | `gws docs documents create` | POST /documents (Google docs API passthrough) | | `gws docs documents batchUpdate` | POST /documents/\{documentId}:batchUpdate (Google docs API passthrough) | | `gws docs write` | Append text to a document. Aliases: `+write`. | | `gws slides presentations get` | GET /presentations/\{presentationId} (Google slides API passthrough) | | `gws slides presentations create` | POST /presentations (Google slides API passthrough) | | `gws slides presentations batchUpdate` | POST /presentations/\{presentationId}:batchUpdate (Google slides API passthrough) | | `gws calendar calendarList list` | GET /users/me/calendarList (Google calendar API passthrough) | | `gws calendar calendars get` | GET /calendars/\{calendarId} (Google calendar API passthrough) | | `gws calendar events list` | GET /calendars/\{calendarId}/events (Google calendar API passthrough) | | `gws calendar events get` | GET /calendars/\{calendarId}/events/\{eventId} (Google calendar API passthrough) | | `gws calendar events insert` | POST /calendars/\{calendarId}/events (Google calendar API passthrough) | | `gws calendar events patch` | PATCH /calendars/\{calendarId}/events/\{eventId} (Google calendar API passthrough) | | `gws calendar events delete` | DELETE /calendars/\{calendarId}/events/\{eventId} (Google calendar API passthrough) | | `gws calendar freebusy query` | POST /freeBusy (Google calendar API passthrough) | | `gws forms forms create` | POST /forms (Google forms API passthrough) | | `gws forms forms get` | GET /forms/\{formId} (Google forms API passthrough) | | `gws forms forms batchUpdate` | POST /forms/\{formId}:batchUpdate (Google forms API passthrough) | | `gws forms forms responses list` | GET /forms/\{formId}/responses (Google forms API passthrough) | | `gws forms forms responses get` | GET /forms/\{formId}/responses/\{responseId} (Google forms API passthrough) | | `gws gmail users drafts create` | POST /users/\{userId}/drafts (Google gmail API passthrough) | | `gws gmail users drafts delete` | DELETE /users/\{userId}/drafts/\{id} (Google gmail API passthrough) | | `gws gmail users drafts get` | GET /users/\{userId}/drafts/\{id} (Google gmail API passthrough) | | `gws gmail users drafts list` | GET /users/\{userId}/drafts (Google gmail API passthrough) | | `gws gmail users drafts send` | POST /users/\{userId}/drafts/send (Google gmail API passthrough) | | `gws gmail users drafts update` | PUT /users/\{userId}/drafts/\{id} (Google gmail API passthrough) | | `gws gmail users labels list` | GET /users/\{userId}/labels (Google gmail API passthrough) | | `gws gmail users messages list` | GET /users/\{userId}/messages (Google gmail API passthrough) | | `gws gmail users messages get` | GET /users/\{userId}/messages/\{id} (Google gmail API passthrough) | | `gws gmail users messages send` | POST /users/\{userId}/messages/send (Google gmail API passthrough) | | `gws gmail users messages trash` | POST /users/\{userId}/messages/\{id}/trash (Google gmail API passthrough) | | `gws gmail users messages attachments get` | GET /users/\{userId}/messages/\{messageId}/attachments/\{id} (Google gmail API passthrough) | | `gws gmail send` | Send a new email via Gmail. Aliases: `+send`. | | `gws gmail read` | Fetch one Gmail message as processed JSON (same shape as cat \<path>.gmail.json). Aliases: `+read`. | | `gws gmail reply` | Reply to the sender of a Gmail message (excludes CC). Aliases: `+reply`. | | `gws gmail reply-all` | Reply to a Gmail message including all recipients (To+CC). Aliases: `+reply-all`. | | `gws gmail forward` | Forward a Gmail message to a new recipient. Aliases: `+forward`. | | `gws gmail triage` | List message summaries (id, from, subject, date, snippet) for a Gmail search query. Aliases: `+triage`. | ## Call an API method ```bash theme={null} gws drive files list --params '{"pageSize":10}' gws gmail users messages get --params '{"userId":"me","id":"MESSAGE_ID"}' gws drive permissions create --params '{"fileId":"FILE_ID"}' --json '{"role":"reader","type":"anyone"}' gws sheets spreadsheets create --json '{"properties":{"title":"Q3 planning"}}' ``` The form is `gws SERVICE RESOURCE METHOD`. `--params` supplies URL path and query parameters; `--json` supplies the body. Methods return the API response as compact JSON. Lists follow `nextPageToken` by default and print multiple pages as NDJSON. Use `--page-limit N` to stop early. Export methods can return raw bytes instead of JSON. The supported methods are the registered subset above, not every method in Google's Discovery documents. ## Use helpers ```bash theme={null} gws gmail triage --query 'is:unread' --max 10 gws gmail +triage --query 'is:unread' --max 10 gws gmail read --id MESSAGE_ID gws gmail send --to user@example.com --subject Hello --body 'Hi there' gws gmail reply --message-id MESSAGE_ID --body 'Thanks' gws sheets read --spreadsheet SHEET_ID --range 'Sheet1!A1:C10' gws sheets append --spreadsheet SHEET_ID --values 'alice,42' gws docs write --document DOC_ID --text 'New paragraph' gws docs write --document DOC_ID --tab TAB_ID --text 'Into this tab' ``` Helpers omit the upstream CLI's `+` prefix: use `gws docs write`, not `gws docs +write`. `--tab` is Mirage's addition for document tabs. ## Choose a document tab `gws docs documents get --params '{"documentId":"DOC_ID"}'` returns the legacy body of the first tab. Add `"includeTabsContent":true` to receive `tabs[].documentTab`, including nested `childTabs`, instead of that flat body. Mounted `.gdoc.json` files always use the tab-aware shape. `docs write` appends to the first tab unless `--tab` selects another one. A raw `batchUpdate` follows the API's defaults: `replaceAllText` without a tab restriction can affect every tab. ## VFS, folder placement and limits The CLI can share `GoogleConfig` with Google's VFS adapters. Each registration owns its config and requires no mount. Setting `folder_id` (`folderId` in TypeScript) changes **creation placement**, not which files the CLI may read: * Drive `files create` and `copy` default `parents` to that folder. * An explicit `parents` array wins, including an empty array. * Docs, Sheets and Slides creation is followed by a Drive move into the folder. These are separate requests, so a failed move can leave the new file created. * Injected placement requests include Shared Drive support. Reads still reach the whole account allowed by the credential. Use command policy to restrict operations; a mounted folder is not a CLI access boundary. Mirage registers a fixed command subset; upstream builds commands from Google Discovery at runtime. Folder placement and helper spelling also differ, and the host config supplies credentials instead of an interactive login. Mirage paginates list methods by default; upstream requires `--page-all`. Parser refusals use Mirage's declared command style, so upstream exit codes and diagnostics are not a blanket compatibility promise. The original `gws` is [Apache-2.0 licensed](https://github.com/googleworkspace/cli/blob/main/LICENSE). Mirage's command implementation is also Apache-2.0; see [compatibility and licenses](/home/setup/clis#compatibility-and-licenses). # hf Source: https://docs.mirage.strukto.ai/python/cli/hf Supported Hugging Face Hub commands for downloads, commits, repositories and tags. Download Hugging Face Hub files into the workspace and upload files or directories as a single commit. Mirage also supports repository creation, tags and file deletion using the [official `hf` vocabulary](https://github.com/huggingface/huggingface_hub). ## Setup Create a token using [Hugging Face setup](/home/setup/hf_models). TypeScript imports `HF` from the Node package. The Hub API needs no Python extra; `hf-buckets` is a separate storage backend. ```python theme={null} from mirage import MountMode, RAMVFS, Workspace from mirage.commands.cli.builtin.hf import HF from mirage.core.hf_hub.config import HfConfig config = HfConfig(token="hf_...") ws = Workspace({"/work": RAMVFS()}, mode=MountMode.WRITE) ws.register_cli("hf", HF, config) ``` No service mount is required. For YAML and multiple accounts, see the [CLI overview](/python/cli/index#register-a-cli). ## Supported commands Run `hf <command> --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `hf auth whoami` | Find out which huggingface.co account you are logged in as | | `hf auth list` | List all stored access tokens | | `hf repo create` | Create a new repo on huggingface.co | | `hf repo tag create` | Create a tag for a repo | | `hf repo tag list` | List tags for a repo | | `hf repo tag delete` | Delete a tag from a repo | | `hf repo-files delete` | Delete files from a repo on the Hub | | `hf download` | Download files from the Hub | | `hf upload` | Upload a file or a folder to the Hub. Recommended for single-commit uploads | | `hf env` | Print information about the environment | | `hf version` | Print information about the hf version | ## Download, edit and upload ```bash theme={null} hf auth whoami hf download acme/model config.json --local-dir /work sed -i 's/1024/2048/' /work/config.json hf upload acme/model /work/config.json config.json --commit-message 'Widen the model' ``` `/work` must be a writable workspace mount. Each upload is one commit, including all files selected from a directory. `--repo-type` selects models, datasets or spaces; `--revision` selects a branch, tag or commit. Local paths resolve against the shell's working directory. With no source, `hf upload acme/model` reads `./model`. Downloads, uploads and cache files use workspace operations rather than the host filesystem. ## Repositories and tags ```bash theme={null} hf repo create acme/new-model --private hf repo tag create acme/model v1.0 hf repo tag list acme/model hf repo tag delete acme/model v1.0 hf repo-files delete acme/model '*.tmp' ``` For spaces, use `--repo-type space` and `--space_sdk`. `--exist-ok` accepts an existing repository. Deleting matching files creates one commit. ## Select files and cache downloads `--include`, `--exclude`, `--delete` and `repo-files delete` use Hub glob semantics: `*` crosses `/`, `[!a]` negates a character class, and a trailing `/` names a folder. Directory uploads exclude `.git` and `.cache/huggingface`. Single-file uploads ignore the include/exclude/delete filters with warnings. Deletion globs match the remote listing; `--delete` is relative to the upload destination and spares files re-added by the same commit. `.gitattributes` is never deleted. An empty change is skipped with a warning. Without `--local-dir`, downloads use the cache layout under `--cache-dir`: ```text theme={null} models--acme--model/ blobs/<etag> refs/main snapshots/<sha>/config.json -> ../../blobs/<etag> ``` A branch or tag download writes its ref; a commit-pinned download does not. `--force-download` refetches a blob. Relative cache paths, including `HF_HUB_CACHE` and `HF_HOME`, resolve against the session's working directory. ## VFS and limits The [model](/python/vfs/hf_models), [dataset](/python/vfs/hf_datasets) and [space](/python/vfs/hf_spaces) VFS adapters expose remote repository files without creating a local checkout. They are read-only. Use a writable mount for editing and `hf upload` to choose the commit boundary. There is no interactive `auth login` or `auth logout`; the registered config supplies the token. Only the listed commands are implemented. Upstream `huggingface_hub` uses [Apache-2.0](https://github.com/huggingface/huggingface_hub/blob/main/LICENSE), as does Mirage's command implementation. See [compatibility and licenses](/home/setup/clis#compatibility-and-licenses). # Himalaya Source: https://docs.mirage.strukto.ai/python/cli/himalaya Supported IMAP and SMTP commands for reading, composing and sending mail. List and search IMAP mail, read messages, and compose, reply, forward or send through SMTP. Mirage uses the [Himalaya](https://github.com/pimalaya/himalaya) command vocabulary with JSON output and workspace file attachments. ## Setup Configure the account using [Email setup](/home/setup/email). Python needs the `email` extra; TypeScript imports `HIMALAYA` from the Node package. ```python theme={null} from mirage import Workspace from mirage.commands.cli.builtin.himalaya import HIMALAYA from mirage.core.email.config import EmailConfig config = EmailConfig( imap_host="imap.example.com", smtp_host="smtp.example.com", username="agent@example.com", password="app-password", ) ws = Workspace({}) ws.register_cli("himalaya", HIMALAYA, config) ``` No service mount is required. For YAML and multiple accounts, see the [CLI overview](/python/cli/index#register-a-cli). ## Supported commands Run `himalaya <command> --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `himalaya mailbox list` | List the mailboxes of the account. Aliases: `ls`. | | `himalaya flag add` | Add flags to messages | | `himalaya flag set` | Replace the flags of messages | | `himalaya flag remove` | Remove flags from messages. Aliases: `rm`. | | `himalaya attachment list` | List the attachments of one message. Aliases: `ls`. | | `himalaya attachment download` | Save a message's attachments to the workspace. Aliases: `dl`. | | `himalaya envelope list` | List the envelopes of a mailbox, most recent first. Aliases: `ls`. | | `himalaya envelope search` | Search envelopes with the query DSL. Aliases: `sr`. | | `himalaya message copy` | Copy messages to another mailbox. Aliases: `cp`. | | `himalaya message move` | Move messages to another mailbox. Aliases: `mv`. | | `himalaya message delete` | Move messages to the trash, or remove them once they are there. Aliases: `rm`. | | `himalaya message read` | Read a message | | `himalaya message compose` | Compose a new message from flags. Aliases: `write`, `new`. | | `himalaya message send` | Send a message through the account | | `himalaya message add` | Add a raw RFC 5322 message to a mailbox. Aliases: `save`. | | `himalaya message reply` | Reply to a message | | `himalaya message forward` | Forward a message. Aliases: `fwd`. | ## Triage and read ```bash theme={null} himalaya envelope list -m INBOX --page 1 --page-size 10 himalaya envelope search -m INBOX not flag seen and from alice@example.com himalaya envelope search after 2026-01-01 order by subject asc himalaya envelope search subject '"quarterly review"' himalaya --json envelope list -m INBOX | jq -r '.envelopes[].subject' himalaya message read -m INBOX 12345 himalaya message read -m INBOX 12345 --raw himalaya mailbox list --counts himalaya flag add 12345 -f seen -f flagged himalaya message move 12345 --to Archive himalaya message copy 12345 --from Archive --to Projects himalaya message delete 12345 himalaya attachment list 12345 himalaya attachment download 12345 -d /data/attachments ``` Output matches upstream Himalaya. Listings print tables and confirmations print a sentence; add the global `--json` for JSON, in any position. `message read` shows the headers and walks the MIME parts, `--raw` returns RFC 5322 bytes, and `--seen` marks the message as seen, which reading alone does not. Messages take positional IDs. `-m/--mailbox` defaults to `INBOX`. An attachment's ID is its position among the message's MIME parts. Listings are newest first, with pages starting at 1 and a default page size of 25. The account's `max_messages` (default 200) bounds the search and paging window. Sorted search considers that whole window. Search conditions are `date`, `after`, `from`, `to`, `subject`, `body` and `flag`. Combine them with `and`, `or`, `not` and parentheses; sort with `order by date|from|to|subject [asc|desc]`. Date conditions use the message's `Date:` header, and `after` is exclusive. A pattern containing spaces needs literal double quotes inside the shell quotes, as above. A malformed query exits 1 before contacting the server, and the report points at where it stopped. ## Compose, reply and send ```bash theme={null} himalaya message compose --to you@example.org --subject Report --body 'See attached' --attach /work/report.pdf himalaya message compose --to you@example.org --subject Hello --body Hi --send echo 'The body' | himalaya message compose --to you@example.org --subject Hello | himalaya message send himalaya message reply -m INBOX 12345 --body 'Thanks' --send himalaya message forward -m INBOX 12345 --to colleague@example.com --send ``` **Without `--send`, compose/reply/forward print MIME bytes and send nothing.** With `--json` they print the decoded fields instead. Bodies come from `--body`, `--body-file` or stdin. `message send` accepts raw MIME on stdin, or after `--` as text or a file path. `--attach` is repeatable and reads workspace files through the VFS; `--from`, `--to`, `--cc`, `--bcc`, `--subject`, `--signature` and `--signature-file` control the composed message. `message add -m MAILBOX` appends raw MIME to a mailbox and reports the new id. Reply uses `Reply-To` or `From`, adds reply headers and quotes the source. Forward prefixes the subject with `Fwd:` and keeps `References`. Both accept `--posting-style top|bottom|none` and `--quote-headline`. There is no reply-all switch; supply the extra recipients through `--cc`. ## Save drafts and sent copies ```bash theme={null} himalaya message compose --to you@example.org --body Draft --save Drafts himalaya message send --save Sent < /work/message.eml ``` Sending normally saves a seen copy by IMAP after SMTP succeeds. Mirage uses the server's `\Sent` folder, or the config's `sent_folder` (`sentFolder`) when set. `save_copy=False` (`saveCopy: false`) disables the default copy. `--save MAILBOX` overrides both settings for one command; without `--send` on a composer, it saves a draft and sends nothing. `--no-save` skips the configured copy. A copy that fails after delivery exits 1 and says the message was already sent, so do not retry it. Saving a draft without sending fails normally if IMAP refuses it. ## VFS and limits The optional [Email VFS](/python/vfs/email) exposes the mailbox as files. Reading a message does not mark it seen. The CLI uses its own account config; attachments can come from any readable workspace mount. Server matching rules determine how search patterns match addresses and text. `trash_folder` picks the mailbox `message delete` moves to, as upstream's `mailbox.alias.trash`; unset, the server's `\\Trash` tag decides. Only the mailbox, envelope, flag, message and attachment commands are present, and `-c`, `-a` and `-b` are not accepted since an install is one account. Upstream Himalaya offers a choice of [MIT](https://github.com/pimalaya/himalaya/blob/master/LICENSE-MIT) or [Apache-2.0](https://github.com/pimalaya/himalaya/blob/master/LICENSE-APACHE). Mirage's command implementation is Apache-2.0; see [compatibility and licenses](/home/setup/clis#compatibility-and-licenses). # Overview Source: https://docs.mirage.strukto.ai/python/cli/index Register and discover Mirage’s supported CLIs, and use them with workspace files. Mirage includes twelve command-line programs for working with services, Git repositories and search mounts inside a workspace. Each program's `--help` describes the commands and flags implemented by Mirage. The [host `mirage` CLI](/home/access/cli) connects to and manages workspaces. The programs on this page run in those workspaces through `ws.shell(...)`, `mirage shell`, or another [access method](/home/access/overview). ## Supported CLIs | Program | Supported operations | Commands | | - | - | - | | [airtable](/python/cli/airtable) | Query bases and tables; read, create, update and delete records; add comments | 10 | | [discord](/python/cli/discord) | Read and send messages; edit, react, create threads and polls; inspect guilds | 14 | | [gh](/python/cli/gh) | Manage repositories, issues, pull requests, releases and Actions; call GitHub APIs | 103 | | [git](/python/cli/git) | Inspect history, stage and commit files, manage branches and tags, clone and fetch | 44 | | [gws](/python/cli/gws) | Call Drive, Sheets, Docs, Slides, Calendar, Forms and Gmail APIs | 54 | | [hf](/python/cli/hf) | Download and upload Hub files; create repositories; manage tags and delete files | 11 | | [himalaya](/python/cli/himalaya) | List and search mail; read, compose, reply, forward and send messages | 17 | | [linear](/python/cli/linear) | Query teams, issues, projects and documents; update issues and comments | 30 | | [ntn](/python/cli/ntn) | Read and edit Markdown pages, query data sources and call Notion APIs | 12 | | [search](/python/cli/search) | Rank the records of Dify, Chroma, mem0, Qdrant and LanceDB mounts for a query | 1 | | [slack](/python/cli/slack) | Read and send messages; manage reactions and pins; find members and search | 14 | | [trello](/python/cli/trello) | Read boards, lists, labels and cards; create, update, move, assign, label and comment on cards | 16 | All twelve are available in Python and TypeScript on Node. The TypeScript Node package provides `hf` and `himalaya`; the other ten live in core. These are Mirage implementations of the listed command trees, not installed copies of the upstream binaries. Each reference links its upstream project or service API and documents its supported subset, limits and relevant licenses. See [compatibility and licenses](/home/setup/clis#compatibility-and-licenses) for the distinction between matching behavior and reusing code. ## Register a CLI Account CLIs need credentials but do not need a service mount: ```python theme={null} from mirage import Workspace from mirage.commands.cli.builtin.slack import SLACK from mirage.core.slack.config import SlackConfig ws = Workspace({}) ws.register_cli("slack", SLACK, SlackConfig(token="xoxb-...")) await ws.shell("slack --help") ``` `register_cli(name, spec, config)` validates a config mapping or accepts an instance of the declared model. `git` and `search` have no account config; register their `GIT` and `SEARCH` specs without the third argument. Two installations of the same spec under different names can use different accounts. Registration is a host operation, not an agent shell command. The equivalent YAML entry is: ```yaml theme={null} clis: slack: cli: slack config: token: ${SLACK_TOKEN} ``` YAML config fields use snake\_case in both languages. [Setup pages](/home/setup/clis) cover credentials and imports for every program. ## Discover functionality ```bash theme={null} man slack --help slack send-message --help man slack send-message type -t slack which slack ``` `man` and `--help` render the registered spec. Unknown commands and flags are refused; wording and exit codes follow the program's declared style. Use each reference for command-specific errors rather than assuming one exit code for all CLIs. Visible installed programs have read-only stubs under `/usr/bin`, so `which slack` returns `/usr/bin/slack`. The stub describes the command without exposing its config or credentials. Executing that path uses the same command and policy checks. Changing `PATH` does not change Mirage's virtual command lookup; host and remote runtimes use their own executable paths. ## Use CLIs with the VFS | Operation | Where it goes | | - | - | | `cat`, `find`, `grep`, `jq` on mounted files | The selected VFS through workspace operations | | Account commands such as `slack send-message` | The service configured for that CLI installation | | File arguments such as `gh --body-file`, `ntn --filter-file`, `himalaya --attach` and `hf upload` paths | Workspace files through `ctx.vfs` | | `git -C /repo ...` | The repository and working tree on workspace mounts | Credentials may be shared between a CLI and a VFS, but neither registers or locates the other. A CLI write uses service IDs, while file arguments resolve against the session's working directory and retain `PathSpec` semantics. After an account CLI write, Mirage expires the caches of every mount the CLI's client may reach, including answers a mount's client keeps itself (a vector store's search results), so later reads can observe the change. A client that names what it reaches narrows this: `gh` reaches only GitHub mounts on its API base. Mount modes and path policy govern workspace file operations. A read-only Slack mount does **not** disable `slack send-message`; use command policy to restrict service actions. The service's own credentials and permissions still apply to its API calls. ## Add a custom CLI Use [the authoring guide](/python/cli/custom) to define a typed command tree, register multiple accounts, work with VFS paths, or run a script CLI. It also covers config validation, snapshots and the shared command grammar. # linear Source: https://docs.mirage.strukto.ai/python/cli/linear Supported Linear commands for issues, comments, teams, projects and search. Query Linear teams, issues, projects, cycles, comments, users and documents. Mirage's noun/verb interface draws partly on [schpet/linear-cli](https://github.com/schpet/linear-cli), with its own supported command tree and normalized JSON output for `jq`. ## Setup Create an API key using [Linear setup](/home/setup/linear). ```python theme={null} from mirage import Workspace from mirage.commands.cli.builtin.linear import LINEAR from mirage.core.linear.config import LinearConfig config = LinearConfig(api_key="lin_api_...") ws = Workspace({}) ws.register_cli("linear", LINEAR, config) ``` No service mount is required. For YAML and multiple accounts, see the [CLI overview](/python/cli/index#register-a-cli). ## Supported commands Run `linear <command> --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `linear team list` | List teams as JSON | | `linear team get` | Get one team by key, name, or ID | | `linear team members` | List a team's members | | `linear issue list` | List a team's issues | | `linear issue get` | Get one issue by key or ID | | `linear issue create` | Create an issue | | `linear issue update` | Update an issue's title or description | | `linear issue assign` | Assign an issue to a user | | `linear issue transition` | Move an issue to a workflow state | | `linear issue set-priority` | Set an issue's priority | | `linear issue set-project` | Attach an issue to a project | | `linear issue relation add` | Create an issue relation | | `linear issue relation list` | List incoming and outgoing relations | | `linear issue relation delete` | Delete an issue relation | | `linear issue add-label` | Add a label to an issue | | `linear issue remove-label` | Remove a label from an issue | | `linear project list` | List a team's projects | | `linear project get` | Get one project by ID | | `linear cycle list` | List a team's cycles | | `linear cycle current` | Get a team's current cycle | | `linear cycle get` | Get one cycle by ID | | `linear label list` | List a team's labels | | `linear comment list` | List an issue's comments | | `linear comment add` | Comment on an issue | | `linear comment update` | Edit a comment | | `linear user list` | List workspace users | | `linear user get` | Get one user by email | | `linear document list` | List a team's documents | | `linear document get` | Get one document by ID | | `linear search` | Search issues by text | ## Find work ```bash theme={null} linear team list linear team members ENG linear issue list --team ENG linear issue get ENG-42 linear project list --team ENG linear cycle current --team ENG linear comment list ENG-42 linear user get sam@example.com linear document list --team ENG linear search "login bug" ``` Issues take a positional key such as `ENG-42` or a raw ID. `--team` accepts a team key, name or ID. Use the list commands to discover project, cycle, label and document IDs. ## Update work ```bash theme={null} linear issue create --team ENG --title "Fix login" --description "Reproduction steps" linear issue update ENG-42 --title "Fix expired-session login" linear issue assign ENG-42 --assignee-email user@example.com linear issue transition ENG-42 --state-name "In Review" linear issue set-priority ENG-42 --priority 2 linear issue set-project ENG-42 --project-name "Search" linear issue add-label ENG-42 --label-name bug linear issue remove-label ENG-42 --label-name bug echo 'Ready for review' | linear comment add ENG-42 linear comment update --comment COMMENT_ID --body "Reviewed" ``` | Value | Accepted forms | | - | - | | Assignee | `--assignee-email` or `--assignee-id` | | Workflow state | `--state-name` or `--state-id` | | Project | `--project-name` or `--project` with an ID | | Label | `--label-name` or `--label` with an ID; preserves existing labels | | Priority | `0` none, `1` urgent, `2` high, `3` normal, `4` low | Descriptions and comment bodies can come from stdin. Issue creation requires `--team` and `--title`; updates use the values explicitly supplied. ## Issue relations ```bash theme={null} linear issue relation add ENG-42 blocks ENG-43 linear issue relation add ENG-42 blocked-by ENG-43 linear issue relation add ENG-42 related ENG-43 linear issue relation add ENG-42 duplicate ENG-43 linear issue relation list ENG-42 linear issue relation delete ENG-42 duplicate ENG-43 --yes ``` The positional order is `ISSUE RELATION RELATED`, matching [linear-cli v3.1.0](https://github.com/schpet/linear-cli/tree/02571d34be662e5487204841fb80bf23ed79b4f0). Relation names are case insensitive. `blocked-by` stores the inverse of `blocks`. Deletion matches the exact stored direction, including `related`. Both issue references are validated before contacting the service. Relation commands accept full keys such as `eng-42`, Linear issue URLs, UUIDs and opaque IDs of the form `prefix_value`. UUID and opaque ID operands extend the upstream interface. An explicit issue is required for listing; branch inference and bare issue numbers are unavailable in this virtual CLI. Adding `ENG-42 duplicate ENG-43` marks ENG-42 as the duplicate and ENG-43 as its original. Linear applies the reserved Duplicate status through the relation mutation. Mirage does not submit a separate state update. Removing that relation lets Linear restore the previous status. See [Linear issue properties](https://linear.app/docs/issue-property) and the [June 18, 2026 changelog](https://linear.app/changelog/2026-06-18-agent-assisted-project-updates). Add and delete return one normalized JSON relation. List returns an array, outgoing relations first, followed by incoming relations, with all pages read. Each row contains `relation_id`, `type`, `direction`, `issue_id`, `issue_key`, `related_issue_id`, `related_issue_key` and `related_issue_title`. `issue_id` always identifies the queried or first operand issue. Incoming `blocks` rows have type `blocked-by`. Incoming `duplicate` rows keep type `duplicate` and `direction: "incoming"`; the other issue is the duplicate in that case. This JSON contract deliberately differs from upstream's text output. Deletion requires `--yes`, also spelled `-y`, `-f`, `--force` or `--confirm`. The virtual CLI cannot prompt. The relation is looked up before confirmation, so a missing relation still reports that failure first. Service errors and false mutation success flags fail the command. Mutations are not retried automatically, including when a response cannot confirm the outcome. Failure output follows the virtual CLI's conventions. Missing required operands and unknown options exit 2. Extra operands, relation validation, missing issues or relations, missing confirmation and service failures exit 1. Upstream instead classifies invalid relation names and missing confirmation as usage errors with exit 2, and missing entities with exit 3. Its authentication and availability failures use exits 4 and 5. Error wording also follows the virtual CLI rather than upstream text. ## VFS and limits The [Linear VFS](/python/vfs/linear) lets agents browse the same service as files. The CLI takes service IDs and its own config; piping a mounted file into a body does not make that mount the CLI's account. Only the commands above are implemented. Commands, flags and JSON output follow this reference; Mirage does not promise full compatibility with `schpet/linear-cli`. That project uses the [ISC license](https://github.com/schpet/linear-cli/blob/main/LICENSE). Mirage's command implementation is Apache-2.0, with ISC-licensed relation adaptations recorded in `licenses/third_party/schpet-linear-cli.txt`; see [compatibility and licenses](/home/setup/clis#compatibility-and-licenses). # From MCP Source: https://docs.mirage.strukto.ai/python/cli/mcp Install a streamable-HTTP MCP server's tools as one CLI. An MCP server's tools become one CLI: each tool is a subcommand that takes the tool's arguments as one JSON object. Profiles, network rules and snapshots apply to it as to any CLI. ## Register a server `mcp_cli` reads the server's tool list and returns a `CLI`; install it with `register_cli`, passing the same config: ```python theme={null} import os from mirage import Workspace, mcp_cli config = { "url": "https://mcp.example.com/mcp", "auth": {"type": "bearer", "token": os.environ["ISSUES_TOKEN"]}, } ws = Workspace({}) ws.register_cli("issues", await mcp_cli(config), config) ``` ```bash theme={null} issues --help issues search-issues --help issues search-issues '{"query": "login bug"}' ``` A tool named `search_issues` becomes the subcommand `search-issues`; its `--help` prints the tool's description and the JSON schema of its arguments. `mcp_cli` raises `MCPToolsError` when the server cannot be listed within 5 minutes in all, it lists more than 1024 tools or more than 16 MiB of them, or its tools cannot all become distinct subcommands. The tool list is read once, at registration. To pick up tools the server added later, list them again, then remove the CLI and register the new one: ```python theme={null} cli = await mcp_cli(config) await ws.unregister_cli("issues") ws.register_cli("issues", cli, config) ``` ## Authentication `auth` sets the one header every request carries. Leave it out for a server that needs none. | `auth` | Header sent | | - | - | | `{"type": "bearer", "token": T}` | `Authorization: Bearer T` | | `{"type": "header", "name": N, "token": T}` | `N: T` | The token is redacted in snapshots. The URL is saved as written, so keep credentials in `auth`, not in the URL. A token must be printable ASCII with no leading or trailing space; any other is refused at registration. ## Register from YAML An MCP server is a `clis:` entry with `cli: mcp`. The token can come from `${VAR}` or a [credential pointer](/home/authentication): ```yaml workspace.yaml theme={null} mounts: /: vfs: ram clis: issues: cli: mcp config: url: https://mcp.example.com/mcp auth: type: bearer token: from: env key: ISSUES_TOKEN ``` `mirage workspace create workspace.yaml` builds it on the server. A program that loads the file itself passes the listed servers to `to_workspace_kwargs`, which raises `ValueError` without them: ```python theme={null} from mirage import Workspace from mirage.config import build_mcp_clis, load_config, resolve_secrets config = await resolve_secrets(load_config("workspace.yaml")) ws = Workspace( **config.to_workspace_kwargs(mcp_clis=await build_mcp_clis(config)) ) ``` ## Call a tool | Call | Result | | - | - | | `issues search-issues '{"query": "x"}'` | the tool's answer on stdout, exit 0 | | `issues list-labels` | the tool called with `{}` | | the tool reports an error | its text on stderr, exit 1 | | the server cannot be reached | `search-issues: MCP server failed: <reason>`, exit 1 | | the server gives no answer within 5 minutes | `search-issues: MCP server timed out`, exit 1 | | the answer is larger than 16 MiB | `search-issues: MCP server reply exceeds 16777216 bytes`, exit 1 | | the operand is not one JSON object | `search-issues: invalid JSON`, `JSON must be an object` or `takes one JSON object`, exit 2, nothing sent | Text content prints as text; any other content prints as one line of JSON. A failed call is not retried. Cancelling the line cancels the call. A `pre_network` policy or a `network:` setting that excludes the server's host refuses the call before anything is sent; a config's `network:` also refuses listing its servers when it loads. ## Profiles A profile names a tool the way it names any CLI subcommand: ```yaml theme={null} profiles: triage: commands: deny: - commands: ["issues delete-issue"] reason: triage never deletes ``` A tool the server marks `readOnlyHint` runs as a read; every other tool counts as a write. ## On a server The [server](/python/access/server) takes `cli: mcp` entries in a workspace's create body. `${VAR}` is expanded only in files; over HTTP, send the token or a pointer. [`mirage cli`](/home/access/cli#saved-connections) saves a server's URL and token under a name, as a CLI of type `mcp`: ```bash theme={null} mirage cli create issues --type mcp --set url=https://mcp.example.com/mcp --set auth.type=bearer --secret auth.token ``` A create body or a template points at the saved fields: ```yaml theme={null} clis: issues: cli: mcp config: url: {from: strukto, ref: issues, key: url} auth: type: {from: strukto, ref: issues, key: auth.type} token: {from: strukto, ref: issues, key: auth.token} ``` ## Snapshots A snapshot keeps the tool list, so loading one rebuilds the CLI without contacting the server. The token is redacted, so pass the config again: ```python theme={null} ws = await Workspace.load("snap.tar", clis={"issues": config}) ``` # ntn Source: https://docs.mirage.strukto.ai/python/cli/ntn Supported Notion commands for Markdown pages, data sources and API calls. Read and edit Notion page bodies as Markdown, query data sources, or call the Notion API directly. Mirage implements the command subset below using the [official `ntn` grammar](https://www.npmjs.com/package/ntn). ## Setup Create an integration and grant it access to the relevant pages using [Notion setup](/home/setup/notion). ```python theme={null} from mirage import Workspace from mirage.commands.cli.builtin.ntn import NTN from mirage.core.notion.config import NotionConfig config = NotionConfig(api_key="secret_...") ws = Workspace({}) ws.register_cli("ntn", NTN, config) ``` No service mount is required. For YAML and multiple accounts, see the [CLI overview](/python/cli/index#register-a-cli). ## Supported commands Run `ntn <command> --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `ntn api` | Call the public Notion API (beta) | | `ntn auth token` | Print the current authentication token | | `ntn datasources query` | Query pages in a data source | | `ntn datasources resolve` | Resolve a Notion database ID to its data source IDs | | `ntn files create` | Create a file upload from stdin or an external URL | | `ntn files get` | Retrieve a file upload by id | | `ntn files list` | List file uploads. Aliases: `ls`. | | `ntn pages get` | Retrieve a page as Markdown | | `ntn pages create` | Create a page from Markdown content | | `ntn pages edit` | Edit a page's content from Markdown | | `ntn pages trash` | Trash a page | | `ntn whoami` | Show the authenticated Notion user | ## Read and edit pages ```bash theme={null} ntn whoami ntn pages get PAGE_ID ntn pages get PAGE_ID --json ntn pages create --parent page:PARENT_ID --content '# Release notes' echo '# Release notes' | ntn pages create --parent data-source:SOURCE_ID ntn pages edit PAGE_ID --content '# Updated body' ntn pages trash PAGE_ID --yes cat /data/photo.png | ntn files create --filename photo.png ntn files create --external-url https://example.com/photo.png ntn files get UPLOAD_ID ntn files list --json ``` Page IDs are positional. Bodies are Markdown; the first heading becomes the title when creating a page. `--parent` accepts `page:`, `database:` or `data-source:` followed by an ID. **`pages edit` replaces the entire body.** Trashing requires confirmation; pass `--yes` for noninteractive use. To update database-row properties, use the API rather than page-body editing: ```bash theme={null} ntn api v1/pages/PAGE_ID -X PATCH -d '{"properties":{"Stage":{"select":{"name":"Draft"}}}}' ``` ## Query data sources ```bash theme={null} ntn datasources resolve DATABASE_ID ntn datasources query SOURCE_ID --limit 10 -s 'Priority desc' ntn datasources query SOURCE_ID --filter '{"property":"Stage","select":{"equals":"Done"}}' ntn datasources query SOURCE_ID --filter-file /work/filter.json --json ``` `resolve` returns a database's data source IDs. `query` accepts a data source or database ID/URL. Its default output is tab-separated: page ID followed by property values, with columns sorted by name from the returned rows. `--json` returns the API response. `--filter-file` reads through the workspace VFS, relative to the session's working directory. ## Call the API ```bash theme={null} ntn api v1/users/me ntn api v1/search -d '{"query":"Roadmap"}' ntn api v1/blocks/PAGE_ID/children page_size==10 ntn api v1/blocks/BLOCK_ID -X DELETE printf '{"query":"Roadmap"}' | ntn api v1/search ``` | Input | Meaning | | - | - | | `-d` / `--data`, stdin, or inline fields | Request body; choose one source | | `name=value` | String body field | | `name:=json` | Typed JSON body field | | `name==value` | Query parameter, regardless of method | | `Header:Value` | Request header | | `-X` / `--method` | `GET`, `POST`, `PATCH`, `PUT` or `DELETE` | A body selects POST unless a method is explicit. Blocks, comments and search use API paths; they are not separate command groups. ## VFS and limits The optional [Notion VFS](/python/vfs/notion) provides page and database files. Reuse its IDs, or obtain them through the API; no mount is required. Interactive login/logout, update, workers, deployment and file-management commands are absent. The config supplies the credential. Command-line parsing follows CLAP style. Exit codes distinguish these failures: | Failure | Exit code | | - | - | | Unknown options or missing required arguments, such as `ntn --bogus` or `ntn pages get` | 2 | | Invalid JSON in a nonempty `ntn api --data` body or stdin | 1 | | Empty `--data`, invalid inline request input, or conflicting body sources | 5 | | Notion API authentication failure (HTTP 401) | 4 | | Other Notion API failures | 5 | The shared conformance suite checks the implemented surface against `ntn`. The suite pins `ntn` 0.21.9, whose [package metadata](https://registry.npmjs.org/ntn/0.21.9) declares MIT. Mirage's command implementation is Apache-2.0; see [compatibility and licenses](/home/setup/clis#compatibility-and-licenses). # search Source: https://docs.mirage.strukto.ai/python/cli/search Rank the records of Dify, Chroma, mem0, Qdrant and LanceDB mounts for a query. `search` asks a mount's own search to rank its records for a query: Dify's retrieval API, Chroma's and Qdrant's vector queries, mem0's memory search and LanceDB's vector search. Use it when meaning matters; `grep` and `rg` still match exact text. ## Setup `search` has no account config. It searches the mounts it is pointed at, so register it on a workspace that mounts a store: ```python theme={null} from mirage import MountMode, Workspace from mirage.commands.cli.builtin.search import SEARCH from mirage.vfs.chroma import ChromaConfig, ChromaVFS vfs = ChromaVFS(ChromaConfig(collection_name="docs")) ws = Workspace({"/knowledge/": vfs}, mode=MountMode.READ) ws.register_cli("search", SEARCH) await ws.shell('search "how do I get started" /knowledge/') ``` Mounting a store does not register `search`. For YAML registration, see the [CLI overview](/python/cli/index#register-a-cli): ```yaml theme={null} clis: search: cli: search ``` ## Supported commands Run `search --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `search` | Rank the records of a search mount for a query | ## Usage ```bash theme={null} search "how do I reset my password" /knowledge/ search --top-k 5 "billing policy" /knowledge/policies/ /knowledge/guides/ search --threshold 0.4 "quickstart" /knowledge/guides/*.md ``` | Argument | Meaning | | - | - | | `QUERY` | The text to rank records by. | | `PATH ...` | Folders, files or globs to search; the working directory when none is given. Several are ranked as one query when one mount serves them all. | | `--top-k N` | The most hits to print, 1 or more. Absent, the mount's default: 10, or the config's `search_limit` on Qdrant and LanceDB and `default_search_limit` on mem0. | | `--threshold F` | The score a hit must reach, or on LanceDB the largest distance it may have; `0` keeps every hit. | | `--method M` | `semantic`, the default. Dify also takes `fulltext`, `hybrid` and `keyword`. | Each hit prints its path, then its score where the store ranks, then the record's text: ```text theme={null} /knowledge/policies/refunds:0.82 Refunds are allowed within 30 days. ``` A file the session cannot see is never printed. ## Mounts | Mount | Searches with | `--threshold` | | - | - | - | | [Dify](/python/vfs/dify#search) | The dataset retrieval API | Dify's score, from 0 to 1 | | [Chroma](/python/vfs/chroma#vector-search) | Chroma's vector query | 1 minus Chroma's distance | | [mem0](/python/vfs/mem0#search) | mem0's memory search | mem0's score, from 0 to 1 | | [Qdrant](/python/vfs/qdrant#semantic-search) | Qdrant's vector query | Qdrant's score | | [LanceDB](/python/vfs/lancedb#semantic-search) | LanceDB's vector search | The largest distance kept | ## Answer from a custom VFS A [custom VFS](/python/vfs/new) joins the list by defining `search`. It gets the path the line names and a `SearchQuery`: the text in `query`, and in `options` the `top_k`, `threshold` and `method` the line gives. It returns one `(path, record)` pair per hit, the hit's workspace path and the text `search` prints; `[]` means no match and `None` declines. A VFS that ranks several paths together defines `search_many(paths, query)` as well. Pass the path on to the service, so a search under one folder ranks only that folder's notes and no other folder's hits use up `top_k`. ```python theme={null} from mirage import BaseVFS, PathSpec, SearchQuery from mirage.utils.key_prefix import mounted_path class NotesVFS(BaseVFS): async def search(self, path: PathSpec, query: SearchQuery) -> list[tuple[str, str]] | None: hits = await self.accessor.client.search( query.query, folder=path.vfs_path, limit=int(query.options.get("top_k", 10)) ) return [(mounted_path(path, "/" + hit.key).virtual, hit.text) for hit in hits] ``` A search never passes the file cache. To keep results, the accessor holds a `ResponseCache` and returns it from `caches()`; the mount then expires it with its read policy and drops it after a write from outside Mirage. ```python theme={null} from mirage import Accessor, ResponseCache class NotesAccessor(Accessor): def __init__(self) -> None: self.searches = ResponseCache[str, list[tuple[str, str]]]() def caches(self): return (self.searches,) ``` `await self.searches.get(key, fetch)` answers from the cache or calls `fetch`. ## Errors | Line | Exit | Prints | | - | - | - | | No query, an empty one, `--top-k` below 1, an unknown option, or a value that is not a number | 2 | `search: query is required`, `search: top-k must be positive`, or the option error and `Try 'search --help' for more information.` | | A value the mount does not take, such as `--method keyword` on Chroma or `--threshold 1.5` on Dify | 1 | The mount's reason, such as `search: only the 'semantic' method is supported` | | A path that does not exist | 1 | `search: /knowledge/nope: No such file or directory` | | A path on a mount without search | 1 | `search: /data: Operation not supported` | # slack Source: https://docs.mirage.strukto.ai/python/cli/slack Supported Slack commands for messages, reactions, pins, members and search. Read and send Slack messages, share files, manage reactions and pins, and look up members or search messages. The action names follow [OpenClaw](https://github.com/openclaw/openclaw); `search` and `list-members` are Mirage extensions. ## Setup Use the bot and user token scopes in [Slack setup](/home/setup/slack). The bot token handles ordinary actions; `search` needs `search_token` (`searchToken` in TypeScript). ```python theme={null} from mirage import Workspace from mirage.commands.cli.builtin.slack import SLACK from mirage.core.slack.config import SlackConfig config = SlackConfig(token="xoxb-...", search_token="xoxp-...") ws = Workspace({}) ws.register_cli("slack", SLACK, config) ``` No service mount is required. For YAML and multiple accounts, see the [CLI overview](/python/cli/index#register-a-cli). ## Supported commands Run `slack <command> --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `slack send-message` | Post a message to a channel or thread | | `slack edit-message` | Replace the text of a message | | `slack delete-message` | Delete a message | | `slack upload-file` | Share a workspace file in a channel or thread | | `slack read-messages` | Read the most recent messages of a channel | | `slack react` | Add an emoji reaction to a message | | `slack reactions` | List the reactions on a message | | `slack pin-message` | Pin a message to its channel | | `slack unpin-message` | Remove a pin from a message | | `slack list-pins` | List the pinned items of a channel | | `slack member-info` | Fetch one user's profile | | `slack list-members` | List workspace members, optionally filtered | | `slack emoji-list` | List the workspace's custom emoji | | `slack search` | Search messages with Slack query operators | ## Messages, reactions and pins ```bash theme={null} slack read-messages --channel C04KEPWF6V7 --limit 20 slack send-message --channel C04KEPWF6V7 --text "Release is ready" slack send-message --channel C04KEPWF6V7 --thread-ts 1712345678.123456 --text "Thread reply" slack edit-message --channel C04KEPWF6V7 --ts 1712345678.123456 --text "Release shipped" slack delete-message --channel C04KEPWF6V7 --ts 1712345678.123456 slack upload-file --channel C04KEPWF6V7 --file /data/reply.wav --initial-comment "Spoken reply" slack react --channel C04KEPWF6V7 --ts 1712345678.123456 --emoji thumbsup slack reactions --channel C04KEPWF6V7 --ts 1712345678.123456 slack pin-message --channel C04KEPWF6V7 --ts 1712345678.123456 slack list-pins --channel C04KEPWF6V7 slack unpin-message --channel C04KEPWF6V7 --ts 1712345678.123456 ``` Channels and users are Slack IDs. A message is identified by its channel and timestamp (`--ts`); replies use the parent's timestamp in `--thread-ts`. `upload-file` reads `--file` from the workspace, so any mount can be the source. ## Find people and messages ```bash theme={null} slack member-info --user U04K21SEVR9 slack list-members --query alice slack emoji-list slack search --query 'from:@priya in:#general launch' --count 20 --page 1 ``` Search accepts Slack operators such as `from:`, `in:` and `after:`. Results are JSON and can be piped to `jq`. ## VFS and limits The optional [Slack VFS](/python/vfs/slack) exposes channels and messages as files. Its IDs can be passed to this CLI, but the CLI gets credentials from its own registration and does not need the mount. Only the listed actions are implemented; this is not Slack's app-development CLI. Mount read-only mode does not prevent service writes—use command policy to restrict sending messages, reactions or pin changes. OpenClaw's source uses the [MIT license](https://github.com/openclaw/openclaw/blob/main/LICENSE). Mirage's command implementation is Apache-2.0; see [compatibility and licenses](/home/setup/clis#compatibility-and-licenses). # trello Source: https://docs.mirage.strukto.ai/python/cli/trello Supported Trello commands for boards, lists, labels, cards and comments. Read Trello boards, lists, labels, cards and comments, and create, update, move, assign, label and comment on cards. Mirage defines this command tree over the [Trello REST API](https://developer.atlassian.com/cloud/trello/rest/); every command prints normalized JSON for `jq`. ## Setup Create an API key and token using [Trello setup](/home/setup/trello). ```python theme={null} from mirage import Workspace from mirage.commands.cli.builtin.trello import TRELLO from mirage.core.trello.config import TrelloConfig config = TrelloConfig(api_key="...", api_token="...") ws = Workspace({}) ws.register_cli("trello", TRELLO, config) ``` No service mount is required. For YAML and multiple accounts, see the [CLI overview](/python/cli/index#register-a-cli). ## Supported commands Run `trello <command> --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `trello board list` | List the boards in scope as JSON | | `trello board show` | Get one board by ID | | `trello board members` | List a board's members | | `trello list list` | List a board's lists | | `trello label list` | List a board's labels | | `trello card list` | List the cards in a list | | `trello card show` | Get one card by ID | | `trello card comments` | List a card's comments | | `trello card create` | Create a new card | | `trello card update` | Update an existing card | | `trello card move` | Move a card to a different list | | `trello card assign` | Assign a member to a card | | `trello card label` | Add a label to a card | | `trello card unlabel` | Remove a label from a card | | `trello card comment` | Add a comment to a card | | `trello card comment-update` | Update an existing comment | ## Find work ```bash theme={null} trello board list trello board show brd_001 trello board members brd_001 trello list list brd_001 trello label list brd_001 trello card list lst_001 trello card show crd_001 trello card comments crd_001 ``` Reads take a board, list or card ID as a positional operand. The [Trello VFS](/python/vfs/trello) embeds each ID after the last `__` of a directory or file name. ## Update cards ```bash theme={null} trello card create --list_id lst_001 --name "Fix login" --desc "Details here" cat brief.md | trello card create --list_id lst_001 --name "Agent bug" trello card update --card_id crd_001 --name "Updated title" --due 2026-11-01 trello card update --card_id crd_001 --closed true trello card move --card_id crd_001 --list_id lst_002 trello card assign --card_id crd_001 --member_id mem_001 trello card label --card_id crd_001 --label_id lbl_001 trello card unlabel --card_id crd_001 --label_id lbl_001 trello card comment --card_id crd_001 --text "Looks good" trello card comment-update --card_id crd_001 --comment_id cmt_001 --text "Updated text" ``` Writes take every ID as a flag. A description or comment comes from `--desc` or `--text`, from the file `--desc_file` or `--text_file` names, or from stdin; `--desc ''` clears a description. `--closed true`, `1` or `yes` archives a card and any other value restores it. Each write prints the card or comment it changed. ## Scope, VFS and limits The CLI uses its own account config and needs no Trello mount. * `workspace_id` and `board_ids` narrow the CLI as they narrow the mount: `trello board list` shows only the boards in scope, and a board, list or card ID on a board outside them is refused before any read or write (`trello card show: card crd_009 is outside the configured scope`, exit 1). * `--desc_file` and `--text_file` read a workspace file through the session, from any mount the session can read. * A read-only Trello mount does not make the CLI read-only: the CLI consults no mount. Use command policy, such as a profile rule denying `trello card create`, to restrict writes. * API failures exit 1 with Trello's error. This is Mirage's Apache-2.0 command implementation for the REST API. No compatibility with a separate Trello CLI is claimed; the API link documents the service rather than an upstream CLI implementation. See [compatibility and licenses](/home/setup/clis#compatibility-and-licenses). # Installation Source: https://docs.mirage.strukto.ai/python/install Install Mirage for Python with mirage-ai from PyPI or uv, then add extras for S3, Redis, FUSE, Google Workspace, and other mounts. ## Quick Install Mirage requires Python 3.12 or newer. In a uv project, install the base package with: ```bash theme={null} uv add mirage-ai ``` This is enough to start with local workflows such as the RAM VFS and to understand the Mirage execution model. In an activated standalone virtual environment, use either installer: ```bash theme={null} uv pip install mirage-ai # or python -m pip install mirage-ai ``` ## Use Mirage as a CLI If you only want the `mirage` CLI (not the library), there are two convenient paths. **One-shot run with `uvx`**, no install, just runs: ```bash theme={null} uvx --from mirage-ai mirage --help uvx --from mirage-ai mirage workspace create workspace.yaml --id demo ``` **Persistent install with `uv tool install`**, drops `mirage` on your PATH globally: ```bash theme={null} uv tool install mirage-ai mirage --help ``` To upgrade later: ```bash theme={null} uv tool install --upgrade mirage-ai ``` ## VFS Extras Install extras when a VFS needs optional dependencies: ```bash theme={null} uv add "mirage-ai[s3]" uv add "mirage-ai[r2]" uv add "mirage-ai[redis]" uv add "mirage-ai[fuse]" ``` Use the VFS docs in the Python section when you are ready to connect real systems. ## Install From Source If you are contributing to Mirage or want the full local development setup: ```bash theme={null} git clone https://github.com/strukto-ai/mirage.git cd mirage/python uv sync --all-extras ``` ## Recommended Path 1. Install the base package. 2. Follow the [Python Quickstart](/python/quickstart) with the RAM VFS. 3. Add the VFS extras and follow the [FUSE setup](/python/setup/fuse) if you need to expose mounts as a real filesystem. # Python Quickstart Source: https://docs.mirage.strukto.ai/python/quickstart Create a Mirage Python workspace, mount RAM as a virtual filesystem, and run shell commands that read, write, search, and transform files. ## Installation Use Python 3.12 or newer. In a uv project, install Mirage with: ```bash theme={null} uv add mirage-ai ``` In another activated environment, install it with: ```bash theme={null} python -m pip install mirage-ai ``` ## Create a Workspace Start with the RAM VFS so you can try Mirage without credentials. ```python quickstart.py theme={null} import asyncio from mirage import MountMode, Workspace from mirage.vfs.ram import RAMVFS async def main() -> None: ws = Workspace({"/data": RAMVFS()}, mode=MountMode.WRITE) await ws.shell('echo \'{"name": "alice"}\' > /data/user.json') files = await ws.shell("ls /data") print(await files.stdout_str(), end="") name = await ws.shell('jq -r ".name" /data/user.json') print(await name.stdout_str(), end="") match = await ws.shell("grep alice /data/user.json") print(await match.stdout_str(), end="") await ws.close() asyncio.run(main()) ``` For a uv project, run `uv run python quickstart.py`. If you installed Mirage in another activated environment, run `python quickstart.py`. It lists `user.json`, prints `alice`, then prints the matching JSON document. Shell failures are returned in the result; check `exit_code` and `stderr_str()` when needed. See the [in-app API reference](/python/access/in-app#session-shell). ## Next Steps * See [Python Installation](/python/install) for VFS extras and the `uv` workflow. * Configure [command output limits](/home/core/output-limits) for large files and long-running commands. * Browse [Python Agents](/python/agents/index) to wire Mirage into the OpenAI Agents SDK, LangChain, and Pydantic AI. * Pick a real backend from [VFS Docs](/python/vfs/index), such as [S3](/python/vfs/s3), [Slack](/python/vfs/slack), or [GitHub](/python/vfs/github). # Runtimes Source: https://docs.mirage.strukto.ai/python/runtime/python What only the Python SDK has for runtimes, WASI details, managing runtimes in code, and child processes. Setup and behavior of every runtime are on the [Runtimes](/home/setup/runtime/overview) pages. This page covers what is specific to the Python SDK. ## Differences from the TypeScript SDK * **Monty:** `os.chdir()` works and lasts for the run, and `os.stat()` returns a real named tuple, so `st[6]` and `len(st)` work. Runs execute on Monty's worker pool, so the event loop stays free and cancelling a run halts the interpreter. Every workspace in the process shares one pool of four workers; a run waiting on workspace I/O holds one, and a run past the four waits for one to free up. * **QuickJS:** the real quickjs-ng `std` and `os`. The first run compiles `qjs-wasi.wasm` and caches `qjs-wasi.cwasm` beside it. A write shows to other commands once the file is closed or the run ends, and a timeout stops the run. * **Local:** with neither `home` nor `MIRAGE_LOCAL_HOME`, `python3` is the interpreter running Mirage. * **Machines:** `mount_type: ssh` needs `pip install 'mirage-ai[ssh]'` on the host. The `ssh` machine matches `host` against `~/.ssh/config`. * **WASI** is in the Python SDK only; Pyodide is in the TypeScript SDK only. ## WASI Install the extra: ```bash theme={null} pip install "mirage-ai[wasi]" ``` Without it, `WasiRuntime(...)` raises `ImportError`. * A read-only mount, or a session narrowed to read, refuses a write at `open()` with `OSError`: errno 30 on the host and Monty, or preview1 errno 69 under WASI. * The CPython build is read-only in the run. A mount at `/` coexists with it: each mount wins under its prefix. * A run starts in the shell's working directory; a missing one fails before any code runs. A direct `execute()` runs in its context's `cwd`. * A script runs as in CPython: `__file__` is absolute, tracebacks quote its lines, and `sys.path[0]` is its directory (`-P` and `-I` leave it off). * The first run compiles `python.wasm` and caches `python.cwasm` beside it; later runs start in milliseconds. A timeout stops the run. ## Managing runtimes in code `Workspace(runtimes=[...])` takes names and runtime objects, and adds `workspace` when the list leaves it out. On a live workspace, `add_runtime` appends an entry (one that runs on a machine goes after the last such entry, else ahead of Monty and QuickJS), `remove_runtime` takes one out, and `runtimes()` lists them: ```python theme={null} from mirage.runtime.python import WasiRuntime await ws.remove_runtime("monty") ws.add_runtime(WasiRuntime(config={"home": "/opt/cpython-wasi"})) ``` `python3` moves to the new runtime at once. A running line finishes before its removed runtime closes, a removed instance cannot be added again, and `workspace` cannot be removed. `register_runtime(name, cls)` makes your own runtime class available by name in YAML. ## Child processes A host application starts a program through the same admitted entry point as the shell. ```python theme={null} from mirage.execution.process.types import SpawnRequest child = ws.spawn(SpawnRequest(("cat",))) result = await child.communicate(b"hello\n") ``` # FUSE Source: https://docs.mirage.strukto.ai/python/setup/fuse Set up FUSE support for MIRAGE in Python. ## Prerequisites * Python 3.12+ * [uv](https://docs.astral.sh/uv/) package manager (optional) ## System FUSE Install the OS-level FUSE driver first (see the [support matrix](/home/setup/fuse) for the full OS overview): * [macOS FUSE Setup](/home/setup/macos), macFUSE + kernel extension + Apple Silicon recovery mode steps. * [Linux FUSE Setup](/home/setup/linux), `fuse3` install and `/etc/fuse.conf`. * [Windows FUSE Setup](/home/setup/windows), WinFsp install; experimental. ## Install Mirage with the FUSE Extra ```bash theme={null} pip install "mirage-ai[fuse]" ``` Or with uv: ```bash theme={null} uv add "mirage-ai[fuse]" ``` ## Verify ```python theme={null} from mirage import Mount, MountBackend, MountMode, Workspace from mirage.vfs.ram import RAMVFS with Workspace( {"/data": Mount(RAMVFS(), mode=MountMode.WRITE, backend=MountBackend.FUSE)}) as ws: print("mountpoints:", ws.fuse_mountpoints) ``` If the printed path exists under `/tmp/mirage-*`, FUSE is wired up correctly. The `Workspace` constructor blocks until every kernel mount is live, so the mountpoint is ready to read as soon as the `with` block is entered, no sleep needed. (In TypeScript, where mounts are async, you `await ws.fuseReady()` instead.) The folder is served on the workspace's event loop, the one its calls run on. In async code, never block that loop on the folder: a synchronous `open()` there, or `subprocess.run` or `asyncio.create_subprocess_exec` with `cwd` inside it, waits on a call only that loop can answer. Use `asyncio.to_thread`, or pass the folder's paths as arguments. A workspace that a `with` block uses first, or that a [`WorkspaceRunner`](/python/access/server#beside-your-own-event-loop) or the server runs, has a loop of its own, so your code may block there. A `with` block entered after async calls keeps their loop. ## Per-mount backends How a mount is exposed is configured **per mount**, through one `backend` field: | `backend` | Effect | | - | - | | `workspace` (default) | Lives only inside mirage's own filesystem, reached through the command surface. Nothing is registered with the kernel. | | `fuse` | Also exposed as a real mountpoint via FUSE. | | `fskit` | Also exposed as a real mountpoint via FSKit, with no kernel extension. macOS 15.4+ only; see below. | | `nfs` | Also exposed as a real mountpoint through the operating system's NFS client: mirage serves NFSv3 on a local port and runs the system `mount`, so no FUSE install is needed. Linux and macOS; Linux needs root to mount. Read-only. A mount that does not set `sizes_always_known` still mounts, with a warning, but its size-unknown files read as empty; use `fuse` for it. | A kernel-backed mount shows only that mount's subtree. `mountpoint` pins where it lands; omit it for a fresh temp directory: ```yaml theme={null} mode: WRITE mounts: /data: vfs: ram backend: fuse mountpoint: /tmp/data-repo # explicit path /s3: vfs: s3 backend: fuse # temp directory /logs: vfs: disk # no backend key: stays on the workspace default, not kernel-mounted ``` `ws.fuse_mountpoints` returns a `{prefix: path}` map of the live mountpoints. ## Mounting without the kernel extension (FSKit) Apple has deprecated third-party kernel extensions: on Apple Silicon the macFUSE kext already needs a reduced-security boot plus admin approval, and future macOS releases are expected to stop loading it entirely. FSKit (macOS 15.4+) is Apple's supported userspace replacement, and macFUSE 5.x serves the same libfuse API through it. `backend=fskit` is mirage's path to keep real mounts working on Macs where the kext is blocked. Only the kernel-to-userspace hop changes: ```mermaid theme={null} flowchart LR A[cat /Volumes/.../file] --> K[kernel VFS] K -->|backend=fuse| X[macFUSE kext] --> L[libfuse] K -->|backend=fskit| F[fskitd + macFUSE FSKit module] --> L L --> M[MirageFS] --> R[vfs] ``` Set `backend` on the mount: ```python theme={null} from mirage import Mount, MountBackend, MountMode, Workspace from mirage.vfs.ram import RAMVFS with Workspace({ "/data/": Mount(RAMVFS(), mode=MountMode.WRITE, backend=MountBackend.FSKIT) }) as ws: print(ws.fuse_mountpoint) # /Volumes/mirage-... ``` `kextstat` stays empty and the mount table tags the volume `fskit`. Two rules are enforced at mount time rather than discovered at run time: * **The mountpoint must be under `/Volumes`.** FSKit refuses anything else. Mirage names one automatically when you do not pass a path, and rejects an explicit path outside it. * **Mirage does not create the mountpoint, macOS does.** An FSKit mount is a volume: the `/Volumes` entry appears when the filesystem goes live and is removed when it unmounts. `/Volumes` is root-owned, so nothing here needs (or could get) elevated permissions. * **Every mounted VFS must be able to size its files.** See below. There is deliberately **no `auto`** value: auto-selecting FSKit would silently break every API-backed mount, and an option whose safe value is always the default is a trap. `MountBackend.FSKIT` is macOS-only and raises elsewhere. The metadata write surface works: create, mkdir, rename, unlink and in-place overwrites. This depends on `mirage/fuse/darwin.py`, which declares macFUSE's Darwin-only callbacks (`setattr_x`, `renamex`) that the FSKit shim uses to finalize new items and route renames; stock mfusepy leaves those slots NULL, which fails every create with ENOSYS after the file already landed. > [!WARNING] > > **Treat fskit mounts as read-mostly.** The macFUSE FSKit shim flushes > pages a file did not already have (a new file, `cp`, `>` truncation) as > NUL bytes; appends are hit-or-miss. The writer sees no error, and the > kernel page cache serves the written data back, so the corruption only > shows in the backing store. Mirage warns at mount time on writable fskit > mounts (`check_writes`); use `MountBackend.FUSE` for writes. > [!WARNING] > > **Two more upstream FSKit-shim caveats** (macFUSE 5.3.3): > [#1181](https://github.com/macfuse/macfuse/issues/1181), running a binary > off an fskit mount fails until the file has been read once; and > [#1165](https://github.com/macfuse/macfuse/issues/1165), new entries in > the volume root may not appear in a live mount because the root readdir > cache cannot be invalidated. > [!WARNING] > > **Size-unknown files read as empty.** There is no `direct_io`, so reads > stop at the size `stat` reported; a file that stats 0 pre-open reads as > empty with exit code 0. Mirage warns at mount time, naming the degraded > mounts (`sizes_always_known`). Byte stores (ram, disk, redis, s3, > gridfs) and Linear (size push-down) qualify; for the rest, use > `MountBackend.FUSE` or scope the fskit mount to a sized subtree. `examples/python/fuse/fskit.py` runs all of this end to end: the size warning, exact reads on a live mount, and each write op with its result. TypeScript supports the same backend with the same size and write warnings, but it cannot create new names: `create`, `mkdir` and `rename` return ENOSYS there ([details](/typescript/setup/fuse#mounting-without-the-kernel-extension-fskit)); `examples/typescript/fuse/fskit.ts` is its live end-to-end check. ## Size semantics for API-backed files Some mounts (Linear, Trello, Slack, ...) cannot report a file's size without fetching its content, so `stat` returns an unknown size. Over the FUSE mount these files behave like Linux `/proc` files: they stat as **0 bytes until first open**, and become fully readable the moment anything opens them. Mirage mounts with `direct_io` (the kernel reads to EOF regardless of the reported size) and `attr_timeout=0` (post-open `fstat` returns the real size of the now-fetched content, kept warm in a 30-second cache). What that means per tool: | Tools | Behavior | | - | - | | `cat`, `grep`, `head`, `cp`, `md5sum`, `sed`, `sort` | correct content, always | | `wc -c`, `tail -c` | correct (they fstat after open, which serves the real size) | | `ls -l`, `du`, `find -size`, `test -s` | report 0 until the file has been opened recently | | `tar`, `rsync`, `scp` | see 0 at stat time and copy empty content, exactly like `tar` over `/proc`; read the file first or use `cat`/`cp` based flows | Mirage never reports a fake size and never fetches content during `stat`: returning real sizes eagerly would fire one API call per file on every `ls -l`. > [!NOTE] > > **Windows differs**: it cannot query attributes without opening a handle, > so a per-file `stat` of a size-unknown file fetches the content and shows > the real size immediately. Directory listings stay cheap. See > [Windows FUSE Setup](/home/setup/windows) for the other Windows-specific > behaviors (unmount at process exit, mount-level ownership). > [!WARNING] > > **macOS allows only one in-process FUSE mount.** macFUSE registers a > process-global signal source, so a second simultaneous mount in the same > process fails with `fuse: cannot register signal source`. Multiple per-mount > FUSE mounts work on Linux and Windows; on macOS, use a kernel backend on a single > mount per workspace (or run additional mounts in separate processes). ## Symlinks and Permissions Symlinks live in Mirage's namespace, not in any backend. Links created with `ln -s` in the Mirage shell (or with `ln -s` inside the mountpoint) appear as real symlinks over FUSE: `ls -l` shows `lrwxrwxrwx`, `readlink` prints the target, and reads follow the link. Absolute targets are displayed relative to the link's directory so they always resolve inside the mountpoint. Permission bits shown over FUSE come from Mirage's metadata (`chmod`, `chown`, `touch` results), and they are **display only**: access control is enforced by Mirage mount modes, not by the kernel. For that reason, never mount with the `default_permissions` FUSE option. It would make the kernel enforce the displayed bits, and a `chmod 000` could lock Mirage out of its own files. Extended attributes over FUSE are the ones the Mirage shell's `getfattr` and `setfattr` read and write. Mirage stores them in its namespace beside the symlinks, so every backend takes them. # Airtable Source: https://docs.mirage.strukto.ai/python/vfs/airtable Mount Airtable bases, tables, records, and saved views as a Mirage filesystem for Python agents. The Airtable VFS exposes the bases a personal access token can reach as a read-only filesystem mounted at a prefix such as `/airtable/`. Writes go through the [airtable CLI](/python/cli/airtable), which takes the same config. For token setup, see [Airtable Setup](/home/setup/airtable). ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.airtable import AirtableConfig, AirtableVFS config = AirtableConfig(token=os.environ["AIRTABLE_TOKEN"]) vfs = AirtableVFS(config=config) ws = Workspace({"/airtable": vfs}, mode=MountMode.READ) ``` | Field | Description | | - | - | | `timeout` default `30` | 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. | | `token` required, secret | Personal access token (or OAuth access token), sent as `Authorization: Bearer`. | | `base_ids` | Only these bases are listed or readable. Unset shows every base the token can reach. | | `base_url` default `'https://api.airtable.com/v0'` | Airtable API root; override to point at a fake or proxy. | | `max_read_records` default `10000` | The most records one file renders. A full read of a larger table or view fails with `File too large` once it passes the cap; `head -n N` still reads its first records. | | `requests_per_second` default `5.0` | Requests per second per base. Airtable allows 5 and answers a burst with a 30-second penalty. | Fields marked secret are redacted in snapshots. Unknown keys are refused, so a misspelled `base_ids` fails loudly instead of widening the mount to every base. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Airtable mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `airtable`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > bases/ > <base-name>__<base-id>/ > base.json # base id, name, permission, tables > <table-name>__<table-id>/ > table.json # typed fields (with options), views > records.jsonl # one record per line > views/ > <view-name>__<view-id>.jsonl # records the view shows, in order > ``` > > * `ls` a directory first to find exact names: the name part of a segment > is sanitized, the id after the last `__` is exact. > * A `records.jsonl` line is a normalized record: `record_id`, > `created_time` and `fields`, keyed by field name with values as > Airtable returns them. `table.json` gives each field's type. > * Airtable omits empty cells, so a missing key means empty, a `false` > checkbox included. A link field is a list of record ids; an attachment > URL expires two hours after it was read. > * `records.jsonl` lists in the API's own order; a view file applies the > view's filter and sort. > * A file over `max_read_records` records stops with `File too large` > after that many, while `head -n N` fetches just N records. > * The `airtable` CLI, if installed, reaches what a file cannot: > server-side filters (`airtable record list --formula` or `--view`), one > record by id (`airtable record get`) and comments > (`airtable comment list`). > > ```sh theme={null} > head -n 20 /<path>/bases/<base>/<table>/records.jsonl | jq .fields > ``` > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep` and `rg` ask `airtable` for the matching lines. `head` asks `airtable` instead of reading a file. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `airtable`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > bases/ > <base-name>__<base-id>/ > base.json # base id, name, permission, tables > <table-name>__<table-id>/ > table.json # typed fields (with options), views > records.jsonl # one record per line > views/ > <view-name>__<view-id>.jsonl # records the view shows, in order > ``` > > - `ls` a directory first to find exact names: the name part of a segment > is sanitized, the id after the last `__` is exact. > - A `records.jsonl` line is a normalized record: `record_id`, > `created_time` and `fields`, keyed by field name with values as > Airtable returns them. `table.json` gives each field's type. > - Airtable omits empty cells, so a missing key means empty, a `false` > checkbox included. A link field is a list of record ids; an attachment > URL expires two hours after it was read. > - `records.jsonl` lists in the API's own order; a view file applies the > view's filter and sort. > - A file over `max_read_records` records stops with `File too large` > after that many, while `head -n N` fetches just N records. > - The `airtable` CLI, if installed, reaches what a file cannot: > server-side filters (`airtable record list --formula` or `--view`), one > record by id (`airtable record get`) and comments > (`airtable comment list`). > > ```sh > head -n 20 /<path>/bases/<base>/<table>/records.jsonl | jq .fields > ``` > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep` and `rg` ask `airtable` for the matching lines. `head` asks `airtable` instead of reading a file. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ```` Names are sanitized (`Ops / Finance` becomes `Ops_Finance`); the id after the last `__` is exact. List a directory to discover names rather than building them. * `base.json` holds the base id, name, the token's permission level, and the table list. * `table.json` holds the typed field schema, with each field's options (select choices, number precision, link targets), and the saved views. * `records.jsonl` holds one record per line: `{"record_id", "created_time", "fields"}`, with `fields` keyed by field name and valued exactly as Airtable returns them. * `views/<view>.jsonl` holds the records the view shows, filtered and ordered by the view. ## Reading Records ```bash theme={null} head -n 20 /airtable/bases/Product_Roadmap__appRoadmapBase001/Features__tblFeatures000001/records.jsonl | jq .fields jq -r 'select(.fields.Status == "Done") | .fields.Name' .../records.jsonl grep -c Done .../views/Done_shipped__viwDone0000000001.jsonl ``` * **`head -n N` fetches N records.** The line count is pushed into Airtable's `maxRecords`, so the first lines of a large table cost one request. * **A full read is bounded.** A file holding more than `max_read_records` records ends with GNU's `File too large` (`cat: <path>: File too large`), rather than paging for minutes at 5 requests per second. `cat` and `grep` print each page of records as it arrives, so the first `max_read_records` records come before the error, and a reader that stops first (`head -c 100`, `grep -l`) stops the paging and never reaches it. Every command reports it per file and moves on, so `grep -l x a b` still answers for the files under the cap. Use `head`, a view, or raise the cap. * **Order.** `records.jsonl` follows the API's own order, which Airtable calls arbitrary but keeps stable; a view file applies the view's sort. * **Empty cells are absent.** Airtable omits empty values from a record, including a `false` checkbox, so a missing key means empty. * **Links and attachments.** A linked-record field is a list of record ids. An attachment URL expires two hours after it was read, so re-read the record before downloading. * **Sizes.** `base.json` and `table.json` report their exact size. Record files are size-unknown until read, which is what `ls -l` and `stat` show. * **Freshness.** Records are never served from the file cache; the listings of bases, tables, and views are cached for the index TTL. ## Integration What Airtable answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Airtable | | - | - | | `grep`, `rg` on one file | A `filterByFormula` fetches only the records that may match | | `head -n N` | Fetches N records | For one plain text in a `records.jsonl` or a view's file, grep and rg ask Airtable for the records that may hold it, with a `filterByFormula` that searches the record id and each text, select, email, url and phone cell, lowercased, and search those records instead of the whole table, in the order a plain read lists them. Number, date and checkbox cells hold no word to search. A link, AI text or attachment cell holds no space outside the text a formula reads of it, so a table with one is searched for a text with a space and read for a single word. The file is read as usual for a table with a collaborator, lookup, rollup or formula field, for a text a field name holds, or when more than `max_read_records` records match. Since only the matching records are fetched, a table too large to read can still be searched when the output shows no line numbers or context. ## Rate Limits Requests are spaced to `requests_per_second` per base. A `429` that says `RATE_LIMIT_REACHED` is retried after Airtable's 30 second penalty; a `429` for an exhausted monthly quota is reported at once, because waiting cannot fix it. ## Writing Records A record write is not a file write, so the mount refuses one and the [airtable CLI](/python/cli/airtable) makes it. The CLI names a base, a table and a record by id: take them from the mount's directory names, after the last `__` (`Product_Roadmap__appRoadmapBase001` is `appRoadmapBase001`), and a record's from its `record_id`. A `records.jsonl` line is the CLI's stdin shape, so an edit pipes straight back: ```bash theme={null} jq -c 'select(.fields.Status == "Todo") | .fields.Status = "Done"' \ /airtable/bases/Product_Roadmap__appRoadmapBase001/Features__tblFeatures000001/records.jsonl \ | airtable record update --base appRoadmapBase001 --table tblFeatures000001 ``` The CLI also reaches what a file cannot: server-side filters (`airtable record list --formula` or `--view`), one record by id (`airtable record get`), and comments (`airtable comment list`, `airtable comment add`). # Alibaba OSS Source: https://docs.mirage.strukto.ai/python/vfs/aliyun Mount an Alibaba Cloud OSS bucket via its S3-compatible API as a virtual filesystem. The Aliyun VFS is a thin wrapper over the [S3 VFS](/python/vfs/s3). It maps an `AliyunConfig` to an `S3Config` and reuses the exact same backend, commands, and behavior as S3, it just derives the right OSS endpoint from `region`. Uses aioboto3 against Alibaba OSS's S3-compatible API. The endpoint is computed from `region` as `s3.oss-<region>.aliyuncs.com` (e.g. `s3.oss-cn-hangzhou.aliyuncs.com`). Note the `s3.` prefix: this is the S3-compatible host, distinct from the native `oss-<region>.aliyuncs.com`. Pass `endpoint_url` to override. Install the extra: ```bash theme={null} pip install "mirage-ai[s3]" ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.aliyun import AliyunConfig, AliyunVFS config = AliyunConfig( bucket=os.environ["OSS_BUCKET"], region=os.environ.get("OSS_REGION", "cn-hangzhou"), access_key_id=os.environ["OSS_ACCESS_KEY_ID"], secret_access_key=os.environ["OSS_ACCESS_KEY_SECRET"], # Optional: # endpoint_url="https://s3.oss-cn-hangzhou.aliyuncs.com", # timeout=30, # proxy="http://proxy:8080", ) vfs = AliyunVFS(config) ws = Workspace({"/data": vfs}, mode=MountMode.READ) ``` Both `READ` and `WRITE` modes are supported. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `bucket` required | Name of the bucket to mount. | | `region` required | Provider region every request is signed for. Most providers also build their endpoint URL from it unless `endpoint_url` is set. | | `endpoint_url` | Endpoint URL that replaces the one the provider derives. | | `access_key_id` secret | Access key ID; set it with `secret_access_key`. Unset uses the AWS credential chain. | | `secret_access_key` secret | Secret access key paired with `access_key_id`. | | `session_token` secret | Session token for temporary credentials, sent with the access key pair. | | `aws_profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `path_style` default `False` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `key_prefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | Fields marked secret are redacted in snapshots. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Alibaba OSS mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.vfs.aliyun import AliyunConfig, AliyunVFS load_dotenv(".env.development") config = AliyunConfig( bucket=os.environ["OSS_BUCKET"], region=os.environ.get("OSS_REGION", "cn-hangzhou"), access_key_id=os.environ["OSS_ACCESS_KEY_ID"], secret_access_key=os.environ["OSS_ACCESS_KEY_SECRET"], ) vfs = AliyunVFS(config) async def main() -> None: ws = Workspace({"/data/": vfs}, mode=MountMode.READ) r = await ws.shell("ls /data/") print(await r.stdout_str()) r = await ws.shell("tree /data/") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Notes * Aliyun registers under its own `VFSName` and routes through the same `core/s3` implementation, so the full S3 shell-command set applies. See the [S3 VFS](/python/vfs/s3) for the complete command reference, range reads, streaming, and the index cache fast path. * For credential setup, see [Alibaba OSS Setup](/home/setup/aliyun). # Backblaze B2 Source: https://docs.mirage.strukto.ai/python/vfs/backblaze Mount a Backblaze B2 bucket via its S3-compatible API as a virtual filesystem. The Backblaze VFS is a thin wrapper over the [S3 VFS](/python/vfs/s3). It maps a `BackblazeConfig` to an `S3Config` and reuses the exact same backend, commands, and behavior as S3, it just derives the right B2 endpoint from `region`. Uses aioboto3 against Backblaze B2's S3-compatible API. The endpoint is computed from `region` as `s3.<region>.backblazeb2.com`. Pass `endpoint_url` to override. Install the extra: ```bash theme={null} pip install "mirage-ai[s3]" ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.backblaze import BackblazeConfig, BackblazeVFS config = BackblazeConfig( bucket=os.environ["B2_BUCKET"], region=os.environ["B2_REGION"], # e.g. us-west-004 access_key_id=os.environ["B2_ACCESS_KEY_ID"], # B2 application keyID secret_access_key=os.environ["B2_SECRET_ACCESS_KEY"], # Optional: # endpoint_url="https://s3.us-west-004.backblazeb2.com", # timeout=30, # proxy="http://proxy:8080", ) vfs = BackblazeVFS(config) ws = Workspace({"/data": vfs}, mode=MountMode.READ) ``` Both `READ` and `WRITE` modes are supported. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `bucket` required | Name of the bucket to mount. | | `region` required | Provider region every request is signed for. Most providers also build their endpoint URL from it unless `endpoint_url` is set. | | `endpoint_url` | Endpoint URL that replaces the one the provider derives. | | `access_key_id` secret | Access key ID; set it with `secret_access_key`. Unset uses the AWS credential chain. | | `secret_access_key` secret | Secret access key paired with `access_key_id`. | | `session_token` secret | Session token for temporary credentials, sent with the access key pair. | | `aws_profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `path_style` default `False` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `key_prefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | Fields marked secret are redacted in snapshots. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Backblaze B2 mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.vfs.backblaze import BackblazeConfig, BackblazeVFS load_dotenv(".env.development") config = BackblazeConfig( bucket=os.environ["B2_BUCKET"], region=os.environ["B2_REGION"], access_key_id=os.environ["B2_ACCESS_KEY_ID"], secret_access_key=os.environ["B2_SECRET_ACCESS_KEY"], ) vfs = BackblazeVFS(config) async def main() -> None: ws = Workspace({"/data/": vfs}, mode=MountMode.READ) r = await ws.shell("ls /data/") print(await r.stdout_str()) r = await ws.shell("find /data/ -name '*.csv'") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Notes * Backblaze registers under its own `VFSName` and routes through the same `core/s3` implementation, so the full S3 shell-command set applies. See the [S3 VFS](/python/vfs/s3) for the complete command reference, range reads, streaming, and the index cache fast path. * For credential setup, see [Backblaze B2 Setup](/home/setup/backblaze). # Box Source: https://docs.mirage.strukto.ai/python/vfs/box Mount a Box account (or a single folder of it) as a read/write Mirage filesystem with async access and shell commands. The Box VFS mounts a Box account at some prefix such as `/box/`. All operations involve network I/O to the [Box v2 HTTP API](https://developer.box.com/reference/): `/2.0/folders/{id}/items` for directories, `/2.0/files/{id}/content` for content, and multipart upload / `/2.0/folders` / `delete` / `PUT` (rename or move) / `copy` for writes. Files are served as raw bytes. Both `READ` and `WRITE` modes are supported. Box addresses everything by numeric **item id**, not by path (the account root is folder id `0`). Mirage resolves each path to its id by listing folders level by level and caches the path → id mapping, so nested directories cost one API call per level on first access. Every Box item is served as its raw bytes, keeping its real name. Box's native `.boxnote` / `.boxcanvas` come back as their stored ProseMirror-style JSON (text, so `cat foo.boxnote | jq .` works), and Box's Google-Workspace files (`.gdoc` / `.gsheet` / `.gslides`) come back as the Office Open XML zips (`docx` / `xlsx` / `pptx`) Box stores them as, opaque binary like any other Office document. > [!NOTE] > > Box exposes no API to edit these formats from a structured payload, so Mirage > does not decode them, it hands back exactly what Box stores. For a rich, > editable view of Google-format documents, mount them through > [Google Drive](/python/vfs/gdrive) with Google credentials instead; the > `gws` commands operate on Google file ids and do not apply to Box. For credential setup, see the [Box Setup](/home/setup/box) guide. The TypeScript packages ship the same backend for Node and the browser, see [Box (TypeScript)](/typescript/setup/box). ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.box import BoxConfig, BoxVFS config = BoxConfig( # A Box developer token from the app console (~60-minute lifetime): access_token=os.environ["BOX_DEVELOPER_TOKEN"], # Optional: # root_folder_id="123456789", # mount a sub-folder as the root ) vfs = BoxVFS(config) ws = Workspace({"/box": vfs}, mode=MountMode.WRITE) ``` Box supports three authentication modes: * **Developer token** (`access_token`): quickest to try; expires after \~60 minutes and cannot be refreshed programmatically. * **OAuth2 refresh** (`client_id` + `refresh_token`, optional `client_secret`): Box rotates the refresh token on each refresh; supply `on_refresh_token_rotated` to persist the new one across restarts. * **Client credentials** (`client_id` + `client_secret` + `enterprise_id`): the app authenticates as its own service account; expired tokens are simply re-fetched. The access token is cached in memory and refreshed \~5 minutes before expiry (refresh and client-credentials modes). ### Config Reference | Field | Description | | - | - | | `timeout` default `30` | 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. | | `endpoint` | Base URL that replaces Box's API, upload and OAuth token hosts, such as a test server. Unset uses Box's hosts. | | `client_id` | Box app client ID. Required with `refresh_token` (OAuth) or with `client_secret` and `enterprise_id` (client credentials). | | `client_secret` secret | Box app client secret. Required for client credentials; the OAuth refresh sends it when set, so a PKCE client can omit it. | | `refresh_token` secret | OAuth refresh token; needs `client_id`. Box rotates it on every refresh, so persist the new one with `on_refresh_token_rotated`. | | `enterprise_id` | Box enterprise ID for the client-credentials grant. With `client_id` and `client_secret`, tokens are minted for the app's service account and no refresh token is involved. | | `access_token` secret | Box developer token, used as is with no refresh flow; it expires after about 60 minutes. It wins over every other credential. | | `root_folder_id` | Box folder ID the mount uses as its root, from the folder's web URL (`box.com/folder/<id>`); unlike a path it survives renames and moves. Unset mounts the account root, folder `0`. | | `refresh_fn` secret | Async callable that takes the current refresh token and returns `(access_token, refresh_token, expires_in)`, called instead of Box's token endpoint. Needs `client_id` and `refresh_token`. | | `on_refresh_token_rotated` secret | Async callable given the new refresh token whenever a refresh rotates it, to persist it; the token it replaces stops working after its first use. | Fields marked secret are redacted in snapshots. \* Provide one of: `access_token`; `client_id` + `refresh_token`; or `client_id` + `client_secret` + `enterprise_id`. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Box mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `box`, write | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > <folder>/ # the Box folder hierarchy, mirrored > <name>.boxnote # Box Note: raw ProseMirror-style JSON > <name>.boxcanvas # Box Canvas: raw canvas JSON > <name>.gdoc # Box's Google Workspace files, stored as > <name>.gsheet # Office Open XML (docx, xlsx, pptx): > <name>.gslides # opaque binary > <file> # PDFs, images and the rest: raw bytes > ``` > > * Every item is served as its raw bytes; pipe the JSON ones to `jq`. > * This is a remote mount: prefer targeted reads over full scans. > * Box names folders by numeric id (the root is `0`). The path-to-id > mapping is cached, so a nested directory costs one API call per level > on first access. `ls` the parent before constructing a path. > > #### 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 `box` 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>` | `box`, write | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > <folder>/ # the Box folder hierarchy, mirrored > <name>.boxnote # Box Note: raw ProseMirror-style JSON > <name>.boxcanvas # Box Canvas: raw canvas JSON > <name>.gdoc # Box's Google Workspace files, stored as > <name>.gsheet # Office Open XML (docx, xlsx, pptx): > <name>.gslides # opaque binary > <file> # PDFs, images and the rest: raw bytes > ``` > > - Every item is served as its raw bytes; pipe the JSON ones to `jq`. > - This is a remote mount: prefer targeted reads over full scans. > - Box names folders by numeric id (the root is `0`). The path-to-id > mapping is cached, so a nested directory costs one API call per level > on first access. `ls` the parent before constructing a path. > > ## 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 `box` 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. > ```` ## Mount a subfolder Pass `root_folder_id` to expose a single Box folder as the mount root instead of the whole account. Every command and FUSE/VFS op is scoped to that folder; paths outside it are unreachable. Folder ids are stable across renames and moves, and are visible in the Box web URL (`app.box.com/folder/<id>`), so an id-based mount survives reorganization that a path prefix would not. ```python theme={null} config = BoxConfig( access_token=os.environ["BOX_DEVELOPER_TOKEN"], root_folder_id="123456789", ) ``` ## Cache The Box VFS caches directory listings via `IndexCacheStore` to hold the path → id mapping and reduce repeated API calls during traversal; with no `index:` configured, listings live for the mount's `ttl` (600 s by default), at most 24 hours; a configured `index:` uses its own `ttl`, still capped by the mount's `ttl:`. File reads go through the standard read cache (`caches_reads = True`). Writes invalidate the affected listings so subsequent reads see the new state. ## Writes A write records the `sha1` its upload reply names, so a `fresh` read right after a `tee` or `sed -i` downloads nothing. ## Conditional writes A rewrite that observes a missing file requires atomic create-only support, which this backend does not currently enable. Appending to a missing file therefore returns an unsupported-operation error under either write policy. An intentional write with `>` can create the file, and subsequent appends to that existing file retain the selected policy. A Box mount accepts `write: conditional`. A write or a file delete compares the `sha1` mirage holds with the one the folder listing it walks anyway shows, and refuses a file changed since it was read before sending anything; the request then carries the file's `etag` as `If-Match`, so Box refuses (412) a change that lands in between. A conditional write costs no request more than a plain one. `rm -r` walks the folder file by file, and a `mv` within the mount is Box's own move, which is not refused when its source changed (a `mv` to another mount is a copy and a conditioned delete, so there a changed source stays and `mv` reports the failed removal). ## Reads under `fresh` A Box mount accepts `read: fresh`. The token is the file's `sha1`, which a folder listing and `GET /files/{id}` both carry; a download names no version, so a whole read stamps the listed `sha1` only when the downloaded bytes hash to it, and a ranged read stamps nothing. On a `write: conditional` mount a whole read stamps the `sha1` of the bytes it downloaded, so a listing another client has since outdated cannot leave the next write without the version the agent read. `modified_at` is never the token: two same-size edits in one second share it. Checking a cached file costs one request, `GET /files/{id}` by the id the mount last listed, while the mount still holds that file's listing row. The answer is trusted only when Box places the same active file at the same path from the mount root; a file that was moved, renamed, trashed or recreated falls back to listing each folder from the mount root, one listing per level (up to two per level when the file is gone). When that fallback confirms byte-identical content, the built-in RAM and Redis indexes retain the newly resolved file row if the original hint is still current. A later check then uses the recovered id without refreshing the parent listing. Custom indexes must implement `replace_if_unchanged` to retain this row; otherwise later checks repeat the fallback walk. A persistent 403 still requires the failed point request and a listing walk on each check. Any stale, unknown or gone verdict on the mount drops its cached listings, so the checks after one walk until a cold read or an `ls` lists the folders again. A file Box reports without a `sha1` cannot be verified: each fresh read of it downloads it again and drops the mount's cached listings. A folder's `etag` does not move when its children change, so under `fresh` listings are re-fetched once per command. Repeated uses within that command share the result; outside commands, the existing one-second listing trust window applies. Before fetching a nested listing, mirage resolves its folder through current parent listings up to the configured mount root. A folder moved away and replaced under the same name is therefore resolved to the replacement on the next fresh command. This costs one listing per ancestor level; a warm file check still uses one metadata request. ## Integration What Box answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Box | | - | - | | `grep -r`, `rg` | Box search, for whole words. It can miss Office files, PDFs, archives, the end of large files, words Box splits differently (`foo.bar`) and recent writes. | | `sha1sum` | The SHA-1 Box keeps, asked live | `grep -rw` and `rg -w` read only the files Box search names. Every file is read when the search fails, reaches its 10,000-match limit or finds nothing, or when the searched path is not a folder. [Search](/home/integration/search) lists how each option uses the search. `walk_limit: -1` in the mount's `"@all"` [command limit](/home/core/output-limits) reads every file instead, since Box searches the text it extracted, not the bytes `grep` reads, and indexes a write some time after it lands. A file that holds the word can be left out: an office file, PDF or archive, the end of a large file, a word Box splits differently (`foo.bar`), or a recent write. ## Example ```python theme={null} import asyncio import os from mirage import MountMode, Workspace from mirage.vfs.box import BoxConfig, BoxVFS config = BoxConfig(access_token=os.environ["BOX_DEVELOPER_TOKEN"]) vfs = BoxVFS(config) async def main() -> None: ws = Workspace({"/box": vfs}, mode=MountMode.WRITE) r = await ws.shell("ls /box/") print(await r.stdout_str()) r = await ws.shell("grep -rl report /box/docs/") print(await r.stdout_str()) # Plain text from a Box Note: # A Box Note comes back as raw ProseMirror JSON: r = await ws.shell("cat /box/notes/standup.boxnote | jq .") print(await r.stdout_str()) await ws.close() asyncio.run(main()) ``` # Ceph (Rados Gateway) Source: https://docs.mirage.strukto.ai/python/vfs/ceph Mount a self-hosted Ceph Rados Gateway bucket as a virtual filesystem. The Ceph VFS is a thin wrapper over the [S3 VFS](/python/vfs/s3). It maps a `CephConfig` to an `S3Config` and reuses the exact same backend, commands, and behavior as S3, it just points at your Ceph Rados Gateway `endpoint_url` and uses path-style addressing by default. Ceph RGW is self-hosted, so `endpoint_url` is **required** (there is no region-derived host). Uses aioboto3 against the gateway's S3-compatible API. Install the extra: ```bash theme={null} pip install "mirage-ai[s3]" ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.ceph import CephConfig, CephVFS config = CephConfig( bucket=os.environ["CEPH_BUCKET"], endpoint_url=os.environ["CEPH_ENDPOINT_URL"], access_key_id=os.environ["CEPH_ACCESS_KEY_ID"], secret_access_key=os.environ["CEPH_SECRET_ACCESS_KEY"], # Optional: # region="us-east-1", # default # path_style=True, # default # timeout=30, # proxy="http://proxy:8080", ) vfs = CephVFS(config) ws = Workspace({"/ceph": vfs}, mode=MountMode.READ) ``` Both `READ` and `WRITE` modes are supported. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `bucket` required | Name of the bucket to mount. | | `region` default `'us-east-1'` | Region requests are signed for; the gateway's endpoint does not depend on it. | | `endpoint_url` required | URL of the self-hosted S3 gateway, such as `http://localhost:9000`. | | `access_key_id` secret | Access key ID; set it with `secret_access_key`. Unset uses the AWS credential chain. | | `secret_access_key` secret | Secret access key paired with `access_key_id`. | | `session_token` secret | Session token for temporary credentials, sent with the access key pair. | | `aws_profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `path_style` default `True` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `key_prefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | Fields marked secret are redacted in snapshots. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Ceph (Rados Gateway) mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.vfs.ceph import CephConfig, CephVFS load_dotenv(".env.development") config = CephConfig( bucket=os.environ["CEPH_BUCKET"], endpoint_url=os.environ["CEPH_ENDPOINT_URL"], access_key_id=os.environ["CEPH_ACCESS_KEY_ID"], secret_access_key=os.environ["CEPH_SECRET_ACCESS_KEY"], ) vfs = CephVFS(config) async def main() -> None: ws = Workspace({"/ceph/": vfs}, mode=MountMode.READ) r = await ws.shell("ls /ceph/") print(await r.stdout_str()) r = await ws.shell("find /ceph/ -name '*.json'") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Notes * Ceph registers under its own `VFSName` and routes through the same `core/s3` implementation, so the full S3 shell-command set applies. See the [S3 VFS](/python/vfs/s3) for the complete command reference, range reads, streaming, and the index cache fast path. * For credential setup, see [Ceph Setup](/home/setup/ceph). # Chroma Source: https://docs.mirage.strukto.ai/python/vfs/chroma Mount a ChromaDB collection as a read-only virtual filesystem. The Chroma VFS exposes an existing ChromaDB collection as text files mounted at a prefix such as `/knowledge/`. It is useful when you already have a chunked knowledge base in Chroma and want agents to use normal filesystem commands like `ls`, `cat`, `grep` and `find`, and to rank chunks by meaning with the [`search` CLI](/python/cli/search). For collection setup, see [Chroma Setup](/home/setup/chroma). Install the extra: ```bash theme={null} pip install "mirage-ai[chroma]" ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.chroma import ChromaConfig, ChromaVFS config = ChromaConfig( host=os.environ.get("CHROMA_HOST", "localhost"), port=int(os.environ.get("CHROMA_PORT", "8000")), ssl=os.environ.get("CHROMA_SSL", "false").lower() == "true", collection_name=os.environ["CHROMA_COLLECTION"], slug_field=os.environ.get("CHROMA_SLUG_FIELD", "page_slug"), chunk_index_field=os.environ.get("CHROMA_CHUNK_INDEX_FIELD", "chunk_index"), ) vfs = ChromaVFS(config=config) ws = Workspace({"/knowledge/": vfs}, mode=MountMode.READ) ``` The VFS is read-only. A snapshot keeps its config, and a load needs the mount handed back through `mounts=`; it has no drift detection, so a restored mount reads current content. | Field | Description | | - | - | | `host` default `'localhost'` | Host name of the Chroma HTTP server. | | `port` default `8000` | Port of the Chroma HTTP server. | | `ssl` default `False` | Connect over HTTPS instead of HTTP. | | `collection_name` required | Name of the existing Chroma collection to mount. | | `slug_field` default `'page_slug'` | Chunk metadata key that holds the path of the file a chunk belongs to, relative to the mount root (`guides/quickstart.md`). | | `chunk_index_field` default `'chunk_index'` | Chunk metadata key whose integer orders a file's chunks; a chunk without one sorts as `0`. | ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Chroma mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `chroma`, read | > > #### VFS Layout > > ##### `/<path>` > > * One ChromaDB collection, mounted read only. > * Paths are document slugs from the collection's path tree. > * Inspect documents with `cat`, `head`, `tail`, `ls`, `find`, `tree` and > `grep`. Writes are not supported. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `chroma` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `chroma`, read | > > ## VFS Layout > > ### `/<path>` > > - One ChromaDB collection, mounted read only. > - Paths are document slugs from the collection's path tree. > - Inspect documents with `cat`, `head`, `tail`, `ls`, `find`, `tree` and > `grep`. Writes are not supported. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `chroma` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ``` Chroma paths come from the path tree document stored in the collection with ID `__path_tree__`. The document body must be a JSON object whose keys are virtual file paths below the mount prefix. ```json theme={null} { "README.md": { "size": 1024 }, "guides/quickstart.md": { "size": 4096, "updated_at": "2026-01-03T00:00:00Z" } } ``` Mounted at `/knowledge/`, this becomes: ```text theme={null} /knowledge/ README.md guides/ quickstart.md ``` Mirage infers folders from path segments and stores the tree in the index cache. The `size`, `created_at`, and `updated_at` metadata values are used by tree and listing operations when present. ## Reading Documents Each file is assembled from Chroma chunk documents whose metadata slug matches the path. Chunks are sorted by the configured chunk index field and joined with a single newline. ```bash theme={null} ls /knowledge/ tree /knowledge/ find /knowledge/ -type f cat /knowledge/guides/quickstart.md head -n 20 /knowledge/guides/quickstart.md tail -n 20 /knowledge/guides/quickstart.md grep -rin "billing" /knowledge/ ``` ## Exact Search with Grep `grep -r` and `rg` read only the pages with a chunk holding the text, which Chroma's `$contains` answers, then match each page as grep does. A page is its chunks joined by line breaks, so no match can span two chunks and the answer is exact. `$contains` matches case, so `-i` reads every page. ```bash theme={null} grep -r "refund" /knowledge/policies/ grep -ri "quickstart" /knowledge/ grep -n "API key" /knowledge/guides/quickstart.md ``` ## Vector Search The [`search` CLI](/python/cli/search) asks Chroma's vector query API. Use it when semantic similarity matters more than exact text matching. Register it on the workspace: ```python theme={null} from mirage.commands.cli.builtin.search import SEARCH ws.register_cli("search", SEARCH) ``` ```bash theme={null} search "how do I get started" /knowledge/ search --top-k 5 "billing policy" /knowledge/policies/ search --top-k 3 "API authentication" /knowledge/guides/quickstart.md search --threshold 0.8 "billing policy" /knowledge/ ``` The score is 1 minus Chroma's distance, and `--threshold` keeps the hits that reach it. `--top-k` defaults to 10. `--method` takes only `semantic`. Each hit prints its page and score, then the chunk: ```text theme={null} /knowledge/guides/quickstart.md:0.82 Use an API key to authenticate requests. ``` ## Cache The VFS uses Mirage's index cache for the virtual tree. The first directory listing or path resolution fetches `__path_tree__`; later `ls`, `find`, `tree`, and path resolution reuse the cached tree until the index cache expires or the workspace is recreated. File content is still read from Chroma when commands materialize document text. ## Integration What Chroma answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Chroma | | - | - | | `grep -r`, `rg` | Chroma `$contains` over the chunks, for any text; `-i` reads every page. It misses nothing. | ## Examples Runnable examples live under `examples/python/vfs/chroma/`: * [`chroma.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/vfs/chroma/chroma.py) — command workflow with `ls`, `tree`, `find`, `cat`, `head`, `tail`, `grep`, and `search`. * [`chroma_vfs.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/vfs/chroma/chroma_vfs.py) — in-process VFS workflow with `os.listdir()`, `open()`, and `os.path.*`. ## Shell Commands | Command | Notes | | - | - | | `ls` | List folders and files from the path tree | | `tree` | Print the mounted path tree | | `find` | Search the virtual tree by name, type, depth, and size | | `cat` | Read full file text assembled from Chroma chunks | | `head` / `tail` | Read the first or last lines/bytes | | `grep` | Exact or regex matching over assembled file text | # Databricks Volume Source: https://docs.mirage.strukto.ai/python/vfs/databricks_volume Mount a Databricks Unity Catalog volume as a filesystem. `DatabricksVolumeVFS` exposes files from a Unity Catalog volume through Mirage's standard filesystem interface. Agents can list, stat, read, stream, glob, and write files under the configured volume root. For auth and environment setup, see [Databricks Volume Setup](/home/setup/databricks). ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.databricks_volume import ( DatabricksVolumeConfig, DatabricksVolumeVFS, ) vfs = DatabricksVolumeVFS(DatabricksVolumeConfig( catalog="main", schema="default", volume="agent_files", root_path="/reports", host=os.environ["DATABRICKS_HOST"], token=os.environ["DATABRICKS_TOKEN"], )) ws = Workspace({"/dbx": vfs}, mode=MountMode.READ) ``` | Field | Description | | - | - | | `timeout` default `30` | 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. | | `catalog` required | Unity Catalog catalog name; one path segment, no `/`. | | `schema` required | Unity Catalog schema name, `schema` in a config; one path segment, no `/`. | | `volume` required | Unity Catalog volume name; one path segment, no `/`. | | `root_path` default `'/'` | Subdirectory inside the volume that becomes the mount root; `..` segments are refused. | | `host` required | Workspace origin, `http://` or `https://`, with no path, query, fragment or credentials. | | `token` required, secret | Bearer token as a string, or a function, synchronous or asynchronous, that returns one for each request. | Fields marked secret are redacted in snapshots. ## Mount mode `read`, `write` or `exec`. Use `exec` if `python3` or `js` should run scripts from the mount. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Databricks Volume mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` Mirage maps the configured mount prefix onto the configured volume subtree. Given: ```python theme={null} DatabricksVolumeConfig( catalog="main", schema="default", volume="agent_files", root_path="/reports/2026", host=os.environ["DATABRICKS_HOST"], token=os.environ["DATABRICKS_TOKEN"], ) ``` and mount prefix `/dbx/`, the volume path: ```text theme={null} /Volumes/main/default/agent_files/reports/2026/q1/summary.md ``` appears in Mirage as: ```text theme={null} /dbx/q1/summary.md ``` `root_path` is normalized before use, and Mirage rejects any virtual path that would escape above that configured subtree. ## Supported operations Reads: `readdir`, `stat`, `exists`, `read` (streamed whole or a byte range), and glob resolution. Writes: `write`, `create`, `mkdir`, `rmdir`, `unlink`, recursive `rm`, `cp`, and `mv`. `mv` and `cp` download and upload the file. These operations are not atomic because the Files API has no server-side rename. A directory `mv` removes only what it copied: a file or directory written into the source after the copy listed its directory stays there, and `mv` fails with `Directory not empty`. ## Shell Commands The Databricks Volume VFS supports shell commands that operate on real file content. Reads use the Files API with range requests, so commands like `head -c BYTES` avoid downloading the whole object. The supported set is scoped to commands that work over the volume API (no compression, encoding, or local-only utilities). ### Read Commands | Command | Notes | | - | - | | `cat` | Read file content | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search (file or directory level) | | `jq` | Query JSON fields | | `wc` | Line/word/byte counts | | `stat` | File metadata (name, size, type, modified) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `nl` | Number lines | ### Text Processing | Command | Notes | | - | - | | `awk` | Pattern scanning and processing | | `sed` | Stream editor | | `tr` | Translate or delete characters | | `sort` | Sort lines | | `uniq` | Remove duplicate lines | | `cut` | Extract fields/columns | | `diff` | Compare files line by line | ### File Operations | Command | Notes | | - | - | | `cp` | Copy files (non-atomic download + upload) | | `mv` | Move/rename files (non-atomic download + upload) | | `rm` | Remove files (recursive for directories) | | `mkdir` | Create directories | | `touch` | Create empty file or update timestamp | ### Path Utilities | Command | Notes | | - | - | | `ls` | List directory contents | ## Rotating tokens Pass a callback as `token` when your application refreshes access tokens: ```python theme={null} def current_token() -> str: return os.environ["DATABRICKS_TOKEN"] config = DatabricksVolumeConfig( catalog="main", schema="default", volume="agent_files", host=os.environ["DATABRICKS_HOST"], token=current_token, ) vfs = DatabricksVolumeVFS(config) ws = Workspace({"/dbx/": vfs}, mode=MountMode.READ) ``` This callback reads the application's current token. Replace its body with your credential broker or token store. The callback takes no arguments and returns `str` or `SecretStr`. It can be synchronous or asynchronous. Mirage runs a synchronous callback off the event loop and awaits any returned awaitable. Mirage resolves the callback before each HTTP request, including each directory page. A deferred read stream resolves its token when the stream opens. Cached reads, construction, and snapshots do not invoke the callback. Tokens must be nonblank and contain no carriage return or newline. Your callback owns token refresh, caching, and coordination between concurrent requests. Mirage propagates provider errors and authentication failures. It does not replay a request after a 401 or fall back to profiles or default credentials. Keep each VFS and workspace bound to one principal and permission scope. Isolate file caches, indexes, and external cache prefixes across identities. If the principal or permission scope changes, rebuild the workspace or invalidate its caches. Token rotation for the same principal and scope can keep the existing VFS. ## Snapshot behavior Mirage redacts static tokens and token callbacks in VFS snapshots. Restore the mount through `mounts=` when loading the workspace. ## Databricks Apps Keep Mirage in-process and supply the workspace host and token explicitly. Your application's OAuth or SDK integration can supply a token callback. This does not require FUSE. The agent accesses the mounted workspace through Mirage's backend adapters or `Workspace.shell(...)`. ## Example ```python theme={null} import asyncio import os from mirage import MountMode, Workspace from mirage.vfs.databricks_volume import ( DatabricksVolumeConfig, DatabricksVolumeVFS, ) vfs = DatabricksVolumeVFS(DatabricksVolumeConfig( catalog="main", schema="default", volume="agent_files", root_path="/reports", host=os.environ["DATABRICKS_HOST"], token=os.environ["DATABRICKS_TOKEN"], )) async def main() -> None: ws = Workspace({"/dbx/": vfs}, mode=MountMode.READ) r = await ws.shell("ls /dbx/") print(await r.stdout_str()) r = await ws.shell("find /dbx/ -name '*.md'") print(await r.stdout_str()) r = await ws.shell('head -n 20 "/dbx/q1/summary.md"') print(await r.stdout_str()) r = await ws.shell('stat "/dbx/q1/summary.md"') print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` See: * `examples/python/vfs/databricks_volume/databricks_volume.py` * `examples/python/agents/langchain/databricks_volume_deepagent.py` ## Use Cases * **Agents in Databricks Apps**: mount a Unity Catalog volume in-process so an agent can read and write governed files without FUSE or hardcoded credentials. * **Reading governed datasets**: expose a reports or dataset subtree through `root_path` and query it with shell commands. * **Sandboxed volume access**: scope an agent to a single volume (and optional `root_path`) so it cannot read or write outside that subtree. * **Writing agent outputs back**: persist generated files to the volume with `write`, `cp`, and `mv`. # Dify Source: https://docs.mirage.strukto.ai/python/vfs/dify Mount a Dify Knowledge dataset as a read-only virtual filesystem. The Dify VFS exposes completed Dify Knowledge documents as text files mounted at a prefix such as `/knowledge/`. Each file is assembled from the document's completed, enabled segments. For API key setup, see [Dify Setup](/home/setup/dify). ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.dify import DifyConfig, DifyVFS config = DifyConfig( api_key=os.environ["DIFY_API_KEY"], base_url=os.environ.get("DIFY_BASE_URL", "https://api.dify.ai/v1"), dataset_id=os.environ["DIFY_DATASET_ID"], slug_metadata_name=os.environ.get("DIFY_SLUG_METADATA_NAME", "slug"), ) vfs = DifyVFS(config=config) ws = Workspace({"/knowledge/": vfs}, mode=MountMode.READ) ``` The VFS is read-only. A snapshot keeps its config, and a load needs the mount handed back through `mounts=`; it has no drift detection, so restored cache entries are served as saved and other reads reach the live backend. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `api_key` required, secret | Dify Knowledge API key, sent as `Authorization: Bearer`. | | `base_url` required | Dify API root, such as `https://api.dify.ai/v1`. | | `dataset_id` required | ID of the Knowledge dataset the mount shows. | | `slug_metadata_name` default `'slug'` | Document metadata field whose value is the document's path in the mount. A document without it is mounted under its document name. | | `max_concurrency` default `10` | The most Dify API requests in flight at once. | | `retry_attempts` default `4` | Attempts per request, the first included. A 429, a 5xx or a transport error is retried. | | `retry_max_delay` default `30.0` | Longest wait in seconds before a retry, whether from backoff or `Retry-After`. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Dify mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `dify`, read | > > #### VFS Layout > > ##### `/<path>` > > * A Dify knowledge base, mounted read only. > * Every file is plain text assembled from the document's Dify segments, > whatever its original extension. > * `cat`, `head`, `tail`, `grep`, `find`, `ls` and `wc` work on these > files. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `dify`, read | > > ## VFS Layout > > ### `/<path>` > > - A Dify knowledge base, mounted read only. > - Every file is plain text assembled from the document's Dify segments, > whatever its original extension. > - `cat`, `head`, `tail`, `grep`, `find`, `ls` and `wc` work on these > files. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ``` Dify documents are mapped to paths using the configured slug metadata field. The default metadata field name is `slug`. If a document has no configured slug metadata, Mirage falls back to the Dify document name. ```text theme={null} /knowledge/ README.md guides/ quickstart.md api.md policies/ support.md ``` Example mapping: | Dify document | Metadata | Mirage path | | - | - | - | | `Quickstart` | `slug=guides/quickstart.md` | `/knowledge/guides/quickstart.md` | | `README.md` | no slug | `/knowledge/README.md` | ### Creating Slug Metadata in Dify In the Dify Knowledge UI, open a document and add a metadata item whose name matches `slug_metadata_name`. The default name is `slug`. ```text theme={null} name: slug value: guides/quickstart.md ``` For a custom Dify metadata name: ```python theme={null} config = DifyConfig( api_key=os.environ["DIFY_API_KEY"], base_url=os.environ.get("DIFY_BASE_URL", "https://api.dify.ai/v1"), dataset_id=os.environ["DIFY_DATASET_ID"], slug_metadata_name="path", ) ``` Then use: ```text theme={null} name: path value: guides/quickstart.md ``` Mirage reads `doc_metadata` from Dify and uses this value as the document's virtual path below the mount prefix. Use these rules for slug metadata values: * Use `/` to create folders. * Do not use empty segments, `.`, or `..`. * Keep each slug metadata value unique across the dataset. * Do not use a path that is also needed as a folder. For example, `guides` and `guides/quickstart.md` cannot both be document paths. Only visible documents are included: * `enabled` is `true` * `indexing_status` is `completed` * `archived` is `false` ## Reading Documents `cat`, `head`, `tail`, and `grep` read Dify document segments. Segment content is joined with a single newline between chunks. ```bash theme={null} ls /knowledge/ find /knowledge/ -type f cat /knowledge/guides/quickstart.md head -n 20 /knowledge/guides/quickstart.md grep -i "billing" /knowledge/guides/quickstart.md wc /knowledge/guides/quickstart.md ``` ## Search The [`search` CLI](/python/cli/search) asks Dify's dataset retrieval API. Use it when meaning matters more than exact text matching. Register it on the workspace: ```python theme={null} from mirage.commands.cli.builtin.search import SEARCH ws.register_cli("search", SEARCH) ``` ```bash theme={null} search "how do I reset my password" /knowledge/ search --method hybrid --top-k 5 "billing policy" /knowledge/policies/ search --method semantic --threshold 0.4 "quickstart" /knowledge/guides/*.md ``` Supported methods: | Method | Dify retrieval mode | | - | - | | `semantic` | semantic search | | `fulltext` | full text search | | `hybrid` | hybrid search | | `keyword` | keyword search | `--top-k` defaults to 10 and is capped at `100`. `--threshold` must be between `0` and `1`; another value, or another method, exits 1 before Dify ranks anything. Results are emitted one retrieval hit per block: ```text theme={null} /knowledge/policies/refunds:0.82 Refunds are allowed within 30 days. ``` Mirage uses the configured slug metadata field to derive the path, and falls back to the Dify document name when that metadata is missing. Multiple hits from the same document remain separate records. Scoped search uses Dify metadata filtering. Documents with the configured slug metadata field are filtered by that field; name-based documents are filtered by `document_name`, which requires Dify Built-in Fields to be enabled in dataset metadata. ### Scoped Search Requirements Mirage converts a scoped search path into Dify metadata filters: | Mirage target | Dify metadata filter | | - | - | | Document with configured slug metadata | `<slug_metadata_name> in [...]` | | Document without configured slug metadata | `document_name in [...]` | | Folder or glob | `<slug_metadata_name>` / `document_name` filters for all matched files | To make scoped search reliable: 1. Add the configured slug metadata field to every document. 2. Enable Dify **Built-in Fields** in the dataset metadata settings. 3. Ensure `document_name` is available if you rely on name-based paths. If Built-in Fields are disabled, scoped search against documents without the configured slug metadata field may return empty results even though `cat`, `grep`, and `find` can still see the same file. ## Cache The VFS uses Mirage's index cache for the virtual tree. Directory listings and path resolution reuse the cached document tree until the index expires or the workspace is recreated. If documents are edited directly in Dify, repeated operations can temporarily see cached paths and metadata. Document content is still read from Dify when commands materialize file data. ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.commands.cli.builtin.search import SEARCH from mirage.vfs.dify import DifyConfig, DifyVFS load_dotenv(".env.development") config = DifyConfig( api_key=os.environ["DIFY_API_KEY"], base_url=os.environ.get("DIFY_BASE_URL", "https://api.dify.ai/v1"), dataset_id=os.environ["DIFY_DATASET_ID"], slug_metadata_name=os.environ.get("DIFY_SLUG_METADATA_NAME", "slug"), ) vfs = DifyVFS(config=config) async def main() -> None: ws = Workspace({"/knowledge/": vfs}, mode=MountMode.READ) ws.register_cli("search", SEARCH) r = await ws.shell("ls /knowledge/") print(await r.stdout_str()) r = await ws.shell("find /knowledge/ -type f | head -n 10") print(await r.stdout_str()) r = await ws.shell('search --method hybrid --top-k 5 "getting started" /knowledge/') print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` A runnable version is available at `examples/python/vfs/dify/dify.py`. ## Shell Commands | Command | Notes | | - | - | | `ls` | List folders and documents | | `cat` | Read full document text from completed segments | | `head` / `tail` | Read the first or last lines/bytes | | `grep` | Exact or regex matching over streamed document text | | `find` | Search the virtual tree by name, type, depth, and size | | `wc` | Count lines, words, bytes, characters, and max line length | # DigitalOcean Spaces Source: https://docs.mirage.strukto.ai/python/vfs/digitalocean Mount a DigitalOcean Spaces bucket via its S3-compatible API as a virtual filesystem. The DigitalOcean VFS is a thin wrapper over the [S3 VFS](/python/vfs/s3). It maps a `DigitalOceanConfig` to an `S3Config` and reuses the exact same backend, commands, and behavior as S3, it just derives the right Spaces endpoint from `region`. Uses aioboto3 against DigitalOcean Spaces' S3-compatible API. The endpoint is computed from `region` as `<region>.digitaloceanspaces.com` (e.g. `nyc3.digitaloceanspaces.com`). Pass `endpoint_url` to override. Install the extra: ```bash theme={null} pip install "mirage-ai[s3]" ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.digitalocean import DigitalOceanConfig, DigitalOceanVFS config = DigitalOceanConfig( bucket=os.environ["DO_SPACE"], region=os.environ.get("DO_REGION", "nyc3"), access_key_id=os.environ["DO_ACCESS_KEY_ID"], secret_access_key=os.environ["DO_SECRET_ACCESS_KEY"], # Optional: # endpoint_url="https://nyc3.digitaloceanspaces.com", # timeout=30, # proxy="http://proxy:8080", ) vfs = DigitalOceanVFS(config) ws = Workspace({"/data": vfs}, mode=MountMode.READ) ``` Both `READ` and `WRITE` modes are supported. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `bucket` required | Name of the bucket to mount. | | `region` required | Provider region every request is signed for. Most providers also build their endpoint URL from it unless `endpoint_url` is set. | | `endpoint_url` | Endpoint URL that replaces the one the provider derives. | | `access_key_id` secret | Access key ID; set it with `secret_access_key`. Unset uses the AWS credential chain. | | `secret_access_key` secret | Secret access key paired with `access_key_id`. | | `session_token` secret | Session token for temporary credentials, sent with the access key pair. | | `aws_profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `path_style` default `False` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `key_prefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | Fields marked secret are redacted in snapshots. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with DigitalOcean Spaces mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.vfs.digitalocean import DigitalOceanConfig, DigitalOceanVFS load_dotenv(".env.development") config = DigitalOceanConfig( bucket=os.environ["DO_SPACE"], region=os.environ.get("DO_REGION", "nyc3"), access_key_id=os.environ["DO_ACCESS_KEY_ID"], secret_access_key=os.environ["DO_SECRET_ACCESS_KEY"], ) vfs = DigitalOceanVFS(config) async def main() -> None: ws = Workspace({"/data/": vfs}, mode=MountMode.READ) r = await ws.shell("ls /data/") print(await r.stdout_str()) r = await ws.shell("tree /data/") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Notes * DigitalOcean registers under its own `VFSName` and routes through the same `core/s3` implementation, so the full S3 shell-command set applies. See the [S3 VFS](/python/vfs/s3) for the complete command reference, range reads, streaming, and the index cache fast path. * For credential setup, see [DigitalOcean Setup](/home/setup/digitalocean). # Discord Source: https://docs.mirage.strukto.ai/python/vfs/discord Mount Discord guilds, channels, messages, attachments, and members as a Mirage virtual filesystem for Python agents. The Discord VFS exposes guild, channel, and member data as a virtual filesystem mounted at some prefix such as `/discord/`. For token setup, see [Discord Setup](/home/setup/discord). ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.discord import DiscordConfig, DiscordVFS config = DiscordConfig(token=os.environ["DISCORD_BOT_TOKEN"]) vfs = DiscordVFS(config=config) ws = Workspace({"/discord": vfs}, mode=MountMode.READ) ``` | Field | Description | | - | - | | `start_time` | Start of the mount's time scope, inclusive: an RFC 3339 timestamp with an explicit timezone and at most millisecond precision. Unset leaves the start open. | | `end_time` | End of the mount's time scope, exclusive, in the same format as `start_time`, which it must follow. Unset leaves the end open. | | `timeout` default `30` | 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. | | `token` required, secret | Discord bot token, sent as `Authorization: Bot <token>`. | | `base_url` | Discord API root. Unset uses `https://discord.com/api/v10`; set it to point at a fake or proxy. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Discord mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `discord`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > <guild-name>__<guild-id>/ > channels/ > <channel-name>__<channel-id>/ > <yyyy-mm-dd>/ > chat.jsonl # messages for that date > files/ # attachments shared that day > <name>__<att-id>.<ext> # cat downloads it from Discord's CDN > members/ > <username>__<user-id>.json # member profile > ``` > > * A guild, channel, member or attachment name is `<display-name>__<id>`. > The display name keeps Discord's spelling (spaces, apostrophes, emoji); > only `/` becomes `∕` (U+2215). `ls` the parent first to find exact > names, and quote a name that has spaces. > * Messages are JSONL; use `jq` for fields such as `.content`, > `.author.username` and `.attachments`. A day's `files/` may be empty. > * Without `start_time`/`end_time`, a channel lists the latest 30 days up > to its newest message; a date glob finds earlier days. > * With `start_time`/`end_time`, listings cover that scope; messages and > attachments outside it are absent, direct paths included. Users and > channel metadata stay available as context. > * `grep` and `rg` read the files they reach, so `grep` needs `-r` for a > directory. Under a channel that reads every listed day, attachments > included: they download from the CDN, and binary ones such as JPG or > PDF produce noise. > > Time scope: `start_time=unbounded` (inclusive), `end_time=unbounded` (exclusive). Explicit paths and globs cannot escape this scope. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `discord`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > <guild-name>__<guild-id>/ > channels/ > <channel-name>__<channel-id>/ > <yyyy-mm-dd>/ > chat.jsonl # messages for that date > files/ # attachments shared that day > <name>__<att-id>.<ext> # cat downloads it from Discord's CDN > members/ > <username>__<user-id>.json # member profile > ``` > > - A guild, channel, member or attachment name is `<display-name>__<id>`. > The display name keeps Discord's spelling (spaces, apostrophes, emoji); > only `/` becomes `∕` (U+2215). `ls` the parent first to find exact > names, and quote a name that has spaces. > - Messages are JSONL; use `jq` for fields such as `.content`, > `.author.username` and `.attachments`. A day's `files/` may be empty. > - Without `start_time`/`end_time`, a channel lists the latest 30 days up > to its newest message; a date glob finds earlier days. > - With `start_time`/`end_time`, listings cover that scope; messages and > attachments outside it are absent, direct paths included. Users and > channel metadata stay available as context. > - `grep` and `rg` read the files they reach, so `grep` needs `-r` for a > directory. Under a channel that reads every listed day, attachments > included: they download from the CDN, and binary ones such as JPG or > PDF produce noise. > > Time scope: `start_time=unbounded` (inclusive), `end_time=unbounded` (exclusive). Explicit paths and globs cannot escape this scope. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ```` Display names keep their original spelling from Discord (spaces, apostrophes, emoji are all preserved). Only `/` is replaced with `∕` (U+2215) so it cannot collide with a directory boundary. The Discord snowflake ID is appended after `__` (double underscore) on guild, channel, member, and attachment names so VFS specific commands can extract it without an extra lookup, and so two same named entities never collide. Quote names containing spaces in shell commands. `stat` also exposes the ID in the `extra` dict (see [Finding IDs](#finding-ids)). ### Guilds The root lists one directory per guild the bot has access to. ### Channels `/discord/<guild>/channels/` lists text channels (types 0, 5, 15). Each channel directory contains day-partitioned **directories** for the 30 days leading up to the channel's last message. Each day directory holds: * `chat.jsonl`, the day's messages (one JSON object per line). * `files/`, attachments posted on that day. Each blob is named `<stem>__<attachment-id>.<ext>`, where the stem keeps the original filename's spelling (only `/` is replaced). The ID suffix keeps the filename collision-free. `cat`'ing a blob downloads it from the Discord CDN. The date range is derived from `last_message_id` on the channel object, so inactive channels show dates around their last activity, not today. Soft errors (403 missing permissions, 404 unknown channel, 429 rate limit) on a single day are swallowed so listings, `find`, and `grep` keep working across the rest of the tree. ### Members `/discord/<guild>/members/` lists one `.json` file per member. Reading a member file returns the full member payload from the Discord API. ## Smart Commands ### grep / rg `grep -r` and `rg` read every day's `chat.jsonl` under the directory they walk, so a channel or guild costs one history fetch per day. Name a day directory or a date glob to search a large channel. Discord's own search is not used: a reply carries the message it answers (`referenced_message`), which that search does not tie to the reply's day, so it cannot say which days hold a word. ### head / tail `head` and `tail` on file-level paths use the Discord messages API directly (`GET /channels/{id}/messages`) instead of downloading the full day's history. ## Cache The Discord VFS uses `IndexCacheStore` (same as S3, disk and GitHub). Index entries store guild IDs, channel IDs, and `last_message_id` for date range computation. File bytes go through the workspace file cache. ## Integration What Discord answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Discord | | - | - | | `tail -f` | Each new message as it is posted | ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.vfs.discord import DiscordConfig, DiscordVFS load_dotenv(".env.development") config = DiscordConfig(token=os.environ["DISCORD_BOT_TOKEN"]) vfs = DiscordVFS(config=config) async def main(): ws = Workspace({"/discord": vfs}, mode=MountMode.READ) # List guilds r = await ws.shell("ls /discord/") print(await r.stdout_str()) guild = (await r.stdout_str()).strip().splitlines()[0] # List channels r = await ws.shell(f'ls "/discord/{guild}/channels/"') print(await r.stdout_str()) ch = (await r.stdout_str()).strip().splitlines()[0] base = f"/discord/{guild}/channels/{ch}" # Discover an available day, then read a few messages r = await ws.shell(f'ls "{base}/" | tail -n 1') day = (await r.stdout_str()).strip() r = await ws.shell(f'head -n 3 "{base}/{day}/chat.jsonl"') print(await r.stdout_str()) # Extract usernames with jq r = await ws.shell( f'jq -r ".author.username" "{base}/{day}/chat.jsonl"') print(await r.stdout_str()) # Count messages per user r = await ws.shell( f'cat "{base}/{day}/chat.jsonl"' ' | jq -r ".author.username" | sort | uniq -c') print(await r.stdout_str()) # List attachments for a day r = await ws.shell(f'ls "{base}/{day}/files/"') print(await r.stdout_str()) # Search every day of the channel r = await ws.shell(f'grep -r hello "{base}/"') print(await r.stdout_str()) # Search across the guild r = await ws.shell(f'grep -r hello "/discord/{guild}/"') print(await r.stdout_str()) # Navigate with cd/pwd await ws.shell(f'cd "{base}"') r = await ws.shell("pwd") print(await r.stdout_str()) # Relative paths after cd r = await ws.shell("ls | tail -n 5") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` See `examples/python/vfs/discord/discord.py` for the full working example. ## Finding IDs VFS-specific commands require Discord snowflake IDs (`channel_id`, `guild_id`, `message_id`). These can be extracted from the filesystem: ```bash theme={null} # Guild ID - use stat stat "/discord/My Server__111222333444555666" # → extra={"guild_id": "1256522563555819574"} # Channel ID - use stat stat "/discord/My Server__111222333444555666/channels/general__777888999000111222" # → extra={"channel_id": "1256522563555819574"} # Message ID - inside JSONL messages jq -r '"\(.id) [\(.author.username)] \(.content)"' \ "/discord/My Server__111222333444555666/channels/general__777888999000111222/2026-04-04/chat.jsonl" # → 1489887688978075769 [alice] hello world # Find a message then reply jq -r 'select(.content | test("hello")) | .id' \ "/discord/My Server__111222333444555666/channels/general__777888999000111222/2026-04-04/chat.jsonl" # → 1489887688978075769 discord send --channel 1256522563555819574 \ --text "Reply" --reply-to 1489887688978075769 ``` ## Working with Large Channels Tips for efficient access on busy channels: ```bash theme={null} # Check message count per day wc -l "/discord/My Server__111222333444555666/channels/general__777888999000111222/2026-04-04/chat.jsonl" # Read only recent messages tail -n 10 "/discord/My Server__111222333444555666/channels/general__777888999000111222/2026-04-04/chat.jsonl" # Search one day grep "keyword" "/discord/My Server__111222333444555666/channels/general__777888999000111222/2026-04-04/chat.jsonl" # Extract specific fields jq -r '"\(.author.username): \(.content)"' \ "/discord/My Server__111222333444555666/channels/general__777888999000111222/2026-04-04/chat.jsonl" | head -n 20 # Count messages per user cat "/discord/My Server__111222333444555666/channels/general__777888999000111222/2026-04-04/chat.jsonl" \ | jq -r '.author.username' | sort | uniq -c ``` ## Shell Commands Standard commands available on the mounted Discord tree: | Command | Notes | | - | - | | `ls` | List guilds, channels, members, dates, attachments | | `cat` | Read `chat.jsonl`, member `.json`, or download an attachment | | `head` / `tail` | Smart: uses messages API for file scope | | `grep` / `rg` | Pattern search (file or directory level) | | `jq` | Query JSON; runs once per line of a JSONL file (`-s` for all) | | `wc` | Line/word/byte counts | | `stat` | File metadata (name, size, type, ID via `extra`) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | Acting on Discord (sending, editing, reactions, threads, polls, member and guild info, search) goes through the [discord CLI](/python/cli/discord) when installed; the mounted tree stays read-oriented. The `<name>__<id>` path segments supply the snowflake IDs the CLI flags take. ## Time scope Set `start_time` and/or `end_time` in the mount's YAML `config` (or pass `start_time`/`end_time` to Python; `startTime`/`endTime` to the TypeScript constructor). Bounds are RFC3339 timestamps with an explicit timezone and at most millisecond precision. Start is inclusive; end is exclusive. An omitted or null bound is open. Start must precede end. ```yaml theme={null} mounts: /history: vfs: discord mode: read config: token: "<bot-token>" start_time: "2026-06-01T10:00:00Z" end_time: "2026-06-02T00:00:00Z" ``` With a bound configured, channel listings cover the selected period rather than the default recent window. Day directories use UTC. Messages are selected by creation time, and attachments follow their parent messages. Direct paths, `stat`, date globs, and `grep`/`rg` cannot escape the scope. Scoped searches scan the filtered files. User/member and channel/server metadata remain visible as context. These settings apply to the VFS, not to separately installed account CLIs. `mode: read` prevents mount writes; it does not freeze upstream edits or deletions. Rebuild/remount the VFS to change its scope so cached listings and bytes are cleared. # Disk Source: https://docs.mirage.strukto.ai/python/vfs/disk Mount a local directory as a Mirage VFS with read/write shell commands and path traversal protection. The Disk VFS mounts a local directory at some prefix such as `/data/`. All operations are backed by real files on disk. Path resolution validates against the root boundary to prevent directory traversal escapes. ## Config ```python theme={null} from mirage import MountMode, Workspace from mirage.vfs.disk import DiskVFS vfs = DiskVFS(root="/path/to/dir") ws = Workspace({"/data": vfs}, mode=MountMode.READ) ``` `DiskVFS(root=..., folder_versions=True)` takes the `root` path of the directory to mount. Both `READ` and `WRITE` modes are supported. | Field | Default | Notes | | - | - | - | | `root` | required | The host directory the mount mirrors. A second disk mount whose root resolves to a folder already mounted is refused; a folder inside one is fine. | | `folder_versions` | `True` | Store each listing at its folder's version, so a `read: fresh` mount re-lists only folders that changed. Must be a boolean. Turn it off for a network or FUSE root. | ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Disk mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `grep -r`, `find` and `du` stop after 10000 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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `grep -r`, `find` and `du` stop after 10000 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. > ``` The Disk VFS mirrors the structure of the `root` directory. For example, if `root="/srv/files"` contains: ```text theme={null} /srv/files/ notes.txt config.json reports/ q1.csv q2.csv ``` Then mounting at `/data/` exposes: ```text theme={null} /data/ notes.txt config.json reports/ q1.csv q2.csv ``` Paths like `../../etc/passwd` are rejected - resolution is always confined to the root boundary. ## Cache The Disk VFS uses `IndexCacheStore` with `index_ttl = 60` (1 minute). Directory listings are cached for up to 60 seconds before being refreshed from disk. A configured `index:` replaces this lifetime with its own `ttl`, and the mount's `ttl:` caps it. Each listing is stored with its folder's version: the folder's device, inode, change time and modified time. Under `read: fresh`, a later command stats the folder and serves the cached listing while the version still matches, so it pays one local stat per listed folder instead of a scan. A folder changed in the last 2 seconds gets no version and is re-listed until it has been quiet that long, since two changes inside one timestamp tick could leave its times unmoved. This assumes a local POSIX filesystem, where adding, renaming or removing an entry moves the folder's change time. A network or FUSE root (NFS, SMB, rclone, s3fs, mirage's own FUSE) may not, so turn the versions off there: ```python theme={null} vfs = DiskVFS(root="/mnt/nfs/share", folder_versions=False) ``` That mount then re-lists a cached folder once per command, as every unversioned backend does. ## Example ```python theme={null} import asyncio import shutil import tempfile from pathlib import Path from mirage import MountMode, Workspace from mirage.vfs.disk import DiskVFS DATA_DIR = Path("/path/to/files") tmp = tempfile.mkdtemp() shutil.copytree(DATA_DIR, Path(tmp) / "files", dirs_exist_ok=True) vfs = DiskVFS(root=tmp + "/files") async def main() -> None: ws = Workspace({"/data/": vfs}, mode=MountMode.READ) r = await ws.shell("ls /data/") print(await r.stdout_str()) r = await ws.shell("cat /data/example.json") print(await r.stdout_str()) r = await ws.shell("tree /data/") print(await r.stdout_str()) r = await ws.shell("find /data/ -name '*.json'") print(await r.stdout_str()) r = await ws.shell("grep example /data/example.json") print(await r.stdout_str()) r = await ws.shell("stat /data/example.json") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Shell Commands The Disk VFS supports the full set of shell commands since it operates on real file content (text, binary, JSON, CSV, etc.): ### Read Commands | Command | Notes | | - | - | | `cat` | Read file content | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search (file or directory level) | | `jq` | Query JSON fields | | `wc` | Line/word/byte counts | | `stat` | File metadata (name, size, type, modified) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `nl` | Number lines | | `du` | Disk usage summary | | `file` | Detect file type | | `strings` | Extract printable strings from binary | | `xxd` | Hex dump | | `md5` | MD5 checksum | | `sha256sum` | SHA-256 checksum | ### Text Processing | Command | Notes | | - | - | | `awk` | Pattern scanning and processing | | `sed` | Stream editor | | `tr` | Translate or delete characters | | `sort` | Sort lines | | `uniq` | Remove duplicate lines | | `cut` | Extract fields/columns | | `join` | Join lines on a common field | | `paste` | Merge lines side by side | | `column` | Columnate output | | `fold` | Wrap lines to a specified width | | `expand` | Convert tabs to spaces | | `unexpand` | Convert spaces to tabs | | `fmt` | Simple text formatter | | `rev` | Reverse lines | | `tac` | Concatenate and print in reverse | | `look` | Display lines beginning with a given string | | `shuf` | Shuffle lines | | `tsort` | Topological sort | | `comm` | Compare two sorted files | | `cmp` | Compare two files byte by byte | | `diff` | Compare files line by line | | `patch` | Apply a diff patch | | `iconv` | Character encoding conversion | ### File Operations | Command | Notes | | - | - | | `cp` | Copy files | | `mv` | Move/rename files | | `rm` | Remove files | | `mkdir` | Create directories | | `touch` | Create empty file or update timestamp | | `ln` | Create symbolic links | | `tee` | Write stdin to file and stdout | | `mktemp` | Create temporary file | | `split` | Split file into pieces | | `csplit` | Split file by context | ### Path Utilities | Command | Notes | | - | - | | `basename` | Strip directory from path | | `dirname` | Strip filename from path | | `realpath` | Resolve path | | `readlink` | Print symbolic link target | | `ls` | List directory contents | ### Compression | Command | Notes | | - | - | | `gzip` | Compress files | | `gunzip` | Decompress gzip files | | `zip` | Create zip archives | | `unzip` | Extract zip archives | | `tar` | Archive files | | `zcat` | Cat compressed files | | `zgrep` | Grep compressed files | ### Encoding | Command | Notes | | - | - | | `base64` | Base64 encode/decode | ## Use Cases * **Local directory access**: Mount local directories for AI agents to read and process * **Sandboxed file access**: Restrict agent file operations to a specific directory tree * **FUSE mounting**: Expose disk files through a virtual FUSE mount for external tools * **Data pipelines**: Process local datasets with shell-like commands * **Development**: Test file operations against real data before deploying to cloud mounts # Dropbox Source: https://docs.mirage.strukto.ai/python/vfs/dropbox Mount a Dropbox account (or a single folder of it) as a read/write Mirage filesystem with async access and shell commands. The Dropbox VFS mounts a Dropbox account at some prefix such as `/dropbox/`. All operations involve network I/O to the [Dropbox v2 HTTP API](https://www.dropbox.com/developers/documentation/http/documentation): `/2/files/list_folder` for directories, `/2/files/download` for content, and `/2/files/upload` / `create_folder_v2` / `delete_v2` / `move_v2` / `copy_v2` for writes. Files are served as raw bytes. Both `READ` and `WRITE` modes are supported. `rmdir` fails `ENOTEMPTY` on a non-empty folder instead of using the API's recursive delete; `rm -r` is the recursive path. For credential setup (app key, secret, refresh token), see the [Dropbox Setup](/home/setup/dropbox) guide. The TypeScript packages ship the same backend for Node and the browser, see [Dropbox (TypeScript)](/typescript/setup/dropbox). ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.dropbox import DropboxConfig, DropboxVFS config = DropboxConfig( client_id=os.environ["DROPBOX_APP_KEY"], client_secret=os.environ["DROPBOX_APP_SECRET"], refresh_token=os.environ["DROPBOX_REFRESH_TOKEN"], # Optional: # root_path="/Team/data", # mount a sub-folder as the root ) vfs = DropboxVFS(config) ws = Workspace({"/dropbox": vfs}, mode=MountMode.WRITE) ``` The access token is fetched from the long-lived refresh token and cached in memory, refreshing \~5 minutes before expiry. ### Config Reference | Field | Description | | - | - | | `timeout` default `30` | 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. | | `client_id` required | Dropbox app key. | | `client_secret` required, secret | Dropbox app secret. | | `refresh_token` required, secret | Long-lived OAuth refresh token; mirage mints short-lived access tokens from it. | | `root_path` default `'/'` | Dropbox folder the mount uses as its root, such as `/Projects`; `/` is the account root. `..` segments are rejected. | | `endpoint` | Base URL that replaces Dropbox's OAuth, API and content hosts, such as a test server. Unset uses Dropbox's hosts. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Dropbox mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `dropbox`, write | > > #### 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 `dropbox` 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>` | `dropbox`, write | > > ## 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 `dropbox` 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. > ``` ## Mount a subfolder Pass `root_path` to expose a single Dropbox folder as the mount root instead of the whole account. Every command and FUSE/VFS op is scoped to that folder; paths outside it are unreachable. ```python theme={null} config = DropboxConfig( client_id=os.environ["DROPBOX_APP_KEY"], client_secret=os.environ["DROPBOX_APP_SECRET"], refresh_token=os.environ["DROPBOX_REFRESH_TOKEN"], root_path="/Team/data", ) ``` `root_path` accepts `Team/data`, `/Team/data`, or `/Team/data/` (all normalized the same way); `..` segments are rejected. ## Integration What Dropbox answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Dropbox | | - | - | | `grep -r`, `rg` | Dropbox search, for whole words. It can miss Office files, PDFs, archives, the end of large files, words Dropbox splits differently (`foo.bar`) and recent writes; file contents on plans below Professional. | | `find`, `du`, `ls -R`, `tree` | One recursive listing | `grep -rw` and `rg -w` read only the files [Dropbox search](https://www.dropbox.com/developers/documentation/http/documentation#files-search) names. Every file is read when the search fails, reaches its 10,000-match limit or finds nothing. [Search](/home/integration/search) lists how each option uses the search. Dropbox can leave out a file that holds the word, so `walk_limit: -1` in the mount's `"@all"` [command limit](/home/core/output-limits) reads every file instead: * Full-text search needs a Dropbox Professional, Essentials or Business plan. On other plans Dropbox matches file names only, so files that hold the word are left out. * Dropbox searches the text it extracted, not the bytes `grep` reads, and indexes a write some time after it lands. A file that holds the word can be left out: an office file, PDF or archive, the end of a large file, a word Dropbox splits differently (`foo.bar`), or a recent write. ## Cache The Dropbox VFS caches directory listings via `IndexCacheStore` to reduce repeated API calls during traversal; with no `index:` configured, listings live for the mount's `ttl` (600 s by default), at most 24 hours; a configured `index:` uses its own `ttl`, still capped by the mount's `ttl:`. File reads go through the standard read cache (`caches_reads = True`). Under `read: fresh`, a cached file is checked against its `content_hash` before it is served: one `get_metadata` per warm read, never a folder listing. A download names the hash in its `Dropbox-API-Result` header, full or ranged, so a read stamps it with no extra request. `server_modified` is not used: Dropbox repeats it across same-size rewrites. ## Names missing from a listing A name missing from a cached listing that the running command did not fetch is looked up on Dropbox by path before mirage answers that it does not exist: one `get_metadata` for a `stat`, or the download itself for a read. A file another client created after the listing is therefore found, and `>>`, `touch` and `sed -i` act on it instead of replacing it. A listing the running command fetched itself is trusted as is, for the whole command. Each command of a script is its own command, but one long-running command, such as a program a runtime runs, does not see a file another client creates after it listed the folder. Some lookups run outside any shell command: FUSE, programmatic calls, `[ ]` and `[[ ]]` tests, and a redirect on anything but a simple command (a brace group, subshell, loop, `if` or `case`). No listing is the caller's own there, so each lookup of a name missing from a cached listing costs one request. ## Writes A write records the `content_hash` its upload reply names, so a `fresh` read right after a `tee` or `sed -i` downloads nothing. ## Conditional writes A rewrite that observes a missing file requires atomic create-only support, which this backend does not currently enable. Appending to a missing file therefore returns an unsupported-operation error under either write policy. An intentional write with `>` can create the file, and subsequent appends to that existing file retain the selected policy. A Dropbox mount accepts `write: conditional`. A write that holds a version looks the file up once (`get_metadata`), refuses a file whose `content_hash` changed since it was read, and uploads in `update` mode with the file's `rev`, so Dropbox refuses (409 `path/conflict`) a change that lands in between; a delete sends the `rev` as `parent_rev`. `rm -r` walks the folder file by file, and a `mv` within the mount is Dropbox's own move, which is not refused when its source changed (a `mv` to another mount is a copy and a conditioned delete, so there a changed source stays and `mv` reports the failed removal). ## Example ```python theme={null} import asyncio import os from mirage import MountMode, Workspace from mirage.vfs.dropbox import DropboxConfig, DropboxVFS config = DropboxConfig( client_id=os.environ["DROPBOX_APP_KEY"], client_secret=os.environ["DROPBOX_APP_SECRET"], refresh_token=os.environ["DROPBOX_REFRESH_TOKEN"], ) vfs = DropboxVFS(config) async def main() -> None: ws = Workspace({"/dropbox": vfs}, mode=MountMode.WRITE) r = await ws.shell("ls /dropbox/") print(await r.stdout_str()) r = await ws.shell("grep -rl report /dropbox/docs/") print(await r.stdout_str()) await ws.close() asyncio.run(main()) ``` `grep` classifies the bytes it reads, including downloaded attachments. Use `-I` to skip binary inputs or `-a` (`--binary-files=text`) to search them as text. Text mode bypasses the content-search index and scans files directly. # Email Source: https://docs.mirage.strukto.ai/python/vfs/email Mount an IMAP mailbox as a Mirage filesystem and send messages through SMTP from Python workspaces. The Email VFS exposes any IMAP mailbox as a virtual filesystem mounted at some prefix such as `/email/`. Sending is handled via SMTP. Sending through `himalaya` needs the extra: ```bash theme={null} pip install "mirage-ai[email]" ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.email import EmailConfig, EmailVFS config = EmailConfig( imap_host=os.environ["IMAP_HOST"], smtp_host=os.environ["SMTP_HOST"], username=os.environ["EMAIL_USERNAME"], password=os.environ["EMAIL_PASSWORD"], ) vfs = EmailVFS(config=config) ws = Workspace({"/email": vfs}, mode=MountMode.READ) ``` ### Config Reference | Field | Description | | - | - | | `timeout` default `30` | 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. | | `imap_host` required | IMAP server hostname. | | `imap_port` default `993` | IMAP server port. | | `smtp_host` required | SMTP server hostname `himalaya` sends mail through. | | `smtp_port` default `587` | SMTP server port. `465` uses implicit TLS; any other port starts in plaintext and upgrades with STARTTLS when the server offers it. | | `username` required | Login for both IMAP and SMTP, usually the email address. | | `password` required, secret | Password or app password for `username`. | | `use_ssl` default `True` | Speak TLS from the first byte of the IMAP connection (IMAPS); off connects in plaintext. SMTP follows `smtp_port` instead. | | `max_messages` default `200` | How many of a folder's newest messages the mount lists and `grep` searches, and the window `himalaya envelope list` and `search` page through. | | `save_copy` default `True` | After `himalaya` sends a message, append a copy to `sent_folder`, as upstream himalaya's `message.send.save-copy`. Off saves a copy only when `--save` names a mailbox. | | `sent_folder` | Mailbox a sent copy goes to. Unset asks the server for the mailbox tagged `\Sent` and falls back to `Sent`. | | `trash_folder` | Mailbox `himalaya message delete` moves messages to, as upstream's `mailbox.alias.trash`. Unset asks the server for the mailbox tagged `\Trash` and falls back to `Trash`. | Fields marked secret are redacted in snapshots. ### Common VFS Settings | Provider | IMAP Host | SMTP Host | Notes | | - | - | - | - | | Yahoo | `imap.mail.yahoo.com` | `smtp.mail.yahoo.com` | App password required | | Fastmail | `imap.fastmail.com` | `smtp.fastmail.com` | App password | | iCloud | `imap.mail.me.com` | `smtp.mail.me.com` | App password | | ProtonMail | `127.0.0.1` (Bridge) | `127.0.0.1` (Bridge) | Requires ProtonMail Bridge | | Self-hosted | Your server hostname | Your server hostname | Whatever you configured | For credentials and provider support, see [Email setup](/home/setup/email). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Email mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `email`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > <folder>/ # INBOX, Sent, Drafts, ... > <yyyy-mm-dd>/ > <subject>__<uid>.email.json # the message as JSON > <subject>__<uid>/ # its attachments, if any > <attachment-filename> > ``` > > * `<subject>` is sanitized: `ls` the date directory rather than > construct it. > * To list, search, read, compose, reply or forward, use the `himalaya` > CLI if installed (`himalaya --help`). > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `email` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `email` answers only for `*/*/*.email.json`; `grep -r` and `rg` read every other 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>` | `email`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > <folder>/ # INBOX, Sent, Drafts, ... > <yyyy-mm-dd>/ > <subject>__<uid>.email.json # the message as JSON > <subject>__<uid>/ # its attachments, if any > <attachment-filename> > ``` > > - `<subject>` is sanitized: `ls` the date directory rather than > construct it. > - To list, search, read, compose, reply or forward, use the `himalaya` > CLI if installed (`himalaya --help`). > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `email` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `email` answers only for `*/*/*.email.json`; `grep -r` and `rg` read every other 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. > ```` Folder directories appear at the root, using IMAP folder names (e.g., `INBOX`, `Sent`, `Drafts`). ### Date Directories Inside each folder, messages are grouped into date subdirectories formatted as `YYYY-MM-DD`. The date is derived from the message's `Date` header. ### Message Files Each message is stored as a `.email.json` file. The filename shape is: ```text theme={null} <sanitized-subject>__<uid>.email.json ``` ### Attachments Messages that have attachments get a companion subdirectory with the same base name (without `.email.json`): ```text theme={null} Meeting_Notes__12345.email.json # message JSON Meeting_Notes__12345/ # attachment directory report.pdf screenshot.png ``` ## Cache The Email VFS uses `IndexCacheStore` (same as Gmail, Slack, Discord, and other mounts). Index entries store folder names, message UIDs, and message metadata. ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.commands.cli.builtin.himalaya import HIMALAYA from mirage.vfs.email import EmailConfig, EmailVFS load_dotenv(".env.development") config = EmailConfig( imap_host=os.environ["IMAP_HOST"], smtp_host=os.environ["SMTP_HOST"], username=os.environ["EMAIL_USERNAME"], password=os.environ["EMAIL_PASSWORD"], ) vfs = EmailVFS(config=config) async def main(): ws = Workspace({"/email": vfs}, mode=MountMode.READ) ws.register_cli("himalaya", HIMALAYA, config.model_dump()) # List folders r = await ws.shell("ls /email/") print(await r.stdout_str()) # List date directories in INBOX r = await ws.shell("ls /email/INBOX/") print(await r.stdout_str()) # List messages for a specific date r = await ws.shell("ls /email/INBOX/2026-04-14/") print(await r.stdout_str()) # Read a message r = await ws.shell( "cat /email/INBOX/2026-04-14/Meeting_Notes__12345.email.json") print(await r.stdout_str()) # Extract subject with jq r = await ws.shell( 'jq ".subject"' " /email/INBOX/2026-04-14/Meeting_Notes__12345.email.json") print(await r.stdout_str()) # List attachments r = await ws.shell("ls /email/INBOX/2026-04-14/Meeting_Notes__12345/") print(await r.stdout_str()) # Search across all messages r = await ws.shell('rg "quarterly" /email/INBOX/') print(await r.stdout_str()) # Tree view r = await ws.shell("tree -L 2 /email/INBOX/") print(await r.stdout_str()) # Triage unread messages r = await ws.shell( "himalaya envelope search -m INBOX --page-size 5 not flag seen") print(await r.stdout_str()) # Send an email r = await ws.shell( 'himalaya message compose --to "user@example.com"' ' --subject "Hello from MIRAGE"' ' --body "This email was sent via the MIRAGE email VFS." --send') print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Finding UIDs VFS-specific commands require message UIDs. These can be extracted from the filesystem: ```bash theme={null} # UID is embedded in filename after "__" ls /email/INBOX/2026-04-14/ # -> Meeting_Notes__12345.email.json <- uid = 12345 # Read a message, then send a reply himalaya message read -m INBOX 12345 himalaya message reply -m INBOX 12345 --body "Thanks for the notes" --send ``` For composing and sending mail, see the [Himalaya CLI](/python/cli/himalaya#compose-reply-and-send). ## Shell Commands Standard commands available on the mounted email tree: | Command | Notes | | - | - | | `ls` | List folders, dates, messages, attachments | | `cat` | Read message JSON or attachment content | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search (file or directory level) | | `jq` | Query message JSON fields | | `wc` | Line/word/byte counts | | `stat` | File metadata (name, size, type) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `basename` | Extract filename from path | | `dirname` | Extract directory from path | | `realpath` | Resolve path to absolute form | | `nl` | Number lines of output | Acting on mail (list, read, send, reply, forward) goes through the [himalaya CLI](/python/cli/himalaya) when installed. ## Integration What Email answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Email | | - | - | | `grep -r`, `rg` | IMAP `SEARCH TEXT`, for any text. It can miss on a server that searches words rather than substrings (Dovecot with full-text search). | `grep -r` and `rg` read only the messages IMAP `SEARCH TEXT` names in each folder or day they walk (from the mount root, in every folder), and print what reading every message would. IMAP matches the headers and body in any case; each hit's file is named from a header-only fetch. Attachments are always read. Every message is read when the text is a key of the message JSON or a flag name, holds anything but ASCII letters and spaces, matches more than `max_messages` messages in a folder, or the search fails. `walk_limit: -1` in the mount's `"@all"` [command limit](/home/core/output-limits) reads every file instead, since a server that answers `SEARCH` from a full-text index (Dovecot with an FTS plugin, for one) matches words rather than substrings, so a narrowed scan could miss a message there. # Google Calendar Source: https://docs.mirage.strukto.ai/python/vfs/gcal Mount Google Calendar calendars and events as JSON files from Python. The Google Calendar VFS exposes every calendar the account can see as a directory of date buckets, with one `.gcal.json` file per event. For Google OAuth setup, see [Google Workspace Setup](/home/setup/google). For the TypeScript SDK, see [Google Calendar (TypeScript)](/typescript/setup/gcal). ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.gcal import GCalConfig, GCalVFS config = GCalConfig( client_id=os.environ["GOOGLE_CLIENT_ID"], client_secret=os.environ["GOOGLE_CLIENT_SECRET"], refresh_token=os.environ["GOOGLE_REFRESH_TOKEN"], ) vfs = GCalVFS(config) ws = Workspace({"/gcal": vfs}, mode=MountMode.READ) ``` | Field | Description | | - | - | | `start_time` | Start of the mount's time scope, inclusive: an RFC 3339 timestamp with an explicit timezone and at most millisecond precision. Unset leaves the start open. | | `end_time` | End of the mount's time scope, exclusive, in the same format as `start_time`, which it must follow. Unset leaves the end open. | | `timeout` default `30` | 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. | | `access_token` secret | OAuth access token, or a callable that returns one. Takes precedence over `client_id` and `refresh_token`. | | `client_id` | Google OAuth client ID. Required with `refresh_token` when `access_token` is unset; mirage then mints and renews access tokens itself. | | `client_secret` secret | Google OAuth client secret, sent with the refresh-token grant. Omit it for a PKCE client. | | `refresh_token` secret | User's OAuth refresh token. Required with `client_id` when `access_token` is unset. | | `api_base` | One base URL that replaces every Google API host and the OAuth token endpoint, such as a test server. Unset uses Google's hosts. | | `time_zone` | IANA time zone the mount buckets every calendar's days in. Unset uses the primary calendar's zone. | | `bucket_days` default `1` | Days each date directory under a calendar holds: `1` names it by its day, `7` and `30` by its first and last day (`<first>--<last>`). | | `min_access_role` | List only calendars where the account has at least this access role: `freeBusyReader`, `reader`, `writer` or `owner`. Unset lists every calendar. | | `today` | Day (`YYYY-MM-DD`) the default listing's 90-day future horizon is measured from, for tests and snapshots. Unset uses the current date in the mount's time zone. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Google Calendar mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `gcal`, write | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > primary/ > calendar.json > 2026-08-11/ > <eventId>__0900-1030_Team_Standup.gcal.json > Engineering__team@group.calendar.google.com/ > 2026-08-11/ > ... > ``` > > Reading the tree: > > * `ls /<path>/` lists the calendars. The primary one is always spelled > `primary`; every other directory ends in `__<calendarId>`. > * `ls /<path>/primary/` lists buckets with events from all available > history through today +90 days unless `end_time` is configured. > `start_time`/`end_time` restrict this mount, including direct paths, > date globs and event reads. A date glob such as > `ls /<path>/primary/2027-03-*` selects its own listing range within > that scope, beyond the default future horizon. > * A bucket is one local day, named by its date. A well-formed date > inside the configured scope is a directory even when it holds no > events. Dates outside the scope are absent. > * A file name is `<eventId>__<HHMM-HHMM>_<Title>.gcal.json`. The times > are clamped to that day, so an event running through it reads > `0000-2400`. A multi-day event appears under every day it covers. > * `cat` an event for the unmodified Calendar API payload, including > attendees, description, location and the original start and end with > offsets. > * `calendar.json` carries the calendar's `accessRole` and, in > `bucketTimeZone`, the zone the buckets are cut in. That zone is > mount-wide, so every calendar's `2026-08-11/` covers the same hours. > * On a calendar shared as free/busy only, Google returns no titles at > all, so events render as `busy`. > > Acting on it: > > * On a `write` path, `rm` an event file to delete that event for every > attendee. > * Everything else goes through the `gws calendar` CLI, which takes the > ids the tree renders. > * A written event must carry an explicit UTC offset or `timeZone`; an > ambiguous local time is not interpreted for you. > > Time scope: `start_time=unbounded` (inclusive), `end_time=unbounded` (exclusive). Explicit paths and globs cannot escape this scope. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest), and `rm` and `unlink`. `grep -r` and `rg` with `-w` ask `gcal` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Not supported: `>`, `>>`, `tee`, `tee -a`, `touch` of a new file, `cp`, `cp -r`, `mkdir`, `mv`, `rm -r`, `rmdir`, `truncate`, `sed -i`. Without `-w`, `grep -r` and `rg` read every file. `gcal` answers only for `*/*/*.gcal.json`; `grep -r` and `rg` read every other 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>` | `gcal`, write | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > primary/ > calendar.json > 2026-08-11/ > <eventId>__0900-1030_Team_Standup.gcal.json > Engineering__team@group.calendar.google.com/ > 2026-08-11/ > ... > ``` > > Reading the tree: > > - `ls /<path>/` lists the calendars. The primary one is always spelled > `primary`; every other directory ends in `__<calendarId>`. > - `ls /<path>/primary/` lists buckets with events from all available > history through today +90 days unless `end_time` is configured. > `start_time`/`end_time` restrict this mount, including direct paths, > date globs and event reads. A date glob such as > `ls /<path>/primary/2027-03-*` selects its own listing range within > that scope, beyond the default future horizon. > - A bucket is one local day, named by its date. A well-formed date > inside the configured scope is a directory even when it holds no > events. Dates outside the scope are absent. > - A file name is `<eventId>__<HHMM-HHMM>_<Title>.gcal.json`. The times > are clamped to that day, so an event running through it reads > `0000-2400`. A multi-day event appears under every day it covers. > - `cat` an event for the unmodified Calendar API payload, including > attendees, description, location and the original start and end with > offsets. > - `calendar.json` carries the calendar's `accessRole` and, in > `bucketTimeZone`, the zone the buckets are cut in. That zone is > mount-wide, so every calendar's `2026-08-11/` covers the same hours. > - On a calendar shared as free/busy only, Google returns no titles at > all, so events render as `busy`. > > Acting on it: > > - On a `write` path, `rm` an event file to delete that event for every > attendee. > - Everything else goes through the `gws calendar` CLI, which takes the > ids the tree renders. > - A written event must carry an explicit UTC offset or `timeZone`; an > ambiguous local time is not interpreted for you. > > Time scope: `start_time=unbounded` (inclusive), `end_time=unbounded` (exclusive). Explicit paths and globs cannot escape this scope. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest), and `rm` and `unlink`. `grep -r` and `rg` with `-w` ask `gcal` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Not supported: `>`, `>>`, `tee`, `tee -a`, `touch` of a new file, `cp`, `cp -r`, `mkdir`, `mv`, `rm -r`, `rmdir`, `truncate`, `sed -i`. Without `-w`, `grep -r` and `rg` read every file. `gcal` answers only for `*/*/*.gcal.json`; `grep -r` and `rg` read every other 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. > ```` ## Write Support The only write is `rm` on an event file, on a mount in `MountMode.WRITE`. It deletes the event on its calendar, for every attendee. The account needs the `owner` or `writer` role on that calendar; otherwise `rm` fails with permission denied. Creating, editing and moving events go through the [`gws calendar`](/home/setup/cli/gws) CLI, which takes the calendar and event ids the tree shows. ## Example ```python theme={null} import asyncio import os from mirage import MountMode, Workspace from mirage.vfs.gcal import GCalConfig, GCalVFS async def main() -> None: config = GCalConfig( client_id=os.environ["GOOGLE_CLIENT_ID"], client_secret=os.environ["GOOGLE_CLIENT_SECRET"], refresh_token=os.environ["GOOGLE_REFRESH_TOKEN"], bucket_days=7, ) ws = Workspace({"/gcal": GCalVFS(config)}, mode=MountMode.READ) # Calendars the account can see res = await ws.shell("ls /gcal") print(await res.stdout_str()) # Weeks that open in November 2026 res = await ws.shell("ls /gcal/primary/2026-11-*") print(await res.stdout_str()) # Events that mention a word res = await ws.shell("grep -lw standup /gcal/primary/*/*.gcal.json") print(await res.stdout_str()) await ws.close() if __name__ == "__main__": asyncio.run(main()) ``` # GCS Source: https://docs.mirage.strukto.ai/python/vfs/gcs Mount Google Cloud Storage buckets through Mirage's async S3-compatible VFS layer for Python agents. The GCS VFS mounts a Google Cloud Storage bucket at some prefix such as `/gcs/`. All operations involve network I/O to the remote object store. Uses aioboto3 against GCS's S3-compatible XML API via HMAC keys, inheriting all S3 VFS capabilities. For credential setup, see [GCS Setup](/home/setup/gcs). Install the extra: ```bash theme={null} pip install "mirage-ai[gcs]" ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.gcs import GCSConfig, GCSVFS config = GCSConfig( bucket=os.environ["GCS_BUCKET"], access_key_id=os.environ["GCS_ACCESS_KEY_ID"], secret_access_key=os.environ["GCS_SECRET_ACCESS_KEY"], # Optional: # endpoint_url="https://storage.googleapis.com", # region="auto", # timeout=30, # proxy="http://proxy:8080", ) vfs = GCSVFS(config) ws = Workspace({"/gcs": vfs}, mode=MountMode.READ) ``` `GCSVFS(config)` takes a `GCSConfig` object with the bucket name and HMAC credentials. Both `READ` and `WRITE` modes are supported. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `bucket` required | Name of the bucket to mount. | | `region` default `'auto'` | Region requests are signed for; GCS serves every region from one host. | | `endpoint_url` default `'https://storage.googleapis.com'` | Endpoint URL of the S3 interoperability API. | | `access_key_id` secret | Access key ID; set it with `secret_access_key`. Unset uses the AWS credential chain. | | `secret_access_key` secret | Secret access key paired with `access_key_id`. | | `session_token` secret | Session token for temporary credentials, sent with the access key pair. | | `aws_profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `path_style` default `False` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `key_prefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | Fields marked secret are redacted in snapshots. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with GCS mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` The GCS VFS maps object keys to virtual paths under the mount prefix, identical to the S3 VFS. GCS "directories" are prefix-based — there are no real directory objects. For example, if bucket `mirage-ai` contains: ```text theme={null} data/example.json data/example.parquet data/example.jsonl ``` Then mounting at `/gcs/` exposes: ```text theme={null} /gcs/ data/ example.json example.parquet example.jsonl ``` Path mapping: virtual `/gcs/data/example.json` maps to GCS key `data/example.json`. ## Cache The GCS VFS uses `IndexCacheStore` with `index_ttl = 600` (10 minutes), same as S3. Directory listings are cached for up to 600 seconds before being refreshed from GCS. This reduces API calls for repeated directory traversals. A configured `index:` replaces this lifetime with its own `ttl`, and the mount's `ttl:` caps it. ## Integration What GCS answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On GCS | | - | - | | `md5sum` | The object's ETag, when it is the MD5: a single-part upload, unencrypted or under SSE-S3 | | `find`, `du`, `ls -R`, `tree` | One recursive listing | ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.vfs.gcs import GCSConfig, GCSVFS load_dotenv(".env.development") config = GCSConfig( bucket=os.environ["GCS_BUCKET"], access_key_id=os.environ["GCS_ACCESS_KEY_ID"], secret_access_key=os.environ["GCS_SECRET_ACCESS_KEY"], ) vfs = GCSVFS(config) async def main() -> None: ws = Workspace({"/gcs/": vfs}, mode=MountMode.READ) r = await ws.shell("ls /gcs/") print(await r.stdout_str()) r = await ws.shell("cat /gcs/data/example.json | head -n 10") print(await r.stdout_str()) r = await ws.shell("tree /gcs/") print(await r.stdout_str()) r = await ws.shell("find /gcs/ -name '*.parquet'") print(await r.stdout_str()) r = await ws.shell("stat /gcs/data/example.json") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Shell Commands The GCS VFS supports the full set of shell commands since it operates on real file content (text, binary, JSON, CSV, etc.). Large files benefit from range reads to avoid downloading entire objects. ### Read Commands | Command | Notes | | - | - | | `cat` | Read file content | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search (file or directory level) | | `jq` | Query JSON fields | | `wc` | Line/word/byte counts | | `stat` | File metadata (name, size, type, modified) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `nl` | Number lines | | `du` | Disk usage summary | | `file` | Detect file type | | `strings` | Extract printable strings from binary | | `xxd` | Hex dump | | `md5` | MD5 checksum | | `sha256sum` | SHA-256 checksum | ### Text Processing | Command | Notes | | - | - | | `awk` | Pattern scanning and processing | | `sed` | Stream editor | | `tr` | Translate or delete characters | | `sort` | Sort lines | | `uniq` | Remove duplicate lines | | `cut` | Extract fields/columns | | `join` | Join lines on a common field | | `paste` | Merge lines side by side | | `column` | Columnate output | | `fold` | Wrap lines to a specified width | | `expand` | Convert tabs to spaces | | `unexpand` | Convert spaces to tabs | | `fmt` | Simple text formatter | | `rev` | Reverse lines | | `tac` | Concatenate and print in reverse | | `look` | Display lines beginning with a given string | | `shuf` | Shuffle lines | | `tsort` | Topological sort | | `comm` | Compare two sorted files | | `cmp` | Compare two files byte by byte | | `diff` | Compare files line by line | | `patch` | Apply a diff patch | | `iconv` | Character encoding conversion | ### File Operations | Command | Notes | | - | - | | `cp` | Copy files | | `mv` | Move/rename files | | `rm` | Remove files | | `mkdir` | Create directories | | `touch` | Create empty file or update timestamp | | `ln` | Create symbolic links | | `tee` | Write stdin to file and stdout | | `mktemp` | Create temporary file | | `split` | Split file into pieces | | `csplit` | Split file by context | ### Path Utilities | Command | Notes | | - | - | | `basename` | Strip directory from path | | `dirname` | Strip filename from path | | `realpath` | Resolve path | | `readlink` | Print symbolic link target | | `ls` | List directory contents | ### Compression | Command | Notes | | - | - | | `gzip` | Compress files | | `gunzip` | Decompress gzip files | | `zip` | Create zip archives | | `unzip` | Extract zip archives | | `tar` | Archive files | | `zcat` | Cat compressed files | | `zgrep` | Grep compressed files | ### Encoding | Command | Notes | | - | - | | `base64` | Base64 encode/decode | ## Use Cases * **AI agents accessing GCS data**: Mount GCS buckets for agents to read and process datasets * **Data pipelines**: Read and write GCS objects with shell-like commands * **FUSE mounting**: Expose GCS buckets through a virtual FUSE mount for external tools # Google Docs Source: https://docs.mirage.strukto.ai/python/vfs/gdocs Mount Google Docs as JSON-backed files so Python agents can read document structure and content through Mirage. The Google Docs VFS exposes Docs documents as a virtual filesystem mounted at some prefix such as `/gdocs/`. For Google OAuth setup, see [Google Workspace Setup](/home/setup/google). ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.gdocs import GDocsConfig, GDocsVFS config = GDocsConfig( client_id=os.environ["GOOGLE_CLIENT_ID"], client_secret=os.environ["GOOGLE_CLIENT_SECRET"], refresh_token=os.environ["GOOGLE_REFRESH_TOKEN"], ) vfs = GDocsVFS(config=config) ws = Workspace({"/gdocs": vfs}, mode=MountMode.READ) ``` | Field | Description | | - | - | | `timeout` default `30` | 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. | | `access_token` secret | OAuth access token, or a callable that returns one. Takes precedence over `client_id` and `refresh_token`. | | `client_id` | Google OAuth client ID. Required with `refresh_token` when `access_token` is unset; mirage then mints and renews access tokens itself. | | `client_secret` secret | Google OAuth client secret, sent with the refresh-token grant. Omit it for a PKCE client. | | `refresh_token` secret | User's OAuth refresh token. Required with `client_id` when `access_token` is unset. | | `api_base` | One base URL that replaces every Google API host and the OAuth token endpoint, such as a test server. Unset uses Google's hosts. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Google Docs mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `gdocs`, write | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > owned/ # docs you created > <YYYY-MM-DD>_<title>__<doc-id>.gdoc.json > shared/ # docs others shared with you > <YYYY-MM-DD>_<title>__<doc-id>.gdoc.json > ``` > > * `<YYYY-MM-DD>` is the file's `modifiedTime`, so a date glob such as > `2026-05-*` narrows by it. > * `<title>` is sanitized: spaces and any character outside > `[A-Za-z0-9_.-]` become `_`, at most 100 characters. > * `<doc-id>` is the Google Docs document id. > * `shared/` holds docs shared with you by others; ones you own > and shared with others are still in `owned/`. > > A `.gdoc.json` holds the Google Docs API `documents.get` response, read > with `includeTabsContent=true` so every tab is present: > > ```jsonc theme={null} > { > "documentId": "...", > "title": "...", > "tabs": [ // one entry per top-level tab > { > "tabProperties": { > "tabId": "t.0", // names a tab for gws docs write > "title": "Tab 1", > "index": 0 > }, > "documentTab": { > "body": { > "content": [ > { // one element per block > "paragraph": { > "elements": [ > { "textRun": { "content": "the actual text\n", > "textStyle": {...} } } > ], > "paragraphStyle": {...} > } > }, > { "table": {...} }, > { "sectionBreak": {...} } > ] > }, > "documentStyle": {...}, > "namedStyles": {...} > }, > "childTabs": [ { ...same shape, nested to any depth... } ] > // a nested tab also carries > // parentTabId and nestingLevel; > // a root tab carries neither > } > ], > "revisionId": "..." > } > ``` > > There is no top-level .body. A tab-aware response leaves the singleton > fields (`.body`, `.documentStyle`, `.namedStyles`) empty and hangs every > tab's content off `.tabs[].documentTab` instead. Tabs also nest, so text > can sit at any depth under `.childTabs`; the recursive recipes below read > a one-tab and a fifty-tab document alike. > > Useful `jq` paths: > > ```jq theme={null} > .title > [.. | .tabProperties? // empty | .title] # every tab name > [.. | .textRun? // empty | .content] | add # all text, any depth > [.. | .tabProperties? // empty] | length # tab count > [.tabs[0].documentTab.body.content[] > | .paragraph?.elements[]?.textRun.content] | add # first tab only > .revisionId > ``` > > The first block of a body is always a `sectionBreak`, which carries no > `.paragraph`, so a path through `.paragraph` needs the `?` or it fails > with `Cannot iterate over null`. > > Delete, on a `write` path: > > ```sh theme={null} > rm /<path>/owned/<file>.gdoc.json # deletes it from Drive for good > rm -f <path> # ignores a missing file > ``` > > Only `.gdoc.json` files can be removed; `owned/` and `shared/` cannot. > > Rename to a new title, on a `write` path: > > ```sh theme={null} > mv /<path>/owned/<date>_<old>__<id>.gdoc.json \ > /<path>/owned/<date>_<new>__<id>.gdoc.json > ``` > > Keep the folder, the date and the id, and spell the title the way the > listing does (spaces become `_`); any other name is refused. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest), and `mv`, `rm` and `unlink`. `grep -r` and `rg` with `-w` ask `gdocs` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Not supported: `>`, `>>`, `tee`, `tee -a`, `touch` of a new file, `cp`, `cp -r`, `mkdir`, `rm -r`, `rmdir`, `truncate`, `sed -i`. 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>` | `gdocs`, write | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > owned/ # docs you created > <YYYY-MM-DD>_<title>__<doc-id>.gdoc.json > shared/ # docs others shared with you > <YYYY-MM-DD>_<title>__<doc-id>.gdoc.json > ``` > > - `<YYYY-MM-DD>` is the file's `modifiedTime`, so a date glob such as > `2026-05-*` narrows by it. > - `<title>` is sanitized: spaces and any character outside > `[A-Za-z0-9_.-]` become `_`, at most 100 characters. > - `<doc-id>` is the Google Docs document id. > - `shared/` holds docs shared with you by others; ones you own > and shared with others are still in `owned/`. > > A `.gdoc.json` holds the Google Docs API `documents.get` response, read > with `includeTabsContent=true` so every tab is present: > > ```jsonc > { > "documentId": "...", > "title": "...", > "tabs": [ // one entry per top-level tab > { > "tabProperties": { > "tabId": "t.0", // names a tab for gws docs write > "title": "Tab 1", > "index": 0 > }, > "documentTab": { > "body": { > "content": [ > { // one element per block > "paragraph": { > "elements": [ > { "textRun": { "content": "the actual text\n", > "textStyle": {...} } } > ], > "paragraphStyle": {...} > } > }, > { "table": {...} }, > { "sectionBreak": {...} } > ] > }, > "documentStyle": {...}, > "namedStyles": {...} > }, > "childTabs": [ { ...same shape, nested to any depth... } ] > // a nested tab also carries > // parentTabId and nestingLevel; > // a root tab carries neither > } > ], > "revisionId": "..." > } > ``` > > There is no top-level .body. A tab-aware response leaves the singleton > fields (`.body`, `.documentStyle`, `.namedStyles`) empty and hangs every > tab's content off `.tabs[].documentTab` instead. Tabs also nest, so text > can sit at any depth under `.childTabs`; the recursive recipes below read > a one-tab and a fifty-tab document alike. > > Useful `jq` paths: > > ```jq > .title > [.. | .tabProperties? // empty | .title] # every tab name > [.. | .textRun? // empty | .content] | add # all text, any depth > [.. | .tabProperties? // empty] | length # tab count > [.tabs[0].documentTab.body.content[] > | .paragraph?.elements[]?.textRun.content] | add # first tab only > .revisionId > ``` > > The first block of a body is always a `sectionBreak`, which carries no > `.paragraph`, so a path through `.paragraph` needs the `?` or it fails > with `Cannot iterate over null`. > > Delete, on a `write` path: > > ```sh > rm /<path>/owned/<file>.gdoc.json # deletes it from Drive for good > rm -f <path> # ignores a missing file > ``` > > Only `.gdoc.json` files can be removed; `owned/` and `shared/` cannot. > > Rename to a new title, on a `write` path: > > ```sh > mv /<path>/owned/<date>_<old>__<id>.gdoc.json \ > /<path>/owned/<date>_<new>__<id>.gdoc.json > ``` > > Keep the folder, the date and the id, and spell the title the way the > listing does (spaces become `_`); any other name is refused. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest), and `mv`, `rm` and `unlink`. `grep -r` and `rg` with `-w` ask `gdocs` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Not supported: `>`, `>>`, `tee`, `tee -a`, `touch` of a new file, `cp`, `cp -r`, `mkdir`, `rm -r`, `rmdir`, `truncate`, `sed -i`. 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. > ```` Documents are split into `owned` (documents you created) and `shared` (documents shared with you). The filename shape is: ```text theme={null} <YYYY-MM-DD>_<sanitized-title>__<document-id>.gdoc.json ``` If the modified date is unavailable, the date prefix is omitted. Reading a document file returns the full Google Docs API JSON for that document. ### Shared Drives The listing covers every corpus the account can reach, so a document that lives in a Shared Drive appears here too. A Shared Drive document has no owner (the drive owns it), so it lands under `shared`, which is what that directory means. This matches the `gdrive` mount, where Shared Drives are top-level directories: without it the same account would see a document under one Google mount and not the other, with no error explaining the difference. Drive answers an all-corpora search best-effort. When it reports that it skipped a corpus, the short listing is still returned but is not cached as the directory, so the next `ls` re-lists instead of serving the gap until the cache expires. ## Cache The Google Docs VFS uses `IndexCacheStore`. Index entries store document IDs and metadata. File bytes go through the workspace file cache; a rendered read through FUSE, `ws.vfs`, a `< file` redirect or a cross-mount `cp`, `sed` or `diff` is not cached. ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.commands.cli.builtin.gws import GWS from mirage.vfs.gdocs import GDocsConfig, GDocsVFS load_dotenv(".env.development") config = GDocsConfig( client_id=os.environ["GOOGLE_CLIENT_ID"], client_secret=os.environ["GOOGLE_CLIENT_SECRET"], refresh_token=os.environ["GOOGLE_REFRESH_TOKEN"], ) vfs = GDocsVFS(config=config) async def main(): ws = Workspace({"/gdocs": vfs}, mode=MountMode.READ) ws.register_cli("gws", GWS, config) # List structure r = await ws.shell("ls /gdocs/") print(await r.stdout_str()) # List owned documents r = await ws.shell("ls /gdocs/owned/") print(await r.stdout_str()) # Read a document r = await ws.shell( "cat /gdocs/owned/2026-04-04_Project_Plan__1AbCdEf.gdoc.json") print(await r.stdout_str()) # Extract title with jq r = await ws.shell( 'jq ".title"' " /gdocs/owned/2026-04-04_Project_Plan__1AbCdEf.gdoc.json") print(await r.stdout_str()) # Search across all documents r = await ws.shell('rg "quarterly" /gdocs/owned/') print(await r.stdout_str()) # Tree view r = await ws.shell("tree -L 1 /gdocs/") print(await r.stdout_str()) # Create a new document r = await ws.shell( 'gws docs documents create --json \'{"title":"MIRAGE Example Doc"}\'') print(await r.stdout_str()) # Append text to a document r = await ws.shell( 'gws docs write --document 1AbCdEf --text "Appended via MIRAGE."') print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` See [`examples/python/vfs/gdocs/gdocs.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/vfs/gdocs/gdocs.py) for the full working example. ## Shell Commands Standard commands available on the mounted Google Docs tree: | Command | Notes | | - | - | | `ls` | List owned/shared documents | | `cat` | Read document JSON | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search | | `jq` | Query JSON fields | | `wc` | Line/word/byte counts | | `stat` | File metadata | | `find` | Recursive search | | `tree` | Directory tree view | | `basename` / `dirname` / `realpath` | Path utilities | | `nl` | Number lines | | `mv` | Retitle a document (`MountMode.WRITE`) | | `rm` | Delete a document (`MountMode.WRITE`) | ## Integration What Google Docs answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Google Docs | | - | - | | `grep -r`, `rg` | Drive full-text search, for whole words. It can miss words only in non-text values (fonts, links and ids) or split by styling. | `grep -rw` and `rg -w` read only the documents Drive full-text search names; every one is read when the search fails or finds nothing. A word the rendered JSON may hold whatever the text says is never asked: one with a digit, a property name or enum value of the Docs API (`paragraph`, `NORMAL_TEXT`), or a word every rendering carries (`https`, `arial`). `walk_limit: -1` in the mount's `"@all"` [command limit](/home/core/output-limits) reads every file instead, since Drive indexes a write some time after it lands and searches the file's text, so one whose JSON holds the word only in another value (a font, a link or image address, a tab title or an id), or only as part of a word styling splits into text runs (`snow` bold in `snowman`), can be left out. Acting on documents (appending text, raw API calls) goes through the [gws CLI](/python/cli/gws) when installed. # Google Drive Source: https://docs.mirage.strukto.ai/python/vfs/gdrive Mount Google Drive folders and files, including Docs, Sheets, and Slides, as a Mirage virtual filesystem. The Google Drive VFS exposes a Google Drive account as a virtual filesystem mounted at some prefix such as `/gdrive/`. For Google OAuth setup, see [Google Workspace Setup](/home/setup/google). ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.gdrive import GoogleDriveConfig, GoogleDriveVFS config = GoogleDriveConfig( client_id=os.environ["GOOGLE_CLIENT_ID"], client_secret=os.environ["GOOGLE_CLIENT_SECRET"], refresh_token=os.environ["GOOGLE_REFRESH_TOKEN"], ) vfs = GoogleDriveVFS(config=config) ws = Workspace({"/gdrive": vfs}, mode=MountMode.WRITE) ``` To mount a subfolder instead of the whole Drive, set `folder_id`. The mount root becomes that folder. The folder may live in My Drive, be shared with you, sit inside a Shared Drive, or be a Shared Drive id itself; the drive scope is resolved automatically. Scoped mounts do not surface other shared drives: ```python theme={null} config = GoogleDriveConfig( client_id=os.environ["GOOGLE_CLIENT_ID"], client_secret=os.environ["GOOGLE_CLIENT_SECRET"], refresh_token=os.environ["GOOGLE_REFRESH_TOKEN"], folder_id="1AbCdEfFolderId", ) ``` | Field | Description | | - | - | | `timeout` default `30` | 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. | | `access_token` secret | OAuth access token, or a callable that returns one. Takes precedence over `client_id` and `refresh_token`. | | `client_id` | Google OAuth client ID. Required with `refresh_token` when `access_token` is unset; mirage then mints and renews access tokens itself. | | `client_secret` secret | Google OAuth client secret, sent with the refresh-token grant. Omit it for a PKCE client. | | `refresh_token` secret | User's OAuth refresh token. Required with `client_id` when `access_token` is unset. | | `api_base` | One base URL that replaces every Google API host and the OAuth token endpoint, such as a test server. Unset uses Google's hosts. | | `folder_id` | 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. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Google Drive mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `gdrive`, write | > > #### 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 > ``` > > * There is no `owned/` and `shared/` split: this is your full Drive > view, including files shared with you that were added to My Drive. > * This is a remote mount: prefer targeted reads over full scans. A > date-prefixed glob (`2026-05-*`) becomes a Drive `modifiedTime` range > query. > * To act on Drive items by id (create, update, export, permissions), use > the `gws` CLI if installed (`gws drive --help`). > > #### 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`, write | > > ## 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 > ``` > > - There is no `owned/` and `shared/` split: this is your full Drive > view, including files shared with you that were added to My Drive. > - This is a remote mount: prefer targeted reads over full scans. A > date-prefixed glob (`2026-05-*`) becomes a Drive `modifiedTime` range > query. > - To act on Drive items by id (create, update, export, permissions), use > the `gws` CLI if installed (`gws drive --help`). > > ## 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. > ```` The mount mirrors the actual Google Drive folder hierarchy. The root contains the Drive API `root` folder plus each Shared Drive visible to the user. Shared Drives appear as top-level directories. Duplicate names receive a `[Shared Drive]` suffix and, when needed, a numeric suffix. Subfolders appear as directories, and regular files keep their original names. ### Synthetic Extensions Google Workspace files cannot be downloaded as raw bytes, so they are exposed with synthetic extensions and read via their respective APIs: | Extension | Type | Read via | | - | - | - | | `.gdoc.json` | Google Docs | Docs API | | `.gsheet.json` | Google Sheets | Sheets API | | `.gslide.json` | Google Slides | Slides API | Regular files (PDFs, images, CSVs, etc.) are downloaded directly from Drive. Large regular files use streaming. ## Write Support Under `MountMode.WRITE` the standard write commands work on regular files and folders: `tee`, `cp`, `mv`, `rm`, `mkdir`, `rmdir`, `touch`, `truncate`, and in-place editors such as `sed -i`. Semantics follow the other object-store mounts (GNU check-then-act: `EEXIST` on mkdir over an existing name, `mv` onto a non-empty directory fails with `ENOTEMPTY`, `cp -r` merges). Google-native files (`.gdoc.json`, `.gsheet.json`, `.gslide.json`) are read-only as bytes; writing to them fails with `EACCES`. Mutate them through the `gws` commands below instead. Drive access is per-item (shared-drive roles, folder-level grants), so a write mount can still hold items you may not edit. A mutation the API denies fails with `EACCES` (Permission denied) on that operand, like a real filesystem; the rest of the mount keeps working. A write records the `md5Checksum` (else the `headRevisionId`) its upload reply names, so a `fresh` read right after a `tee` or `sed -i` downloads nothing. Use `MountMode.EXEC` if `python3` or `js` should run scripts from the mount. ### Writing inside a Shared Drive A Shared Drive is not a read-only corner of the mount. Every Drive call mirage makes carries `supportsAllDrives`, so create, write, rename, copy and delete work the same inside a Shared Drive as in My Drive, and the commands above behave identically there. What you may actually do is decided by Drive, not by mirage: a Shared Drive has its own role model (`viewer`, `commenter`, `contributor`, `content manager`, `manager`), and some organizations restrict deletion or moving content out of the drive. mirage does not attempt to predict those rules. It issues the operation and reports the answer, so a role that forbids the change fails with `EACCES` on that operand, exactly like an unwritable item in My Drive. The practical consequence is that a write mount spanning Shared Drives is partly writable, and the boundary follows your roles rather than the mount. If you want a mount that cannot write at all, use `MountMode.READ`; if you want to scope one to a single drive, set `folder_id` to the Shared Drive id. ## Snapshots The VFS supports workspace snapshots. Recorded reads capture the file's Drive revision (`headRevisionId`), and a loaded snapshot pins reads to that revision via the Drive Revisions API, so replay serves the exact bytes the agent saw. A path the agent wrote carries its write's token and no revision: loading checks the live file against that token, and replay reads the live file rather than a pinned revision. Google Docs, Sheets and Slides files carry no revision: loading checks them against the live file instead. ## Cache The Google Drive VFS uses `IndexCacheStore` (same as Slack, Gmail, and other mounts). Index entries store folder IDs, file IDs, and file metadata. File bytes go through the workspace file cache. ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.commands.cli.builtin.gws import GWS from mirage.vfs.gdrive import GoogleDriveConfig, GoogleDriveVFS load_dotenv(".env.development") config = GoogleDriveConfig( client_id=os.environ["GOOGLE_CLIENT_ID"], client_secret=os.environ["GOOGLE_CLIENT_SECRET"], refresh_token=os.environ["GOOGLE_REFRESH_TOKEN"], ) vfs = GoogleDriveVFS(config=config) async def main(): ws = Workspace({"/gdrive": vfs}, mode=MountMode.WRITE) ws.register_cli("gws", GWS, config) # List root r = await ws.shell("ls /gdrive/ | head -n 10") print(await r.stdout_str()) # Browse a subfolder r = await ws.shell("ls /gdrive/Projects/") print(await r.stdout_str()) # Read a regular file r = await ws.shell("cat /gdrive/Projects/spec.pdf | head -c 200") print(await r.stdout_str()) # Read a Google Doc title r = await ws.shell('jq ".title" /gdrive/Notes/meeting.gdoc.json') print(await r.stdout_str()) # Read a Google Sheet title r = await ws.shell( 'jq ".properties.title" /gdrive/Projects/roadmap.gsheet.json') print(await r.stdout_str()) # Read a Google Slides deck length r = await ws.shell( 'jq ".slides | length"' " /gdrive/Presentations/quarterly_review.gslide.json") print(await r.stdout_str()) # Search across all files r = await ws.shell('rg "quarterly" /gdrive/Projects/') print(await r.stdout_str()) # Tree view r = await ws.shell("tree -L 2 /gdrive/") print(await r.stdout_str()) # Create a new Google Doc r = await ws.shell( "gws docs documents create" ' --json \'{"title": "New Doc from MIRAGE"}\'') print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` See [`examples/python/vfs/gdrive/gdrive.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/vfs/gdrive/gdrive.py) for the full working example. ## Shell Commands Standard commands available on the mounted Google Drive tree: | Command | Notes | | - | - | | `ls` | List folders and files | | `cat` | Read file content (regular or Workspace) | | `head` / `tail` | First/last N lines or bytes | | `grep` / `rg` | Pattern search (file or directory level) | | `jq` | Query JSON fields on Workspace files | | `wc` | Line/word/byte counts | | `stat` | File metadata (name, size, type) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `basename` | Extract filename from path | | `dirname` | Extract directory from path | | `realpath` | Resolve path to absolute form | | `nl` | Number lines of output | | `sort` | Sort lines | | `uniq` | Deduplicate adjacent lines | | `cut` | Extract fields/columns | | `awk` | Pattern-directed scanning | | `sed` | Stream editor | | `tr` | Translate/delete characters | | `diff` | Compare two files | | `rev` | Reverse lines | | `tac` | Reverse file line order | | `paste` | Merge lines of files | | `join` | Join lines on a common field | | `column` | Columnate output | | `comm` | Compare sorted files line by line | | `fold` | Wrap lines to a given width | | `fmt` | Reformat paragraph text | | `expand` | Convert tabs to spaces | | `unexpand` | Convert spaces to tabs | | `du` | Estimate file space usage | | `shuf` | Randomly permute lines | | `look` | Display lines beginning with a prefix | | `strings` | Extract printable strings from binary | | `base64` | Base64 encode/decode | | `md5` | MD5 checksum | | `sha256sum` | SHA-256 checksum | | `xxd` | Hex dump | | `zcat` | Read compressed files | | `zgrep` | Search compressed files | | `readlink` | Print resolved symbolic links | | `cmp` | Compare two files byte by byte | | `tsort` | Topological sort | | `file` | Detect file type | ## Integration What Google Drive answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Google Drive | | - | - | | `grep -r`, `rg` | Drive full-text search, for whole words (`-w`, `-x`). It can miss Docs, Sheets and Slides JSON, office files, PDFs, archives, the end of large files, words Drive splits differently (`foo.bar`) and recent writes. | | `md5sum`, `sha1sum`, `sha256sum` | The digest Drive keeps; a Docs, Sheets or Slides file is read | | `find`, `du`, `ls -R`, `tree` | One recursive listing | `grep -rw` and `rg -w` read only the files Drive full-text search names; every file is read when the search fails or finds nothing. `walk_limit: -1` in the mount's `"@all"` [command limit](/home/core/output-limits) reads every file instead, since Drive searches the text it extracted, not the bytes `grep` reads, and indexes a write some time after it lands, so a file that holds the word can be left out: 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`). ## Acting on Drive Acting on Drive files by id (create, update, copy, delete, share, export, plus the Docs/Sheets/Slides helpers) goes through the [gws CLI](/python/cli/gws) when installed. # GitHub Source: https://docs.mirage.strukto.ai/python/vfs/github Mount a GitHub repository as a read-only Mirage filesystem for agents to list, read, search, and inspect code. The GitHub VFS uses GitHub's [REST API](https://docs.github.com/en/rest) to mount a repository as a read-only virtual filesystem. It does not imitate another CLI. For token setup, see [GitHub Setup](/home/setup/github). ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.github import GitHubConfig, GitHubVFS config = GitHubConfig(token=os.environ["GITHUB_TOKEN"]) vfs = GitHubVFS( config=config, owner="my-org", repo="my-repo", ref="main") ws = Workspace({"/github": vfs}, mode=MountMode.READ) ``` | Field | Description | | - | - | | `timeout` default `30` | 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. | | `token` required, secret | GitHub personal access token. | | `owner` | Repository owner, a user or an organization. Required unless the `GitHubVFS` constructor is given `owner`. | | `repo` | Repository name. Required unless the `GitHubVFS` constructor is given `repo`. | | `ref` | Branch, tag or commit SHA the mount reads. Unset follows the repository's default branch, resolved on the first read. | | `base_url` | GitHub API root. Unset uses `https://api.github.com`; set it for GitHub Enterprise. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with GitHub mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `github`, read | > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` with `-w` ask `github` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. Without `-w`, `grep -r` and `rg` read every file. `grep -r`, `find` and `du` stop after 5000 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>` | `github`, read | > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` with `-w` ask `github` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. Without `-w`, `grep -r` and `rg` read every file. `grep -r`, `find` and `du` stop after 5000 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. > ``` ```text theme={null} /github/ README.md pyproject.toml src/ __init__.py main.py utils.py models/ user.py item.py tests/ test_main.py ``` The filesystem mirrors the repository tree. No owner/repo/branch in the path - those are specified at mount time. ## Tree Fetching The full recursive tree is fetched on the first read, not at mount time, so constructing the VFS never blocks on the network. For repos with > 100K entries, it falls back to per-directory fetching. ## Cache The GitHub VFS uses `IndexCacheStore` with SHA-based fingerprinting. Content is content-addressed - if the SHA matches, the content is identical. Under `read: fresh`, a cached listing is checked against the head commit the `ref` resolves to: one small check per command (a shallow `git/trees/{ref}`), after which every cached listing of the mount at that commit is served. A mount whose `ref` is a full 40- or 64-hex commit sha serves its cached listings with no request: github.com refuses a branch or tag named with 40 or 64 hex characters, so such a ref always names a commit (a GitHub Enterprise host is assumed to do the same). A repository whose recursive tree comes back truncated stores no version, so each folder is re-listed once per command. ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.vfs.github import GitHubConfig, GitHubVFS load_dotenv(".env.development") async def main(): config = GitHubConfig(token=os.environ["GITHUB_TOKEN"]) vfs = GitHubVFS( config=config, owner="my-org", repo="my-repo", ref="main") ws = Workspace({"/github": vfs}, mode=MountMode.READ) # List repository root r = await ws.shell("ls /github/") print(await r.stdout_str()) # Read a file r = await ws.shell("cat /github/README.md") print(await r.stdout_str()) # Search for a pattern r = await ws.shell('rg "def main" /github/') print(await r.stdout_str()) # Tree view r = await ws.shell("tree -L 2 /github/") print(await r.stdout_str()) # File metadata with SHA r = await ws.shell("stat /github/README.md") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` See [`examples/python/vfs/github/github.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/vfs/github/github.py) for the full working example. ## Finding SHAs Git blob SHAs are available via the `stat` command: ```bash theme={null} stat /github/README.md # -> extra={"sha": "a1b2c3d4e5f6..."} stat /github/src/main.py # -> extra={"sha": "f6e5d4c3b2a1..."} ``` ## Working with Large Repos Tips for efficient access on large repositories: ```bash theme={null} # Find files by name find /github/ -name "*.py" # Search whole words with rg (uses GitHub code search on large repos) rg -w "TODO" /github/ # Read only the first lines of a file head -n 20 /github/src/main.py # Check file sizes du /github/src/ # List deeply nested directories tree -L 3 /github/src/ ``` ## Shell Commands Standard commands available on the mounted GitHub tree: | Command | Notes | | - | - | | `ls` | List files and directories | | `cat` | Read file contents | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search; see [grep and rg](#integration) | | `jq` | Query JSON files | | `wc` | Line/word/byte counts | | `stat` | File metadata including git SHA | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `diff` | Compare files | | `du` | Disk usage / file sizes | | `awk` | Text processing | | `sed` | Stream editing | | `sort` | Sort lines | | `uniq` | Deduplicate lines | | `cut` | Extract columns | | `tr` | Translate characters | | `nl` | Number lines | | `md5` | MD5 checksum | | `sha256sum` | SHA-256 checksum | | `file` | Detect file type | | `basename` | Strip directory from path | | `dirname` | Strip filename from path | | `realpath` | Resolve path | ## Integration What GitHub answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On GitHub | | - | - | | `grep -r`, `rg` | GitHub code search, for whole words, on the default branch, under a path with more than 100 files. It can miss recent pushes. | | `find`, `du`, `ls -R`, `tree` | One recursive tree listing | `grep -rw` and `rg -w` read only the files GitHub code search names when: * the scope holds more than 100 files; a smaller one is read directly, * the mounted ref is the default branch, the only one code search indexes, * the repository tree was listed in full, * and the search returns every hit, 100 at most. Every file is read otherwise. Files code search never indexes are always read. Each file is one request, so `grep -r`, `git grep`, `find` and the other walks stop after `walk_limit` files (default 5000) and keep what they printed, and a glob matching more, `tar -c`, `cp -r`, `rm -r` and the [other whole-tree commands](/home/integration/search#walk_limit) are refused above it: ```bash theme={null} $ grep -r TODO /github/ /github/src/main.py:# TODO: retry grep: /github/: stopped after 5000 files (walk_limit); narrow the path ``` # Gmail Source: https://docs.mirage.strukto.ai/python/vfs/gmail Mount Gmail mailboxes as a Mirage filesystem so Python agents can browse labels, messages, and attachments. The Gmail VFS exposes a Gmail account as a virtual filesystem mounted at some prefix such as `/gmail/`. For Google OAuth setup, see [Google Workspace Setup](/home/setup/google). ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.gmail import GmailConfig, GmailVFS config = GmailConfig( client_id=os.environ["GOOGLE_CLIENT_ID"], client_secret=os.environ["GOOGLE_CLIENT_SECRET"], refresh_token=os.environ["GOOGLE_REFRESH_TOKEN"], ) vfs = GmailVFS(config=config) ws = Workspace({"/gmail": vfs}, mode=MountMode.READ) ``` | Field | Description | | - | - | | `timeout` default `30` | 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. | | `access_token` secret | OAuth access token, or a callable that returns one. Takes precedence over `client_id` and `refresh_token`. | | `client_id` | Google OAuth client ID. Required with `refresh_token` when `access_token` is unset; mirage then mints and renews access tokens itself. | | `client_secret` secret | Google OAuth client secret, sent with the refresh-token grant. Omit it for a PKCE client. | | `refresh_token` secret | User's OAuth refresh token. Required with `client_id` when `access_token` is unset. | | `api_base` | One base URL that replaces every Google API host and the OAuth token endpoint, such as a test server. Unset uses Google's hosts. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Gmail mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `gmail`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > <label>/ > <yyyy-mm-dd>/ > <subject>__<message-id>.gmail.json # the email, body included > <subject>__<message-id>/ # its attachments, if any > <attachment-filename> > ``` > > * `<label>` is a Gmail label: `INBOX`, `SENT`, `DRAFT`, `IMPORTANT`, > `STARRED`, `TRASH`, `SPAM` or any user label. > * `<yyyy-mm-dd>` is the date the message was received. Listing one > (`ls /<path>/INBOX/2026-05-03/`) pushes `after:`/`before:` into the > Gmail query, much cheaper than scanning the whole label. > * `<subject>` is sanitized: `ls` the date directory rather than > construct it. `<message-id>` is the Gmail message id. > * The email body is in the `.gmail.json` file; read it with `cat`, > `head` or `jq`, keeping the suffix. The sibling directory, the same > name without the extension, holds attachments only: `cat` one to > download its bytes. `grep -r` over a date directory skips these binary > files. > * A `grep` or `rg` hit names the `.gmail.json` file, not the attachments > directory. To list a message's attachments, `ls` its path with > `.gmail.json` stripped; `ENOENT` means it has none: > `ls /<path>/INBOX/2026-05-03/<subject>__<message-id>/` > > A `.gmail.json` is processed by Mirage, not the raw Gmail API response: > > ```jsonc theme={null} > { > "id": "...", > "thread_id": "...", > "from": { "name": "...", "email": "..." }, > "to": [ { "name": "...", "email": "..." } ], > "cc": [ ... ], > "subject": "...", > "date": "Mon, 3 May 2026 10:00:00 -0700", > "body_text": "decoded plain-text body", > "snippet": "first ~200 chars from Gmail", > "labels": [ "INBOX", "IMPORTANT", ... ], > "attachments": [ > { "id": "...", "filename": "invoice.pdf", > "mime_type": "application/pdf", "size": 12345 } > ] > } > ``` > > Useful `jq` paths: > > ```jq theme={null} > .subject > .from.email > .body_text > .labels[] > .attachments[] | .filename > ``` > > To act on messages (read by id, triage, raw API calls), use the `gws` > CLI if installed (`gws gmail --help`). > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `gmail` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `gmail` answers only for `*/*/*.gmail.json`; `grep -r` and `rg` read every other 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>` | `gmail`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > <label>/ > <yyyy-mm-dd>/ > <subject>__<message-id>.gmail.json # the email, body included > <subject>__<message-id>/ # its attachments, if any > <attachment-filename> > ``` > > - `<label>` is a Gmail label: `INBOX`, `SENT`, `DRAFT`, `IMPORTANT`, > `STARRED`, `TRASH`, `SPAM` or any user label. > - `<yyyy-mm-dd>` is the date the message was received. Listing one > (`ls /<path>/INBOX/2026-05-03/`) pushes `after:`/`before:` into the > Gmail query, much cheaper than scanning the whole label. > - `<subject>` is sanitized: `ls` the date directory rather than > construct it. `<message-id>` is the Gmail message id. > - The email body is in the `.gmail.json` file; read it with `cat`, > `head` or `jq`, keeping the suffix. The sibling directory, the same > name without the extension, holds attachments only: `cat` one to > download its bytes. `grep -r` over a date directory skips these binary > files. > - A `grep` or `rg` hit names the `.gmail.json` file, not the attachments > directory. To list a message's attachments, `ls` its path with > `.gmail.json` stripped; `ENOENT` means it has none: > `ls /<path>/INBOX/2026-05-03/<subject>__<message-id>/` > > A `.gmail.json` is processed by Mirage, not the raw Gmail API response: > > ```jsonc > { > "id": "...", > "thread_id": "...", > "from": { "name": "...", "email": "..." }, > "to": [ { "name": "...", "email": "..." } ], > "cc": [ ... ], > "subject": "...", > "date": "Mon, 3 May 2026 10:00:00 -0700", > "body_text": "decoded plain-text body", > "snippet": "first ~200 chars from Gmail", > "labels": [ "INBOX", "IMPORTANT", ... ], > "attachments": [ > { "id": "...", "filename": "invoice.pdf", > "mime_type": "application/pdf", "size": 12345 } > ] > } > ``` > > Useful `jq` paths: > > ```jq > .subject > .from.email > .body_text > .labels[] > .attachments[] | .filename > ``` > > To act on messages (read by id, triage, raw API calls), use the `gws` > CLI if installed (`gws gmail --help`). > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `gmail` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `gmail` answers only for `*/*/*.gmail.json`; `grep -r` and `rg` read every other 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. > ```` Label directories appear at the root. System labels use the Gmail label ID (e.g., `INBOX`, `SENT`, `STARRED`). User-created labels use their label name as is. ### Date Directories Inside each label, messages are grouped into date subdirectories formatted as `YYYY-MM-DD`. The date is derived from the message's `internalDate` (epoch milliseconds) converted to a calendar date. ### Message Files Each message is stored as a `.gmail.json` file. The filename shape is: ```text theme={null} <sanitized-subject>__<message-id>.gmail.json ``` Subjects are sanitized for filesystem safety and truncated when necessary. The message ID is embedded after `__` and before `.gmail.json`. ### Attachments Messages that have attachments get a companion subdirectory with the same base name (without `.gmail.json`). Decoded attachment files are placed inside: ```text theme={null} Meeting_Notes__msg123.gmail.json # message JSON Meeting_Notes__msg123/ # attachment directory report.pdf screenshot.png ``` ## Cache The Gmail VFS uses `IndexCacheStore` (same as Slack, Discord, and other mounts). Index entries store label IDs, message IDs, and message metadata. File bytes go through the workspace file cache. ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.commands.cli.builtin.gws import GWS from mirage.vfs.gmail import GmailConfig, GmailVFS load_dotenv(".env.development") config = GmailConfig( client_id=os.environ["GOOGLE_CLIENT_ID"], client_secret=os.environ["GOOGLE_CLIENT_SECRET"], refresh_token=os.environ["GOOGLE_REFRESH_TOKEN"], ) vfs = GmailVFS(config=config) async def main(): ws = Workspace({"/gmail": vfs}, mode=MountMode.READ) ws.register_cli("gws", GWS, config) # List labels r = await ws.shell("ls /gmail/") print(await r.stdout_str()) # List date directories in INBOX r = await ws.shell("ls /gmail/INBOX/") print(await r.stdout_str()) # List messages for a specific date r = await ws.shell("ls /gmail/INBOX/2026-04-12/") print(await r.stdout_str()) # Read a message r = await ws.shell( "cat /gmail/INBOX/2026-04-12/Meeting_Notes__msg123.gmail.json") print(await r.stdout_str()) # Extract subject with jq r = await ws.shell( 'jq ".subject"' " /gmail/INBOX/2026-04-12/Meeting_Notes__msg123.gmail.json") print(await r.stdout_str()) # List attachments r = await ws.shell("ls /gmail/INBOX/2026-04-12/Meeting_Notes__msg123/") print(await r.stdout_str()) # Search across all messages r = await ws.shell('rg "quarterly" /gmail/INBOX/') print(await r.stdout_str()) # Tree view r = await ws.shell("tree -L 2 /gmail/INBOX/") print(await r.stdout_str()) # Triage unread messages r = await ws.shell('gws gmail triage --query "is:unread" --max 5') print(await r.stdout_str()) # Send an email r = await ws.shell( 'gws gmail send --to "user@example.com"' ' --subject "Hello from MIRAGE"' ' --body "This email was sent via the MIRAGE Gmail VFS."') print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` See [`examples/python/vfs/gmail/gmail.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/vfs/gmail/gmail.py) for the full working example. ## Finding IDs VFS-specific commands require message IDs. These can be extracted from the filesystem: ```bash theme={null} # Message ID -- embedded in filename after "__" ls /gmail/INBOX/2026-04-12/ # -> Meeting_Notes__msg123.gmail.json <- message_id = msg123 # Extract message ID from filename basename /gmail/INBOX/2026-04-12/Meeting_Notes__msg123.gmail.json .gmail.json # -> Meeting_Notes__msg123 # The part after "__" is the message ID: msg123 # Read a message then reply gws gmail read --id msg123 gws gmail reply --message-id msg123 --body "Thanks for the notes" ``` ## Working with Large Labels Labels with many messages are split into date directories. A bare `ls` of a label lists the days of its 50 most recent messages; a glob over the date names (`ls /gmail/INBOX/2026-03-*`) or a date directory by name reaches older days. Tips for efficient access: ```bash theme={null} # List available dates ls /gmail/INBOX/ # Check message count for a specific date ls /gmail/INBOX/2026-04-12/ | wc -l # Read only the most recent date ls /gmail/INBOX/ | tail -n 1 # Search across all dates in a label rg "keyword" /gmail/INBOX/ # Extract specific fields to reduce output jq -r '.subject' /gmail/INBOX/2026-04-12/*.gmail.json | head -n 20 # Find messages with attachments find /gmail/INBOX/2026-04-12/ -type d # Tree view of a label tree -L 2 /gmail/INBOX/ ``` ## Shell Commands Standard commands available on the mounted Gmail tree: | Command | Notes | | - | - | | `ls` | List labels, dates, messages, attachments | | `cat` | Read message JSON or attachment content | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search (file or directory level) | | `jq` | Query message JSON fields | | `wc` | Line/word/byte counts | | `stat` | File metadata (name, size, type) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `basename` | Extract filename from path | | `dirname` | Extract directory from path | | `realpath` | Resolve path to absolute form | | `nl` | Number lines of output | Acting on Gmail (send, reply, forward, triage, raw API calls) goes through the [gws CLI](/python/cli/gws) when installed. ## Integration What Gmail answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Gmail | | - | - | | `grep -r`, `rg` | The message text the listing keeps, for ASCII text. It misses nothing. | The listing keeps each message's text, and `grep -r` and `rg` read only the messages whose text holds the pattern's text in any case, printing what reading every message would. Listing a label already fetches its messages in full, so this asks Gmail nothing more and saves the second fetch of each message it rules out. Gmail's own search is not used: it reads the HTML part of a message and can miss a word of the plain-text body a `.gmail.json` holds, such as one inside a link. Attachments are always read, and so is every message for a text that is not ASCII, or that may be part of the labels field (`inbox`, `STARRED`, `Label_1`, `abel`), since a message's labels change after the listing kept its text. With `walk_limit: -1` in the mount's `"@all"` [command limit](/home/core/output-limits), the listing keeps no message text, and every message is read. # GridFS Source: https://docs.mirage.strukto.ai/python/vfs/gridfs Mount a MongoDB GridFS bucket as a Mirage filesystem with revisions, server-side find, and shell commands. The GridFS VFS mounts a MongoDB GridFS bucket at some prefix such as `/gridfs/`. Files are stored inside MongoDB itself: metadata in the `<bucket>.files` collection, content in 255KB chunks in `<bucket>.chunks`. Uses pymongo's native async API. Install the extra: ```bash theme={null} pip install "mirage-ai[gridfs]" ``` ## Config ```python theme={null} from mirage import MountMode, Workspace from mirage.vfs.gridfs import GridFSVFS, GridFSConfig config = GridFSConfig( uri="mongodb://localhost:27017", database="app", # Optional: # bucket="fs", # GridFS bucket name (default "fs") # key_prefix="users/alice", # scope the mount to a subpath # chunk_size_bytes=261120, # default 255KB ) vfs = GridFSVFS(config) ws = Workspace({"/gridfs": vfs}, mode=MountMode.WRITE) ``` Both `READ` and `WRITE` modes are supported. Small files are fine: a file smaller than the chunk size is stored as a single chunk document, so tiny config files and large binaries go through the same path. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `uri` required, secret | MongoDB connection URI. | | `database` required | Database that holds the GridFS bucket. | | `bucket` default `'fs'` | GridFS bucket name; its collections are `<bucket>.files` and `<bucket>.chunks`. | | `key_prefix` | Filename prefix the mount treats as its root; files outside it are not listed. | | `chunk_size_bytes` | Chunk size in bytes for files the mount writes; unset uses the driver's default, 255 KiB. | | `keep_revisions` | Revisions kept per file, newest first: a write or an `rm` deletes the rest, under the file's name and in the trash `rm` moves revisions to (`/trash/<filename>`, which no mount path reaches). Unset keeps every revision, so a snapshot pinned to any of them still reads. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with GridFS mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` GridFS filenames are used as slash-separated keys, exactly like S3 object keys. Directories are prefix-based; `mkdir` creates a zero-byte `key/` marker document so empty directories stay visible. ```text theme={null} data/file.txt data/config.json reports/q1.csv ``` mounted at `/gridfs/` exposes: ```text theme={null} /gridfs/ data/ file.txt config.json reports/ q1.csv ``` ## Revisions GridFS filenames are not unique: every write uploads a **new revision** and keeps the old ones. The VFS always reads and lists the newest revision per filename, and snapshot-pinned reads resolve old revisions by their file `_id`, so time-travel reads work natively. `mv` retags every revision's filename server-side (history moves with the file). `rm` destroys nothing: it retags every revision of the file into the trash, `/trash/<filename>`, the same way `mv` does. A mount key never starts with a slash, so no path on any mount, whatever its `key_prefix`, can list, stat or read a trashed revision, and the name reads as gone; a snapshot pinned to one of those revisions still stats and reads it by its `_id`. A file `mv` overwrites goes to the trash the same way. The trash keeps the whole original filename, so a revision is traceable to the key it was written under. `keep_revisions` bounds the history. Set it, and a write or an `rm` deletes the revisions past that count per filename, oldest first, under the file's name and under its trash name alike; a snapshot pinned to a pruned revision then fails to read it. Unset, the default, keeps every revision. ```python theme={null} GridFSConfig(uri=..., database="app", keep_revisions=5) ``` ## Walks GridFS metadata lives in an ordinary MongoDB collection, so a walk (`find`, `du`, `ls -R`, `tree`, `grep -r`, `rg`, `cp -r`) reads every file under the start directory with one `fs.files` query and answers each directory below it from that answer. See [Walks](/home/integration/walks). ## Cache The GridFS VFS uses `IndexCacheStore` with `index_ttl = 600` (10 minutes). Directory listings are cached before being refreshed from MongoDB, reducing queries for repeated traversals. A configured `index:` replaces this lifetime with its own `ttl`, and the mount's `ttl:` caps it. ## Integration What GridFS answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On GridFS | | - | - | | `find`, `du`, `ls -R`, `tree` | One recursive listing | ## Example ```python theme={null} import asyncio from mirage import MountMode, Workspace from mirage.vfs.gridfs import GridFSVFS, GridFSConfig config = GridFSConfig( uri="mongodb://localhost:27017", database="app", bucket="assets", ) vfs = GridFSVFS(config) async def main() -> None: ws = Workspace({"/gridfs/": vfs}, mode=MountMode.WRITE) await ws.shell("echo hello | tee /gridfs/notes/a.txt > /dev/null") r = await ws.shell("ls /gridfs/") print(await r.stdout_str()) r = await ws.shell("cat /gridfs/notes/a.txt") print(await r.stdout_str()) r = await ws.shell("find /gridfs/ -name '*.txt'") print(await r.stdout_str()) r = await ws.shell("grep hello /gridfs/notes/a.txt") print(await r.stdout_str()) r = await ws.shell("stat /gridfs/notes/a.txt") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Shell Commands The GridFS VFS supports the same full command surface as the [S3 VFS](/python/vfs/s3): read commands (`cat`, `head`, `tail`, `grep`, `rg`, `jq`, `wc`, `stat`, `find`, `tree`, `du`, checksums), text processing (`awk`, `sed`, `sort`, `cut`, `diff`, ...), file operations (`cp`, `mv`, `rm`, `mkdir`, `touch`, `tee`, `split`, ...), compression, and encoding. Range reads (`head -c`, `tail -c`) seek chunk-wise, so large files are never downloaded whole. ## Scoping a VFS to a key prefix Pass `key_prefix` to `GridFSConfig` to transparently scope every operation to a subpath of the bucket, mirroring the S3 `key_prefix` behavior: ```python theme={null} GridFSVFS(GridFSConfig( uri="mongodb://localhost:27017", database="app", bucket="shared", key_prefix=f"users/{user_id}/", )) ``` Agents see clean paths like `/data/notes.md`; the underlying GridFS filename is `users/{user_id}/data/notes.md`. Leading slashes are stripped and a trailing slash is added automatically; `None` and an empty string mean "no prefix." ## Use Cases * **Files next to your data**: keep agent-visible files in the same MongoDB deployment as the rest of your application state, with one backup story * **Revision-aware storage**: writes never destroy old content; snapshots can pin reads to the exact revision they saw * **Cheap find on big buckets**: metadata queries replace full listings * **Multi-tenant mounts**: one bucket, per-tenant `key_prefix` scoping # Google Sheets Source: https://docs.mirage.strukto.ai/python/vfs/gsheets Mount Google Sheets spreadsheets as JSON-backed files that Python agents can read through Mirage shell commands. The Google Sheets VFS exposes Sheets spreadsheets as a virtual filesystem mounted at some prefix such as `/gsheets/`. For Google OAuth setup, see [Google Workspace Setup](/home/setup/google). ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.gsheets import GSheetsConfig, GSheetsVFS config = GSheetsConfig( client_id=os.environ["GOOGLE_CLIENT_ID"], client_secret=os.environ["GOOGLE_CLIENT_SECRET"], refresh_token=os.environ["GOOGLE_REFRESH_TOKEN"], ) vfs = GSheetsVFS(config=config) ws = Workspace({"/gsheets": vfs}, mode=MountMode.READ) ``` | Field | Description | | - | - | | `timeout` default `30` | 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. | | `access_token` secret | OAuth access token, or a callable that returns one. Takes precedence over `client_id` and `refresh_token`. | | `client_id` | Google OAuth client ID. Required with `refresh_token` when `access_token` is unset; mirage then mints and renews access tokens itself. | | `client_secret` secret | Google OAuth client secret, sent with the refresh-token grant. Omit it for a PKCE client. | | `refresh_token` secret | User's OAuth refresh token. Required with `client_id` when `access_token` is unset. | | `api_base` | One base URL that replaces every Google API host and the OAuth token endpoint, such as a test server. Unset uses Google's hosts. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Google Sheets mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `gsheets`, write | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > owned/ # sheets you created > <YYYY-MM-DD>_<title>__<spreadsheet-id>.gsheet.json > shared/ # sheets others shared with you > <YYYY-MM-DD>_<title>__<spreadsheet-id>.gsheet.json > ``` > > * `<YYYY-MM-DD>` is the file's `modifiedTime`, so a date glob such as > `2026-05-*` narrows by it. > * `<title>` is sanitized: spaces and any character outside > `[A-Za-z0-9_.-]` become `_`, at most 100 characters. > * `<spreadsheet-id>` is the Google Sheets spreadsheet id. > * `shared/` holds sheets shared with you by others; ones you own > and shared with others are still in `owned/`. > > A `.gsheet.json` matches the Google Sheets API `spreadsheets.get` > response: > > ```jsonc theme={null} > { > "spreadsheetId": "...", > "spreadsheetUrl": "...", > "properties": { "title": "...", "locale": "...", "timeZone": "..." }, > "sheets": [ > { // one element per tab > "properties": { > "sheetId": 0, "title": "...", "index": 0, > "gridProperties": { "rowCount": 1000, "columnCount": 26 } > }, > "data": [ > { > "rowData": [ > { "values": [ > { "formattedValue": "...", > "userEnteredValue": {...}, > "effectiveValue": {...} } > ]} // an empty cell is {}, a trailing one absent > ] > } > ] > } > ], > "namedRanges": [...] > } > ``` > > Useful `jq` paths: > > ```jq theme={null} > .properties.title > .sheets[].properties.title # tab names > .sheets[0].data[0].rowData[].values[].formattedValue # cell strings > .namedRanges[] > ``` > > Delete, on a `write` path: > > ```sh theme={null} > rm /<path>/owned/<file>.gsheet.json # deletes it from Drive for good > rm -f <path> # ignores a missing file > ``` > > Only `.gsheet.json` files can be removed; `owned/` and `shared/` cannot. > > Rename to a new title, on a `write` path: > > ```sh theme={null} > mv /<path>/owned/<date>_<old>__<id>.gsheet.json \ > /<path>/owned/<date>_<new>__<id>.gsheet.json > ``` > > Keep the folder, the date and the id, and spell the title the way the > listing does (spaces become `_`); any other name is refused. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest), and `mv`, `rm` and `unlink`. `grep -r` and `rg` with `-w` ask `gsheets` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Not supported: `>`, `>>`, `tee`, `tee -a`, `touch` of a new file, `cp`, `cp -r`, `mkdir`, `rm -r`, `rmdir`, `truncate`, `sed -i`. 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>` | `gsheets`, write | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > owned/ # sheets you created > <YYYY-MM-DD>_<title>__<spreadsheet-id>.gsheet.json > shared/ # sheets others shared with you > <YYYY-MM-DD>_<title>__<spreadsheet-id>.gsheet.json > ``` > > - `<YYYY-MM-DD>` is the file's `modifiedTime`, so a date glob such as > `2026-05-*` narrows by it. > - `<title>` is sanitized: spaces and any character outside > `[A-Za-z0-9_.-]` become `_`, at most 100 characters. > - `<spreadsheet-id>` is the Google Sheets spreadsheet id. > - `shared/` holds sheets shared with you by others; ones you own > and shared with others are still in `owned/`. > > A `.gsheet.json` matches the Google Sheets API `spreadsheets.get` > response: > > ```jsonc > { > "spreadsheetId": "...", > "spreadsheetUrl": "...", > "properties": { "title": "...", "locale": "...", "timeZone": "..." }, > "sheets": [ > { // one element per tab > "properties": { > "sheetId": 0, "title": "...", "index": 0, > "gridProperties": { "rowCount": 1000, "columnCount": 26 } > }, > "data": [ > { > "rowData": [ > { "values": [ > { "formattedValue": "...", > "userEnteredValue": {...}, > "effectiveValue": {...} } > ]} // an empty cell is {}, a trailing one absent > ] > } > ] > } > ], > "namedRanges": [...] > } > ``` > > Useful `jq` paths: > > ```jq > .properties.title > .sheets[].properties.title # tab names > .sheets[0].data[0].rowData[].values[].formattedValue # cell strings > .namedRanges[] > ``` > > Delete, on a `write` path: > > ```sh > rm /<path>/owned/<file>.gsheet.json # deletes it from Drive for good > rm -f <path> # ignores a missing file > ``` > > Only `.gsheet.json` files can be removed; `owned/` and `shared/` cannot. > > Rename to a new title, on a `write` path: > > ```sh > mv /<path>/owned/<date>_<old>__<id>.gsheet.json \ > /<path>/owned/<date>_<new>__<id>.gsheet.json > ``` > > Keep the folder, the date and the id, and spell the title the way the > listing does (spaces become `_`); any other name is refused. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest), and `mv`, `rm` and `unlink`. `grep -r` and `rg` with `-w` ask `gsheets` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Not supported: `>`, `>>`, `tee`, `tee -a`, `touch` of a new file, `cp`, `cp -r`, `mkdir`, `rm -r`, `rmdir`, `truncate`, `sed -i`. 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. > ```` Spreadsheets are split into `owned` (spreadsheets you created) and `shared` (spreadsheets shared with you). The filename shape is: ```text theme={null} <YYYY-MM-DD>_<sanitized-title>__<spreadsheet-id>.gsheet.json ``` If the modified date is unavailable, the date prefix is omitted. Reading a spreadsheet file returns the full Google Sheets API JSON for that spreadsheet, including sheet metadata. ### Shared Drives The listing covers every corpus the account can reach, so a spreadsheet that lives in a Shared Drive appears here too. A Shared Drive spreadsheet has no owner (the drive owns it), so it lands under `shared`, which is what that directory means. This matches the `gdrive` mount, where Shared Drives are top-level directories: without it the same account would see a spreadsheet under one Google mount and not the other, with no error explaining the difference. Drive answers an all-corpora search best-effort. When it reports that it skipped a corpus, the short listing is still returned but is not cached as the directory, so the next `ls` re-lists instead of serving the gap until the cache expires. ## Cache The Google Sheets VFS uses `IndexCacheStore`. Index entries store spreadsheet IDs and metadata. File bytes go through the workspace file cache; a rendered read through FUSE, `ws.vfs`, a `< file` redirect or a cross-mount `cp`, `sed` or `diff` is not cached. ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.commands.cli.builtin.gws import GWS from mirage.vfs.gsheets import GSheetsConfig, GSheetsVFS load_dotenv(".env.development") config = GSheetsConfig( client_id=os.environ["GOOGLE_CLIENT_ID"], client_secret=os.environ["GOOGLE_CLIENT_SECRET"], refresh_token=os.environ["GOOGLE_REFRESH_TOKEN"], ) vfs = GSheetsVFS(config=config) async def main(): ws = Workspace({"/gsheets": vfs}, mode=MountMode.READ) ws.register_cli("gws", GWS, config) # List structure r = await ws.shell("ls /gsheets/") print(await r.stdout_str()) # List owned spreadsheets r = await ws.shell("ls /gsheets/owned/") print(await r.stdout_str()) # Read a spreadsheet r = await ws.shell( "cat /gsheets/owned/2026-04-04_Roadmap__1AbCdEf.gsheet.json") print(await r.stdout_str()) # Extract title with jq r = await ws.shell( 'jq ".properties.title"' " /gsheets/owned/2026-04-04_Roadmap__1AbCdEf.gsheet.json") print(await r.stdout_str()) # Search across all spreadsheets r = await ws.shell('rg "revenue" /gsheets/owned/') print(await r.stdout_str()) # Tree view r = await ws.shell("tree -L 1 /gsheets/") print(await r.stdout_str()) # Read cell values r = await ws.shell( 'gws sheets read --spreadsheet 1AbCdEf --range "Sheet1!A1:C3"') print(await r.stdout_str()) # Append rows r = await ws.shell( "gws sheets append --spreadsheet 1AbCdEf --values Alice,30,NYC") print(await r.stdout_str()) # Create a new spreadsheet r = await ws.shell( 'gws sheets spreadsheets create' ' --json \'{"properties":{"title":"MIRAGE Sheet"}}\'') print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` See [`examples/python/vfs/gsheets/gsheets.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/vfs/gsheets/gsheets.py) for the full working example. ## Shell Commands Standard commands available on the mounted Google Sheets tree: | Command | Notes | | - | - | | `ls` | List owned/shared spreadsheets | | `cat` | Read spreadsheet JSON | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search | | `jq` | Query JSON fields | | `wc` | Line/word/byte counts | | `stat` | File metadata | | `find` | Recursive search | | `tree` | Directory tree view | | `basename` / `dirname` / `realpath` | Path utilities | | `nl` | Number lines | | `mv` | Retitle a spreadsheet (`MountMode.WRITE`) | | `rm` | Delete a spreadsheet (`MountMode.WRITE`) | ## Integration What Google Sheets answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Google Sheets | | - | - | | `grep -r`, `rg` | Drive full-text search, for whole words. It can miss words only in non-text values (formulas, the time zone, sheet titles, links and ids). | `grep -rw` and `rg -w` read only the spreadsheets Drive full-text search names; every one is read when the search fails or finds nothing. A word the rendered JSON may hold whatever the text says is never asked: one with a digit, a property name or enum value of the Sheets API (`formattedValue`, `NUMBER`), or a word every rendering carries (`https`, `arial`). `walk_limit: -1` in the mount's `"@all"` [command limit](/home/core/output-limits) reads every file instead, since Drive indexes a write some time after it lands and searches the file's text, so one whose JSON holds the word only in another value (a formula, the time zone, a sheet title, a link or an id) can be left out. Acting on spreadsheets (read/write/append ranges, raw API calls) goes through the [gws CLI](/python/cli/gws) when installed. # Google Slides Source: https://docs.mirage.strukto.ai/python/vfs/gslides Mount Google Slides presentations as JSON-backed files that Python agents can read through Mirage shell commands. The Google Slides VFS exposes presentations as a virtual filesystem mounted at some prefix such as `/gslides/`. For Google OAuth setup, see [Google Workspace Setup](/home/setup/google). ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.gslides import GSlidesConfig, GSlidesVFS config = GSlidesConfig( client_id=os.environ["GOOGLE_CLIENT_ID"], client_secret=os.environ["GOOGLE_CLIENT_SECRET"], refresh_token=os.environ["GOOGLE_REFRESH_TOKEN"], ) vfs = GSlidesVFS(config=config) ws = Workspace({"/gslides": vfs}, mode=MountMode.READ) ``` | Field | Description | | - | - | | `timeout` default `30` | 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. | | `access_token` secret | OAuth access token, or a callable that returns one. Takes precedence over `client_id` and `refresh_token`. | | `client_id` | Google OAuth client ID. Required with `refresh_token` when `access_token` is unset; mirage then mints and renews access tokens itself. | | `client_secret` secret | Google OAuth client secret, sent with the refresh-token grant. Omit it for a PKCE client. | | `refresh_token` secret | User's OAuth refresh token. Required with `client_id` when `access_token` is unset. | | `api_base` | One base URL that replaces every Google API host and the OAuth token endpoint, such as a test server. Unset uses Google's hosts. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Google Slides mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `gslides`, write | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > owned/ # presentations you created > <YYYY-MM-DD>_<title>__<presentation-id>.gslide.json > shared/ # presentations others shared with you > <YYYY-MM-DD>_<title>__<presentation-id>.gslide.json > ``` > > * `<YYYY-MM-DD>` is the file's `modifiedTime`, so a date glob such as > `2026-05-*` narrows by it. > * `<title>` is sanitized: spaces and any character outside > `[A-Za-z0-9_.-]` become `_`, at most 100 characters. > * `<presentation-id>` is the Google Slides presentation id. > * `shared/` holds presentations shared with you by others; ones you own > and shared with others are still in `owned/`. > > A `.gslide.json` matches the Google Slides API `presentations.get` > response: > > ```jsonc theme={null} > { > "presentationId": "...", > "title": "...", > "pageSize": { "width": {...}, "height": {...} }, > "slides": [ > { // one element per slide > "objectId": "...", > "pageElements": [ > { > "objectId": "...", > "shape": { > "shapeType": "TEXT_BOX", > "text": { > "textElements": [ > { "textRun": { "content": "the actual text\n", > "style": {...} } } > ] > } > } > }, > { "image": {...} }, > { "table": {...} } > ] > } > ], > "masters": [...], > "layouts": [...] > } > ``` > > Useful `jq` paths: > > ```jq theme={null} > .title > .slides | length # slide count > .slides[].pageElements[].shape.text.textElements[].textRun.content # all text > .slides[0].objectId > ``` > > Delete, on a `write` path: > > ```sh theme={null} > rm /<path>/owned/<file>.gslide.json # deletes it from Drive for good > rm -f <path> # ignores a missing file > ``` > > Only `.gslide.json` files can be removed; `owned/` and `shared/` cannot. > > Rename to a new title, on a `write` path: > > ```sh theme={null} > mv /<path>/owned/<date>_<old>__<id>.gslide.json \ > /<path>/owned/<date>_<new>__<id>.gslide.json > ``` > > Keep the folder, the date and the id, and spell the title the way the > listing does (spaces become `_`); any other name is refused. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest), and `mv`, `rm` and `unlink`. `grep -r` and `rg` with `-w` ask `gslides` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Not supported: `>`, `>>`, `tee`, `tee -a`, `touch` of a new file, `cp`, `cp -r`, `mkdir`, `rm -r`, `rmdir`, `truncate`, `sed -i`. 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>` | `gslides`, write | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > owned/ # presentations you created > <YYYY-MM-DD>_<title>__<presentation-id>.gslide.json > shared/ # presentations others shared with you > <YYYY-MM-DD>_<title>__<presentation-id>.gslide.json > ``` > > - `<YYYY-MM-DD>` is the file's `modifiedTime`, so a date glob such as > `2026-05-*` narrows by it. > - `<title>` is sanitized: spaces and any character outside > `[A-Za-z0-9_.-]` become `_`, at most 100 characters. > - `<presentation-id>` is the Google Slides presentation id. > - `shared/` holds presentations shared with you by others; ones you own > and shared with others are still in `owned/`. > > A `.gslide.json` matches the Google Slides API `presentations.get` > response: > > ```jsonc > { > "presentationId": "...", > "title": "...", > "pageSize": { "width": {...}, "height": {...} }, > "slides": [ > { // one element per slide > "objectId": "...", > "pageElements": [ > { > "objectId": "...", > "shape": { > "shapeType": "TEXT_BOX", > "text": { > "textElements": [ > { "textRun": { "content": "the actual text\n", > "style": {...} } } > ] > } > } > }, > { "image": {...} }, > { "table": {...} } > ] > } > ], > "masters": [...], > "layouts": [...] > } > ``` > > Useful `jq` paths: > > ```jq > .title > .slides | length # slide count > .slides[].pageElements[].shape.text.textElements[].textRun.content # all text > .slides[0].objectId > ``` > > Delete, on a `write` path: > > ```sh > rm /<path>/owned/<file>.gslide.json # deletes it from Drive for good > rm -f <path> # ignores a missing file > ``` > > Only `.gslide.json` files can be removed; `owned/` and `shared/` cannot. > > Rename to a new title, on a `write` path: > > ```sh > mv /<path>/owned/<date>_<old>__<id>.gslide.json \ > /<path>/owned/<date>_<new>__<id>.gslide.json > ``` > > Keep the folder, the date and the id, and spell the title the way the > listing does (spaces become `_`); any other name is refused. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest), and `mv`, `rm` and `unlink`. `grep -r` and `rg` with `-w` ask `gslides` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Not supported: `>`, `>>`, `tee`, `tee -a`, `touch` of a new file, `cp`, `cp -r`, `mkdir`, `rm -r`, `rmdir`, `truncate`, `sed -i`. 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. > ```` Presentations are split into `owned` (presentations you created) and `shared` (presentations shared with you). The filename shape is: ```text theme={null} <YYYY-MM-DD>_<sanitized-title>__<presentation-id>.gslide.json ``` If the modified date is unavailable, the date prefix is omitted. Reading a presentation file returns the full Google Slides API JSON for that presentation. ### Shared Drives The listing covers every corpus the account can reach, so a presentation that lives in a Shared Drive appears here too. A Shared Drive presentation has no owner (the drive owns it), so it lands under `shared`, which is what that directory means. This matches the `gdrive` mount, where Shared Drives are top-level directories: without it the same account would see a presentation under one Google mount and not the other, with no error explaining the difference. Drive answers an all-corpora search best-effort. When it reports that it skipped a corpus, the short listing is still returned but is not cached as the directory, so the next `ls` re-lists instead of serving the gap until the cache expires. ## Cache The Google Slides VFS uses `IndexCacheStore`. Index entries store presentation IDs and metadata. File bytes go through the workspace file cache; a rendered read through FUSE, `ws.vfs`, a `< file` redirect or a cross-mount `cp`, `sed` or `diff` is not cached. ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.commands.cli.builtin.gws import GWS from mirage.vfs.gslides import GSlidesConfig, GSlidesVFS load_dotenv(".env.development") config = GSlidesConfig( client_id=os.environ["GOOGLE_CLIENT_ID"], client_secret=os.environ["GOOGLE_CLIENT_SECRET"], refresh_token=os.environ["GOOGLE_REFRESH_TOKEN"], ) vfs = GSlidesVFS(config=config) async def main(): ws = Workspace({"/gslides": vfs}, mode=MountMode.READ) ws.register_cli("gws", GWS, config) # List structure r = await ws.shell("ls /gslides/") print(await r.stdout_str()) # List owned presentations r = await ws.shell("ls /gslides/owned/") print(await r.stdout_str()) # Read a presentation r = await ws.shell( "cat /gslides/owned/2026-04-04_QBR_Deck__1AbCdEf.gslide.json") print(await r.stdout_str()) # Extract title with jq r = await ws.shell( 'jq ".title"' " /gslides/owned/2026-04-04_QBR_Deck__1AbCdEf.gslide.json") print(await r.stdout_str()) # Search across all presentations r = await ws.shell('rg "quarterly" /gslides/owned/') print(await r.stdout_str()) # Tree view r = await ws.shell("tree -L 1 /gslides/") print(await r.stdout_str()) # Create a new presentation r = await ws.shell( 'gws slides presentations create --json \'{"title":"MIRAGE Deck"}\'') print(await r.stdout_str()) # Batch update a presentation r = await ws.shell( 'gws slides presentations batchUpdate' ' --params \'{"presentationId":"1AbCdEf"}\'' ' --json \'{"requests":[]}\'') print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` See [`examples/python/vfs/gslides/gslides.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/vfs/gslides/gslides.py) for the full working example. ## Shell Commands Standard commands available on the mounted Google Slides tree: | Command | Notes | | - | - | | `ls` | List owned/shared presentations | | `cat` | Read presentation JSON | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search | | `jq` | Query JSON fields | | `wc` | Line/word/byte counts | | `stat` | File metadata | | `find` | Recursive search | | `tree` | Directory tree view | | `basename` / `dirname` / `realpath` | Path utilities | | `nl` | Number lines | | `mv` | Retitle a presentation (`MountMode.WRITE`) | | `rm` | Delete a presentation (`MountMode.WRITE`) | ## Integration What Google Slides answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Google Slides | | - | - | | `grep -r`, `rg` | Drive full-text search, for whole words. It can miss words only in non-text values (fonts, links, layout names and ids) or split by styling. | `grep -rw` and `rg -w` read only the presentations Drive full-text search names; every one is read when the search fails or finds nothing. A word the rendered JSON may hold whatever the text says is never asked: one with a digit, a property name or enum value of the Slides API (`pageElements`, `SLIDE`), or a word every rendering carries (`https`, `arial`). `walk_limit: -1` in the mount's `"@all"` [command limit](/home/core/output-limits) reads every file instead, since Drive indexes a write some time after it lands and searches the file's text, so one whose JSON holds the word only in another value (a font, a link or image address, a layout name or an id), or only as part of a word styling splits into text runs (`snow` bold in `snowman`), can be left out. Acting on presentations (create, batchUpdate, raw API calls) goes through the [gws CLI](/python/cli/gws) when installed. # HF Buckets Source: https://docs.mirage.strukto.ai/python/vfs/hf_buckets Mount Hugging Face Buckets as a Mirage filesystem with async reads and writes for Python agents. The HF Buckets VFS mounts a [Hugging Face Bucket](https://huggingface.co/docs/hub/storage-buckets) at some prefix such as `/hf/`. Listing and writes use [OpenDAL](https://opendal.apache.org/) (the `hf-buckets` extra). Reads stream from the Hub. For credential setup, see [HF Buckets Setup](/home/setup/hf_buckets). ## Install ```bash theme={null} uv add "mirage-ai[hf-buckets]" ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.hf_buckets import HfBucketsConfig, HfBucketsVFS config = HfBucketsConfig( bucket=os.environ["HF_BUCKET_NAME"], # "namespace/bucket-name" token=os.environ["HF_TOKEN"], # Optional: # endpoint="https://huggingface.co", # timeout=30, # key_prefix="data/", ) vfs = HfBucketsVFS(config) ws = Workspace({"/hf": vfs}, mode=MountMode.READ) ``` `HfBucketsVFS(config)` takes an `HfBucketsConfig` object with the bucket in `namespace/bucket-name` form plus an optional access token. `timeout` is how many seconds one Hub request may go without progress: connecting, waiting for the answer, or between two chunks of a download. A large file that keeps arriving is never cut off, and `0` turns the bound off. Both `READ` and `WRITE` modes are supported out of the box. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `bucket` required | Bucket id in `namespace/name` form. | | `token` secret | Hugging Face access token. | | `endpoint` default `'https://huggingface.co'` | Hub origin requests go to, for a mirror or a self-hosted Hub. | | `key_prefix` | Path inside the bucket that becomes the mount root; files outside it are not listed. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with HF Buckets mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Not supported: `mv`, `rmdir`. `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Not supported: `mv`, `rmdir`. `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. > ``` The HF Buckets VFS maps bucket object keys to virtual paths under the mount prefix. For example, if bucket `your-user/my-data` contains: ```text theme={null} data/file.txt data/config.json reports/q1.csv reports/q2.csv ``` Then mounting at `/hf/` exposes: ```text theme={null} /hf/ data/ file.txt config.json reports/ q1.csv q2.csv ``` Path mapping: virtual `/hf/data/file.txt` maps to bucket key `data/file.txt`. ## Cache The HF Buckets VFS uses `IndexCacheStore` with `index_ttl = 600` (10 minutes). Directory listings are cached and populate file-size/type entries that `stat` reads via a fast path, so a `readdir` followed by per-entry `stat` calls (which is what `ls`, FUSE `getattr`, and most shell commands trigger) costs one HTTP request instead of N. A configured `index:` replaces this lifetime with its own `ttl`, and the mount's `ttl:` caps it. ## Integration What Hugging Face buckets answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Hugging Face buckets | | - | - | | `find`, `du`, `ls -R`, `tree` | One recursive listing | ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.vfs.hf_buckets import HfBucketsConfig, HfBucketsVFS load_dotenv(".env.development") config = HfBucketsConfig( bucket=os.environ["HF_BUCKET_NAME"], token=os.environ["HF_TOKEN"], ) vfs = HfBucketsVFS(config) async def main() -> None: ws = Workspace({"/hf/": vfs}, mode=MountMode.READ) r = await ws.shell("ls /hf/") print(await r.stdout_str()) r = await ws.shell("cat /hf/data/file.txt") print(await r.stdout_str()) r = await ws.shell("tree /hf/") print(await r.stdout_str()) r = await ws.shell("find /hf/ -name '*.json'") print(await r.stdout_str()) r = await ws.shell("grep example /hf/data/config.json") print(await r.stdout_str()) r = await ws.shell("stat /hf/data/file.txt") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Shell Commands The HF Buckets VFS supports the full set of shell commands since it operates on real file content (text, binary, JSON, CSV, etc.). Large files benefit from range reads to avoid downloading entire objects. ### Read Commands | Command | Notes | | - | - | | `cat` | Read file content | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search (file or directory level) | | `jq` | Query JSON fields | | `wc` | Line/word/byte counts | | `stat` | File metadata (name, size, type, modified) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `nl` | Number lines | | `du` | Disk usage summary | | `file` | Detect file type | | `strings` | Extract printable strings from binary | | `xxd` | Hex dump | | `md5` | MD5 checksum | | `sha256sum` | SHA-256 checksum | ### Text Processing | Command | Notes | | - | - | | `awk` | Pattern scanning and processing | | `sed` | Stream editor | | `tr` | Translate or delete characters | | `sort` | Sort lines | | `uniq` | Remove duplicate lines | | `cut` | Extract fields/columns | | `join` | Join lines on a common field | | `paste` | Merge lines side by side | | `column` | Columnate output | | `fold` | Wrap lines to a specified width | | `expand` | Convert tabs to spaces | | `unexpand` | Convert spaces to tabs | | `fmt` | Simple text formatter | | `rev` | Reverse lines | | `tac` | Concatenate and print in reverse | | `look` | Display lines beginning with a given string | | `shuf` | Shuffle lines | | `tsort` | Topological sort | | `comm` | Compare two sorted files | | `cmp` | Compare two files byte by byte | | `diff` | Compare files line by line | | `iconv` | Character encoding conversion | ### File Operations | Command | Notes | | - | - | | `rm` | Remove files; `-r` removes a subtree | | `mkdir` | No-op: a directory exists only while it holds a file | | `touch` | Create empty file or update timestamp | | `mktemp` | Create temporary file | | `split` | Split file into pieces | | `csplit` | Split file by context | ### Path Utilities | Command | Notes | | - | - | | `basename` | Strip directory from path | | `dirname` | Strip filename from path | | `realpath` | Resolve path | | `readlink` | Print symbolic link target | | `ls` | List directory contents | ### Compression | Command | Notes | | - | - | | `gzip` | Compress files | | `gunzip` | Decompress gzip files | | `zip` | Create zip archives | | `unzip` | Extract zip archives | | `tar` | Archive files | | `zcat` | Cat compressed files | | `zgrep` | Grep compressed files | ### Encoding | Command | Notes | | - | - | | `base64` | Base64 encode/decode | ## Use Cases * **AI agents accessing HF datasets**: Mount HF Buckets for agents to read and process datasets stored on the Hub * **Data pipelines**: Read and write HF bucket objects with shell-like commands * **Sandboxed bucket access**: Restrict agent operations to a specific bucket and prefix * **FUSE mounting**: Expose HF Buckets through a virtual FUSE mount for external tools ## Scoping a VFS to a key prefix Pass `key_prefix: str | None = None` to `HfBucketsConfig` to transparently scope every operation to a subpath of the bucket: ```python theme={null} HfBucketsVFS(HfBucketsConfig( bucket="your-user/app-data", token=hf_token, key_prefix=f"users/{user_id}/", )) ``` When set, every read/write/list/stat operation is transparently scoped to that bucket subpath. Agents see clean paths like `/data/notes.md`; the underlying bucket key is `users/{user_id}/data/notes.md`. Useful for multi-tenant systems. **Normalization:** leading slashes are stripped and a trailing slash is added automatically. Both `None` and an empty string are treated as "no prefix." # HF Datasets Source: https://docs.mirage.strukto.ai/python/vfs/hf_datasets Mount a Hugging Face dataset repository as a read-only filesystem and browse its shards with shell commands. The HF Datasets VFS mounts a [Hugging Face Dataset](https://huggingface.co/datasets) repo at some prefix such as `/ds/`. All reads are lazy: only the bytes you actually `cat`/`head` get transferred. For credential setup, see [HF Datasets Setup](/home/setup/hf_datasets). ## Install ```bash theme={null} # No extra needed: the Hub API is reached over aiohttp, a core dependency. uv add mirage-ai ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.hf_datasets import HfDatasetsConfig, HfDatasetsVFS config = HfDatasetsConfig( repo_id=os.environ["HF_DATASET_REPO"], # "namespace/dataset-name" token=os.environ.get("HF_TOKEN"), # Optional: # endpoint="https://huggingface.co", # revision="main", # key_prefix="train/", ) vfs = HfDatasetsVFS(config) ws = Workspace({"/ds": vfs}, mode=MountMode.READ) ``` `HfDatasetsConfig` takes `repo_id` in `namespace/dataset-name` form plus an optional access token. Public datasets need no token. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `repo_id` required | Repository id as `namespace/name`, or a bare `name` that resolves against the token's owner. | | `token` secret | Hugging Face access token; unset sends anonymous requests, which reach public repositories only. | | `endpoint` default `'https://huggingface.co'` | Hub origin requests go to, for a mirror or a self-hosted Hub. | | `key_prefix` | Path inside the repository that becomes the mount root; files outside it are not listed. | | `revision` | Branch, tag or commit the mount reads; unset reads `main`. | | `expand_commits` | Fetch each file's last commit so listings carry modification times, at 50 entries per request instead of 1000. Unset does so only when the whole repository fits in one page. | Fields marked secret are redacted in snapshots. ## Reading, not writing This mount is read-only, the way a [`github`](/python/vfs/github) mount is. A Hub write is a **commit**, and a POSIX write cannot say where a commit ends, so `echo >`, `rm`, `cp` and `mv` are refused here rather than silently making one commit per file. The [`hf` CLI](/python/cli/hf) is the write half: `hf download --local-dir` puts a copy on a ram or disk mount, which is an ordinary writable filesystem, and `hf upload` sends it back as a single commit. ## Listings under `fresh` Under `read: fresh`, a cached listing is checked against the commit the `revision` resolves to: one small check per command (`revision/{rev}?expand[]=sha`), after which every cached listing of the mount at that commit is served. A mount whose `revision` is a full 40- or 64-hex commit sha is checked the same way, with that one small request per command: a branch or tag named like the sha could take the name, and mirage does not assume which one the Hub resolves. With a `key_prefix`, the stored version is that commit joined with the prefix, so mounts of different subtrees sharing an index never share a version. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with HF Datasets mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | read | > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | read | > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ``` Maps dataset repo files to virtual paths under the mount prefix. For example, if dataset `AlienKevin/SWE-ZERO-12M-trajectories` contains: ```text theme={null} README.md data/train-00000-of-01000.parquet data/train-00001-of-01000.parquet ``` Then mounting at `/ds/` exposes: ```text theme={null} /ds/ README.md data/ train-00000-of-01000.parquet train-00001-of-01000.parquet ``` ## Integration What Hugging Face datasets answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Hugging Face datasets | | - | - | | `sha256sum` | The LFS sha256 the Hub keeps; other files are read | ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.vfs.hf_datasets import HfDatasetsConfig, HfDatasetsVFS load_dotenv(".env.development") config = HfDatasetsConfig( repo_id=os.environ.get("HF_DATASET_REPO", "AlienKevin/SWE-ZERO-12M-trajectories"), token=os.environ.get("HF_TOKEN"), ) vfs = HfDatasetsVFS(config) async def main() -> None: ws = Workspace({"/ds": vfs}, mode=MountMode.READ) r = await ws.shell("ls /ds/") print(await r.stdout_str()) r = await ws.shell("cat /ds/README.md | head -n 20") print(await r.stdout_str()) r = await ws.shell("find /ds/ -name '*.parquet' | head -n 5") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Shell Commands Every read command in [HF Buckets'](/python/vfs/hf_buckets#read-commands) set works here, as do the text processing and path utilities, which only read. What does not is the [File Operations](/python/vfs/hf_buckets#file-operations) group: this mount is read-only, so `rm` and `touch` are refused, as is any command asked to write into it. ## Cache Uses `IndexCacheStore` with `index_ttl = 86_400` (one day), capped by the mount's `ttl:` (600 seconds unless raised). Directory listings are cached and populate file-size/type entries for `stat`'s fast path. The first listing fills the index for the whole mount: one revision request for the commit, then the recursive tree walked at that commit, so a `readdir` + per-entry `stat` (which `ls`, FUSE `getattr`, and most shell commands trigger) costs those requests rather than one per entry. ## Use Cases * **AI agents inspecting datasets**: Mount, browse the README, read byte ranges from large shards without downloading the whole dataset * **Dataset triage**: `ls`, `stat`, `find` to see what's in a repo before committing to a full local copy * **Sandboxed access**: Pin a `revision` for reproducibility # HF Models Source: https://docs.mirage.strukto.ai/python/vfs/hf_models Mount a Hugging Face model repository as a filesystem and inspect weights, configs, and cards with shell commands. The HF Models VFS mounts a [Hugging Face Model](https://huggingface.co/models) repo at some prefix such as `/m/`. You can inspect configs, tokenizers, and READMEs without downloading the weights, weights stream only when you actually `cat` them. For credential setup, see [HF Models Setup](/home/setup/hf_models). ## Install ```bash theme={null} # No extra needed: the Hub API is reached over aiohttp, a core dependency. uv add mirage-ai ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.hf_models import HfModelsConfig, HfModelsVFS config = HfModelsConfig( repo_id=os.environ["HF_MODEL_REPO"], # "namespace/model-name" token=os.environ.get("HF_TOKEN"), # Optional: # endpoint="https://huggingface.co", # revision="main", ) vfs = HfModelsVFS(config) ws = Workspace({"/m": vfs}, mode=MountMode.READ) ``` | Field | Description | | - | - | | `timeout` default `30` | 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. | | `repo_id` required | Repository id as `namespace/name`, or a bare `name` that resolves against the token's owner. | | `token` secret | Hugging Face access token; unset sends anonymous requests, which reach public repositories only. | | `endpoint` default `'https://huggingface.co'` | Hub origin requests go to, for a mirror or a self-hosted Hub. | | `key_prefix` | Path inside the repository that becomes the mount root; files outside it are not listed. | | `revision` | Branch, tag or commit the mount reads; unset reads `main`. | | `expand_commits` | Fetch each file's last commit so listings carry modification times, at 50 entries per request instead of 1000. Unset does so only when the whole repository fits in one page. | Fields marked secret are redacted in snapshots. ## Reading, not writing This mount is read-only, the way a [`github`](/python/vfs/github) mount is. A Hub write is a **commit**, and a POSIX write cannot say where a commit ends, so `echo >`, `rm`, `cp` and `mv` are refused here rather than silently making one commit per file. The [`hf` CLI](/python/cli/hf) is the write half: `hf download --local-dir` puts a copy on a ram or disk mount, which is an ordinary writable filesystem, and `hf upload` sends it back as a single commit. ## Listings under `fresh` Under `read: fresh`, a cached listing is checked against the commit the `revision` resolves to: one small check per command (`revision/{rev}?expand[]=sha`), after which every cached listing of the mount at that commit is served. A mount whose `revision` is a full 40- or 64-hex commit sha is checked the same way, with that one small request per command: a branch or tag named like the sha could take the name, and mirage does not assume which one the Hub resolves. With a `key_prefix`, the stored version is that commit joined with the prefix, so mounts of different subtrees sharing an index never share a version. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with HF Models mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | read | > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | read | > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ``` Maps model repo files (config, tokenizer, weights, etc.) to virtual paths. For example, `sapientinc/HRM-Text-1B` mounted at `/m/` exposes: ```text theme={null} /m/ README.md config.json tokenizer.json tokenizer_config.json model.safetensors ← never downloaded unless you cat it ``` ## Integration What Hugging Face models answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Hugging Face models | | - | - | | `sha256sum` | The LFS sha256 the Hub keeps; other files are read | ## Example ```python theme={null} import asyncio from mirage import MountMode, Workspace from mirage.vfs.hf_models import HfModelsConfig, HfModelsVFS config = HfModelsConfig(repo_id="sapientinc/HRM-Text-1B") vfs = HfModelsVFS(config) async def main() -> None: ws = Workspace({"/m": vfs}, mode=MountMode.READ) # ls is cheap: one HTTP list call r = await ws.shell("ls -lh /m/") print(await r.stdout_str()) # Read the config (small, fast) r = await ws.shell("cat /m/config.json") print(await r.stdout_str()) # Stat the weights without downloading them r = await ws.shell("stat /m/model.safetensors") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Shell Commands Every read command in [HF Buckets'](/python/vfs/hf_buckets#read-commands) set works here, as do the text processing and path utilities, which only read. What does not is the [File Operations](/python/vfs/hf_buckets#file-operations) group: this mount is read-only, so `rm` and `touch` are refused, as is any command asked to write into it. ## Use Cases * **Model card inspection**: Read configs, tokenizers, READMEs without pulling multi-GB weight files * **Compatibility checks**: `jq` over `config.json` to verify architecture before committing to a download * **Pinned revisions**: Mount a specific commit/tag for reproducibility # HF Spaces Source: https://docs.mirage.strukto.ai/python/vfs/hf_spaces Mount a Hugging Face Space repository as a filesystem and read its application files with shell commands. The HF Spaces VFS mounts a [Hugging Face Space](https://huggingface.co/spaces) repo (app code, README, config, requirements) at some prefix such as `/s/`. For credential setup, see [HF Spaces Setup](/home/setup/hf_spaces). ## Install ```bash theme={null} # No extra needed: the Hub API is reached over aiohttp, a core dependency. uv add mirage-ai ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.hf_spaces import HfSpacesConfig, HfSpacesVFS config = HfSpacesConfig( repo_id=os.environ["HF_SPACE_REPO"], # "namespace/space-name" token=os.environ.get("HF_TOKEN"), # Optional: # endpoint="https://huggingface.co", # revision="main", ) vfs = HfSpacesVFS(config) ws = Workspace({"/s": vfs}, mode=MountMode.READ) ``` | Field | Description | | - | - | | `timeout` default `30` | 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. | | `repo_id` required | Repository id as `namespace/name`, or a bare `name` that resolves against the token's owner. | | `token` secret | Hugging Face access token; unset sends anonymous requests, which reach public repositories only. | | `endpoint` default `'https://huggingface.co'` | Hub origin requests go to, for a mirror or a self-hosted Hub. | | `key_prefix` | Path inside the repository that becomes the mount root; files outside it are not listed. | | `revision` | Branch, tag or commit the mount reads; unset reads `main`. | | `expand_commits` | Fetch each file's last commit so listings carry modification times, at 50 entries per request instead of 1000. Unset does so only when the whole repository fits in one page. | Fields marked secret are redacted in snapshots. ## Reading, not writing This mount is read-only, the way a [`github`](/python/vfs/github) mount is. A Hub write is a **commit**, and a POSIX write cannot say where a commit ends, so `echo >`, `rm`, `cp` and `mv` are refused here rather than silently making one commit per file. The [`hf` CLI](/python/cli/hf) is the write half: `hf download --local-dir` puts a copy on a ram or disk mount, which is an ordinary writable filesystem, and `hf upload` sends it back as a single commit. ## Listings under `fresh` Under `read: fresh`, a cached listing is checked against the commit the `revision` resolves to: one small check per command (`revision/{rev}?expand[]=sha`), after which every cached listing of the mount at that commit is served. A mount whose `revision` is a full 40- or 64-hex commit sha is checked the same way, with that one small request per command: a branch or tag named like the sha could take the name, and mirage does not assume which one the Hub resolves. With a `key_prefix`, the stored version is that commit joined with the prefix, so mounts of different subtrees sharing an index never share a version. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with HF Spaces mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | read | > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | read | > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ``` For example, `HuggingFaceBio/carbon-demo` mounted at `/s/` might expose: ```text theme={null} /s/ README.md app.py requirements.txt Dockerfile ``` ## Integration What Hugging Face Spaces answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Hugging Face Spaces | | - | - | | `sha256sum` | The LFS sha256 the Hub keeps; other files are read | ## Example ```python theme={null} import asyncio from mirage import MountMode, Workspace from mirage.vfs.hf_spaces import HfSpacesConfig, HfSpacesVFS async def main() -> None: vfs = HfSpacesVFS( HfSpacesConfig(repo_id="HuggingFaceBio/carbon-demo")) ws = Workspace({"/s": vfs}, mode=MountMode.READ) r = await ws.shell("ls /s/") print(await r.stdout_str()) r = await ws.shell("cat /s/README.md | head -n 20") print(await r.stdout_str()) r = await ws.shell("grep -l import /s/*.py 2>/dev/null") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Shell Commands Every read command in [HF Buckets'](/python/vfs/hf_buckets#read-commands) set works here, as do the text processing and path utilities, which only read. What does not is the [File Operations](/python/vfs/hf_buckets#file-operations) group: this mount is read-only, so `rm` and `touch` are refused, as is any command asked to write into it. ## Use Cases * **Space introspection**: Browse an app's structure, requirements, and config before forking/cloning * **App code review**: `grep` / `find` across a Space's Python without cloning the repo # Overview Source: https://docs.mirage.strukto.ai/python/vfs/index Python VFS types you can mount in a Mirage workspace. VFS types are the storage systems and services you mount into a Mirage workspace. Open **Providers** in the sidebar to browse every Python-supported backend by category. Each provider page covers the required configuration, mounted tree, and VFS-specific behavior. Provider setup spans local filesystems, object stores, cloud drives, collaboration tools, databases, vector stores, and agent memory systems. To implement another backend, see [Adding a New VFS](/python/vfs/new). # Jaeger Source: https://docs.mirage.strukto.ai/python/vfs/jaeger Read Jaeger services, operations, and traces as read-only JSON files. The Jaeger VFS provides read-only access to the services, operations, and traces of an existing Jaeger query service. It needs no extra: its HTTP client ships with `mirage-ai`. For connection setup, see [Jaeger Setup](/home/setup/jaeger). For the TypeScript SDK, see [Jaeger (TypeScript)](/typescript/setup/jaeger). ## Config ```python theme={null} from mirage import MountMode, Workspace from mirage.vfs.jaeger import JaegerConfig, JaegerVFS config = JaegerConfig(host="http://localhost:16686") vfs = JaegerVFS(config) ws = Workspace({"/jaeger": vfs}, mode=MountMode.READ) ``` | Field | Description | | - | - | | `timeout` default `30` | 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. | | `host` default `'http://localhost:16686'` | Jaeger query service URL. | | `default_trace_limit` default `100` | The most traces one service's `traces/` listing shows, newest first. An older trace is still readable by its id. | | `default_from_timestamp` | Lower bound of trace listings, an ISO 8601 timestamp. Unset searches from the beginning. | | `default_to_timestamp` | Upper bound of trace listings, an ISO 8601 timestamp. Unset means now. | ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Jaeger mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `jaeger`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > services/ > <service-name>/ > operations.json > traces/ > <trace-id>.json > ``` > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `jaeger`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > services/ > <service-name>/ > operations.json > traces/ > <trace-id>.json > ``` > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ```` ## Layout reference | Path | Contents | | - | - | | `services/` | One directory per service Jaeger's `/api/services` reports, including Jaeger's own `jaeger` service when it traces itself | | `services/<service>/operations.json` | The operation records `/api/operations` returns for the service | | `services/<service>/traces/<trace-id>.json` | The trace document `/api/traces/<trace-id>` returns | The `traces/` listing shows the newest `default_trace_limit` traces of the service within `default_from_timestamp` and `default_to_timestamp`. Unset bounds search from the beginning up to now. A trace older than the listing is still readable by its id, as long as one of its spans comes from that service. A service Jaeger does not know, a trace id that is not 16 or 32 hex digits, and a trace without a span from the addressed service are reported as missing paths. Every listed file has an exact size, so `ls -l`, `du`, and `stat` work without reading the files. The mount has no write operations. ## Example ```python theme={null} import asyncio from mirage import MountMode, Workspace from mirage.vfs.jaeger import JaegerConfig, JaegerVFS async def main() -> None: config = JaegerConfig(host="http://localhost:16686") ws = Workspace({"/jaeger": JaegerVFS(config)}, mode=MountMode.READ) # Discover services res = await ws.shell("ls /jaeger/services") print(await res.stdout_str()) # Operation names of one service res = await ws.shell( "jq -r '.[].name' /jaeger/services/frontend/operations.json" ) print(await res.stdout_str()) # Span names of the newest traces res = await ws.shell( "jq -r '.spans[].operationName' /jaeger/services/frontend/traces/*.json" ) print(await res.stdout_str()) await ws.close() if __name__ == "__main__": asyncio.run(main()) ``` # LanceDB Source: https://docs.mirage.strukto.ai/python/vfs/lancedb Mount a LanceDB table as a Mirage filesystem, with label folders, multimodal blobs, and semantic search through the search CLI for Python agents. The LanceDB VFS exposes a LanceDB table as a virtual filesystem mounted at some prefix such as `/fashion/`. Group-by columns become nested folders, each row becomes a card plus an optional blob file, and semantic search is the [`search` CLI](/python/cli/search), which returns ranked rows as canonical file paths. For connection setup (LanceDB OSS, object storage, Cloud, Enterprise), see [LanceDB Setup](/home/setup/lancedb). Install the extra: ```bash theme={null} pip install "mirage-ai[lancedb]" ``` ## Config ```python theme={null} from mirage import MountMode, Workspace from mirage.vfs.lancedb import LanceDBConfig, LanceDBVFS config = LanceDBConfig( uri="/data/fashion.lancedb", table="fashion", group_by=["gender", "articleType", "baseColour"], id_column="id", title_column="productDisplayName", blob_column="image_bytes", blob_ext="jpg", vector_column="vector", search_limit=5, ) vfs = LanceDBVFS(config) ws = Workspace({"/fashion/": vfs}, mode=MountMode.READ) ``` The mapping is config-driven; nothing about the dataset is hardcoded. Point `group_by` at different columns and the folder tree changes. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `uri` required | Database location: a local directory, an `s3://`, `gs://` or `az://` URI, or a `db://` URI for LanceDB Cloud or Enterprise. | | `api_key` secret | API key for LanceDB Cloud or Enterprise. | | `region` default `'us-east-1'` | LanceDB Cloud region of a `db://` database; ignored for other URIs. | | `host_override` | Endpoint of a LanceDB Enterprise deployment for a `db://` URI; ignored for other URIs. | | `storage_options` | Options passed to LanceDB's object-store layer, such as credentials or an endpoint for an `s3://` URI. | | `table` | Table the mount root shows; unset lists every table as a top-level folder. | | `group_by` default `[]` | Columns that become folder levels, one per column in order; unset puts every row's files directly under the table. | | `id_column` default `'id'` | Column whose value names each row's files (`<id>.md`, `<id>.<blob_ext>`). | | `title_column` | Column whose value heads a row's card as a `# ` title; unset leaves the card without one. | | `blob_column` | Column of raw or base64 bytes served as `<id>.<blob_ext>` and left out of the card; unset adds no blob file. | | `blob_ext` default `'bin'` | File extension of the blob file, without the dot. | | `vector_column` | Embedding column left out of cards and listings. | | `search_limit` default `10` | Results `search` returns when `--top-k` is not given. | | `max_rows` default `1000` | Most rows one folder listing reads; rows past it are left out, and a group folder lists only the values those rows carry. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with LanceDB mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `lancedb`, read | > > #### VFS Layout > > ##### `/<path>` > > * A LanceDB table, exposed as a filesystem. > * Directories are the configured group-by columns; descending one narrows > a filter. > * Each matching row is a `<id>.md` card plus a `<id>.<ext>` blob file. > * `ls`, `cd`, `cat`, `tree`, `find`, `wc`, `grep` and `rg` work as > usual. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `lancedb` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `lancedb` answers only for `*/*.md`; `grep -r` and `rg` read every other 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>` | `lancedb`, read | > > ## VFS Layout > > ### `/<path>` > > - A LanceDB table, exposed as a filesystem. > - Directories are the configured group-by columns; descending one narrows > a filter. > - Each matching row is a `<id>.md` card plus a `<id>.<ext>` blob file. > - `ls`, `cd`, `cat`, `tree`, `find`, `wc`, `grep` and `rg` work as > usual. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `lancedb` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `lancedb` answers only for `*/*.md`; `grep -r` and `rg` read every other 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. > ``` Every path is translated into a LanceDB query. Descending a folder adds one `WHERE` clause; the leaf level lists rows. ```text theme={null} / # list tables (omitted when `table` is pinned) /<table>/ # distinct group_by[0] values <v1>/ # distinct group_by[1] WHERE group_by[0]=v1 .../<vN>/ # all group-by columns bound -> row files <id>.md # rendered card (text) <id>.<ext> # raw blob / image bytes ``` A group value holding `/` renders as `∕`, and a blank or dot-led value is led by `⁄`, so every value keeps its own directory that lists and opens, and descending into it filters for exactly that value. When `table` is set the table level is elided, so the mount root is that table: ```text theme={null} /fashion/ Men/ Shoes/ White/ 3.md 3.jpg ``` ### Row cards A `<id>.md` card renders the row's columns as readable text and points at its blob. The vector and blob columns are omitted from the card body. ```text theme={null} # Nike Men White Running Sneakers id: 3 gender: Men articleType: Shoes baseColour: White productDisplayName: Nike Men White Running Sneakers blob: 3.jpg ``` ## Semantic search Search is the [`search` CLI](/python/cli/search), not a path. Register it on the workspace: ```python theme={null} from mirage.commands.cli.builtin.search import SEARCH ws.register_cli("search", SEARCH) ``` It returns each ranked row as its **canonical file path** (the same `<id>.md` you would `cat` while browsing) annotated with the vector distance, followed by the card body. Results point back at the real files, so search composes with `cat`, pipes, and `wc`: ```text theme={null} $ search "white running sneakers" /fashion /fashion/Men/Shoes/White/3.md:0.2679 # Nike Men White Running Sneakers id: 3 gender: Men articleType: Shoes baseColour: White productDisplayName: Nike Men White Running Sneakers blob: 3.jpg ... ``` Flags: `--top-k <n>` (default `search_limit`), `--threshold <max-distance>`, `--method semantic` (the only supported method; `grep`/`rg` stay lexical). ## Integration What LanceDB answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On LanceDB | | - | - | | `grep -r`, `rg` | The string columns of each row, for any text; a table with list, struct or bytes columns reads every card. It misses nothing. | ## Supported commands All commands delegate to Mirage's shared implementations. | Command | Behaviour on a LanceDB mount | | - | - | | `ls` | list tables, label folders, or row files | | `cd` | navigate (each level narrows the filter) | | `tree` | render the label hierarchy | | `cat` | print a row card, or dump raw blob/image bytes | | `stat` | directory vs file, blob size, image mime type | | `find` | walk the tree (e.g. `find /fashion -name '*.md'`) | | `grep` / `rg` | lexical search over the rendered cards | | `head` / `tail` | first/last lines of a card | | `wc` | count lines/bytes of a card | `grep`/`rg` stay lexical (literal/regex). The `search` CLI is the semantic path: it auto-embeds the query via the table's embedding function and returns ranked rows as canonical file paths, which compose with `cat`, `wc`, and pipes. `grep -r` and `rg` read only the cards whose string columns hold the text, which a `LIKE` query answers. A text that could match a column's name, a boolean or `null`, or the `column: ` prefix reads every card, as does a table that renders a list, struct or bytes column. ## Access pattern The mount is **read-only** (`MountMode.READ`); writes are not supported. The two read modes are: * **Browse** by label folders: pure metadata `WHERE` filters, no embedding. * **Search** by meaning: the `search` CLI's `search "<query>" <path>` runs vector search using the table's embedding function and returns canonical row paths. Folder listings scan one column with `SELECT DISTINCT` and are capped by `max_rows`, so very large tables should keep `group_by` to low-cardinality columns. # Langfuse Source: https://docs.mirage.strukto.ai/python/vfs/langfuse Mount Langfuse traces, observations, prompts, datasets, and scores as a Mirage virtual filesystem. The Langfuse VFS exposes LLM observability data (traces, observations, prompts, datasets, scores) as a virtual filesystem mounted at some prefix such as `/langfuse/`. For credential setup, see [Langfuse Setup](/home/setup/langfuse). Install the extra: ```bash theme={null} pip install "mirage-ai[langfuse]" ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.langfuse import LangfuseConfig, LangfuseVFS config = LangfuseConfig( public_key=os.environ["LANGFUSE_PUBLIC_KEY"], secret_key=os.environ["LANGFUSE_SECRET_KEY"], host=os.environ.get("LANGFUSE_HOST", "https://cloud.langfuse.com"), ) vfs = LangfuseVFS(config=config) ws = Workspace({"/langfuse": vfs}, mode=MountMode.READ) ``` | Field | Description | | - | - | | `timeout` default `30` | 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. | | `public_key` required | Langfuse project public key. | | `secret_key` required, secret | Langfuse project secret key. | | `host` default `'https://cloud.langfuse.com'` | Langfuse API host; override for a self-hosted or regional instance. | | `default_trace_limit` default `100` | The most traces one trace listing (`traces/` or a session's traces) shows. An older trace is still readable by its id. | | `default_from_timestamp` | List only traces from this ISO 8601 timestamp on. Unset lists whatever the project holds, up to `default_trace_limit`. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Langfuse mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `langfuse`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > traces/ > <trace-id>.json > sessions/ > <session-id>/ > <trace-id>.json > prompts/ > <prompt-name>/ > <version>.json > datasets/ > <dataset-name>/ > items.jsonl > runs/ > <run-name>.jsonl > ``` > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `langfuse`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > traces/ > <trace-id>.json > sessions/ > <session-id>/ > <trace-id>.json > prompts/ > <prompt-name>/ > <version>.json > datasets/ > <dataset-name>/ > items.jsonl > runs/ > <run-name>.jsonl > ``` > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ```` ### Traces `/langfuse/traces/` lists traces (capped at `default_trace_limit`, from `default_from_timestamp` on). The cap bounds the listing, not the tree: `stat` and `cat` still reach an older trace by its id, and `sessions/<id>/` serves only that session's traces. Each trace is a `.json` file: the trace's root observation, with its other observations (spans, generations, events) in `observations` and its scores in `scores`. `input` and `output` are the strings Langfuse stores; `jq '.input | fromjson'` parses a JSON one. ### Sessions `/langfuse/sessions/` lists the sessions of the traces `traces/` lists. Each session directory contains trace `.json` files belonging to that session. ### Prompts `/langfuse/prompts/` lists prompt names as directories. Each prompt directory contains version files (`1.json`, `2.json`, etc.) with the prompt content and metadata. ### Datasets `/langfuse/datasets/` lists dataset names as directories. Each contains `items.jsonl` (dataset items) and `runs/`, one `.jsonl` file per experiment run on the dataset. ## grep and rg grep and rg read each file as `cat` renders it, at every scope; `grep -r` and `rg` walk a directory. No provider-side content search is used, so a search over `traces/` reads every trace the listing returns. ```bash theme={null} grep -r "error" "/langfuse/traces/" rg -l "classify" "/langfuse/prompts/" ``` ## Limits | Command | Limit behavior | | - | - | | `ls traces/` | Returns up to `default_trace_limit` traces | | `cat traces/<id>.json` | Full trace (single doc, no limit needed) | | `grep -r traces/` | Reads every trace `ls traces/` lists | | `wc -l traces/` | Not supported (Langfuse has no count endpoint) | ## Cache The Langfuse VFS uses `IndexCacheStore` (same as other mounts). Index entries store trace IDs, session IDs, and prompt names. ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.vfs.langfuse import LangfuseConfig, LangfuseVFS load_dotenv(".env.development") config = LangfuseConfig( public_key=os.environ["LANGFUSE_PUBLIC_KEY"], secret_key=os.environ["LANGFUSE_SECRET_KEY"], ) vfs = LangfuseVFS(config=config) async def main(): ws = Workspace({"/langfuse": vfs}, mode=MountMode.READ) # List top-level resources r = await ws.shell("ls /langfuse/") print(await r.stdout_str()) # List traces r = await ws.shell("ls /langfuse/traces/") print(await r.stdout_str()) # Read a specific trace traces = (await r.stdout_str()).strip().splitlines() if traces: r = await ws.shell(f'cat "/langfuse/traces/{traces[0]}"') print((await r.stdout_str())[:500]) # List prompts r = await ws.shell("ls /langfuse/prompts/") print(await r.stdout_str()) # Search the listed traces r = await ws.shell('grep -r "error" "/langfuse/traces/"') print(await r.stdout_str()) # List datasets r = await ws.shell("ls /langfuse/datasets/") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Shell Commands | Command | Notes | | - | - | | `ls` | List traces, sessions, prompts, datasets | | `cat` | Read trace JSON, prompt version, dataset items | | `head` / `tail` | Read the beginning/end of a file; directories are rejected | | `grep` / `rg` | Lexically search files; recursive forms walk listed files | | `jq` | Query JSON trace/prompt data | | `stat` | Metadata (trace count, prompt versions, dataset items) | | `find` | Search across resources with `-name` | | `tree` | Directory tree view | # Linear Source: https://docs.mirage.strukto.ai/python/vfs/linear Mount Linear workspaces, teams, projects, issues, and comments as a Mirage filesystem for Python agents. The Linear VFS exposes Linear workspace data as a virtual filesystem mounted at some prefix such as `/linear/`. For API key setup, see [Linear Setup](/home/setup/linear). ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.linear import LinearConfig, LinearVFS config = LinearConfig(api_key=os.environ["LINEAR_API_KEY"]) vfs = LinearVFS(config=config) ws = Workspace({"/linear": vfs}, mode=MountMode.READ) ``` | Field | Description | | - | - | | `timeout` default `30` | 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. | | `api_key` required, secret | Linear personal API key. | | `workspace` | Accepted for compatibility; not read. | | `team_ids` | Only these teams are listed or readable. Unset shows every team the key can reach. | | `base_url` default `'https://api.linear.app/graphql'` | Linear GraphQL endpoint; override to point at a fake or proxy. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Linear mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `linear`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > teams/ > <team-key>__<team-name>__<team-id>/ > team.json > members/ > <display-name>__<user-id>.json > issues/ > <issue-key>__<issue-id>/ > issue.json > comments.jsonl > projects/ > <name>__<project-id>.json > cycles/ > <name>__<cycle-id>.json > documents/ > <title>__<document-id>.json > ``` > > * `ls` directories first to discover exact names. > * Every entity-named segment is `<sanitized-human-readable>__<id>`. The > human-readable part is sanitized, so don't construct it; `ls` the > parent directory instead. > * The id is the last `__`-separated segment: > > ```text theme={null} > /<path>/teams/STR__Strukto-ai__<team-id>/ -> <team-id> > /<path>/teams/.../issues/STR-42__<issue-id>/ -> <issue-id> > /<path>/teams/.../members/Alice__<user-id>.json -> <user-id> > ``` > > All `cat` output is normalized by Mirage (snake\_case keys), not the raw > Linear GraphQL response. The shapes: > > `team.json`: > > ```jsonc theme={null} > { > "team_id": "...", "team_key": "STR", "team_name": "Strukto", > "name": "...", "description": "...", "timezone": "...", > "updated_at": "...", > "states": [ > { "state_id": "...", "state_name": "Todo", "type": "unstarted" }, > ... // one element per workflow state > ] > } > ``` > > `issue.json`: > > ```jsonc theme={null} > { > "issue_id": "...", "issue_key": "STR-42", > "title": "...", "description": "...", > "team_id": "...", "team_key": "...", "team_name": "...", > "project_id": "...", "project_name": "...", > "cycle_id": "...", "cycle_name": "...", "cycle_number": 7, > "state_id": "...", "state_name": "In Progress", > "assignee_id": "...", "assignee_email": "...", "assignee_name": "...", > "creator_id": "...", "creator_email": "...", "creator_name": "...", > "priority": 2, // 0=none 1=urgent 2=high 3=medium 4=low > "label_ids": ["..."], > "label_names": ["bug", "frontend"], > "created_at": "...", "updated_at": "...", "url": "..." > } > ``` > > `comments.jsonl`, one normalized comment per line: > > ```jsonc theme={null} > { "comment_id": "...", "issue_id": "...", "issue_key": "STR-42", > "user_id": "...", "user_email": "...", "user_name": "...", > "body": "...", "created_at": "...", "updated_at": "...", > "url": "..." } > ``` > > A project (`projects/<name>__<project-id>.json`): > > ```jsonc theme={null} > { > "project_id": "...", "team_id": "...", > "name": "...", "description": "...", "state": "started", > "lead_id": "...", "updated_at": "...", "url": "...", > "issue_count": 12, > "issues": [ > { "issue_id": "...", "issue_key": "STR-42", "title": "...", > "state_id": "...", "state_name": "In Progress", "url": "..." } > ] > } > ``` > > A cycle (`cycles/<name>__<cycle-id>.json`): > > ```jsonc theme={null} > { > "cycle_id": "...", "team_id": "...", > "name": "...", "number": 7, > "starts_at": "...", "ends_at": "...", > "updated_at": "...", "url": "..." > } > ``` > > A member (`members/<display-name>__<user-id>.json`): > > ```jsonc theme={null} > { > "user_id": "...", "name": "...", "display_name": "...", > "email": "...", "is_active": true, "is_admin": false, > "updated_at": "...", "url": "..." > } > ``` > > A document (`documents/<title>__<document-id>.json`): > > ```jsonc theme={null} > { > "document_id": "...", "title": "...", "content": "...", > "project_id": "...", "project_name": "...", > "creator_id": "...", "creator_name": "...", "creator_email": "...", > "created_at": "...", "updated_at": "...", "url": "..." > } > ``` > > Useful `jq` paths: > > ```jq theme={null} > .issue_key # issue.json > .state_name # issue.json > .assignee_email # issue.json > .label_names[] # issue.json > .issues[] | select(.state_name == "In Progress") # a project > .states[].state_name # team.json > [inputs] | length # comments.jsonl: count > [inputs | select(.user_email == "x")] | length # comments.jsonl > ``` > > To act on issues (list, get, create, update, assign, transition, > comments, projects, cycles, labels, users, documents, search), use the > `linear` CLI if installed (`linear --help`). > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `linear` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `linear` answers only for `teams/*/issues/*/issue.json`, `teams/*/members/*`, `teams/*/projects/*`, `teams/*/cycles/*` and `teams/*/documents/*`; `grep -r` and `rg` read every other 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>` | `linear`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > teams/ > <team-key>__<team-name>__<team-id>/ > team.json > members/ > <display-name>__<user-id>.json > issues/ > <issue-key>__<issue-id>/ > issue.json > comments.jsonl > projects/ > <name>__<project-id>.json > cycles/ > <name>__<cycle-id>.json > documents/ > <title>__<document-id>.json > ``` > > - `ls` directories first to discover exact names. > - Every entity-named segment is `<sanitized-human-readable>__<id>`. The > human-readable part is sanitized, so don't construct it; `ls` the > parent directory instead. > - The id is the last `__`-separated segment: > > ```text > /<path>/teams/STR__Strukto-ai__<team-id>/ -> <team-id> > /<path>/teams/.../issues/STR-42__<issue-id>/ -> <issue-id> > /<path>/teams/.../members/Alice__<user-id>.json -> <user-id> > ``` > > All `cat` output is normalized by Mirage (snake_case keys), not the raw > Linear GraphQL response. The shapes: > > `team.json`: > > ```jsonc > { > "team_id": "...", "team_key": "STR", "team_name": "Strukto", > "name": "...", "description": "...", "timezone": "...", > "updated_at": "...", > "states": [ > { "state_id": "...", "state_name": "Todo", "type": "unstarted" }, > ... // one element per workflow state > ] > } > ``` > > `issue.json`: > > ```jsonc > { > "issue_id": "...", "issue_key": "STR-42", > "title": "...", "description": "...", > "team_id": "...", "team_key": "...", "team_name": "...", > "project_id": "...", "project_name": "...", > "cycle_id": "...", "cycle_name": "...", "cycle_number": 7, > "state_id": "...", "state_name": "In Progress", > "assignee_id": "...", "assignee_email": "...", "assignee_name": "...", > "creator_id": "...", "creator_email": "...", "creator_name": "...", > "priority": 2, // 0=none 1=urgent 2=high 3=medium 4=low > "label_ids": ["..."], > "label_names": ["bug", "frontend"], > "created_at": "...", "updated_at": "...", "url": "..." > } > ``` > > `comments.jsonl`, one normalized comment per line: > > ```jsonc > { "comment_id": "...", "issue_id": "...", "issue_key": "STR-42", > "user_id": "...", "user_email": "...", "user_name": "...", > "body": "...", "created_at": "...", "updated_at": "...", > "url": "..." } > ``` > > A project (`projects/<name>__<project-id>.json`): > > ```jsonc > { > "project_id": "...", "team_id": "...", > "name": "...", "description": "...", "state": "started", > "lead_id": "...", "updated_at": "...", "url": "...", > "issue_count": 12, > "issues": [ > { "issue_id": "...", "issue_key": "STR-42", "title": "...", > "state_id": "...", "state_name": "In Progress", "url": "..." } > ] > } > ``` > > A cycle (`cycles/<name>__<cycle-id>.json`): > > ```jsonc > { > "cycle_id": "...", "team_id": "...", > "name": "...", "number": 7, > "starts_at": "...", "ends_at": "...", > "updated_at": "...", "url": "..." > } > ``` > > A member (`members/<display-name>__<user-id>.json`): > > ```jsonc > { > "user_id": "...", "name": "...", "display_name": "...", > "email": "...", "is_active": true, "is_admin": false, > "updated_at": "...", "url": "..." > } > ``` > > A document (`documents/<title>__<document-id>.json`): > > ```jsonc > { > "document_id": "...", "title": "...", "content": "...", > "project_id": "...", "project_name": "...", > "creator_id": "...", "creator_name": "...", "creator_email": "...", > "created_at": "...", "updated_at": "...", "url": "..." > } > ``` > > Useful `jq` paths: > > ```jq > .issue_key # issue.json > .state_name # issue.json > .assignee_email # issue.json > .label_names[] # issue.json > .issues[] | select(.state_name == "In Progress") # a project > .states[].state_name # team.json > [inputs] | length # comments.jsonl: count > [inputs | select(.user_email == "x")] | length # comments.jsonl > ``` > > To act on issues (list, get, create, update, assign, transition, > comments, projects, cycles, labels, users, documents, search), use the > `linear` CLI if installed (`linear --help`). > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `linear` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `linear` answers only for `teams/*/issues/*/issue.json`, `teams/*/members/*`, `teams/*/projects/*`, `teams/*/cycles/*` and `teams/*/documents/*`; `grep -r` and `rg` read every other 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. > ```` Directory and file names embed the Linear ID after `__` so that VFS-specific commands can reference the correct VFS without extra lookups. ### Teams Each team directory is named: ```text theme={null} <team-key>__<team-name>__<team-id> ``` Inside the team directory: * `team.json` is the normalized team metadata * `members/` contains one JSON file per member * `issues/` contains one directory per issue * `projects/` contains one JSON file per project, including lightweight related issue references * `cycles/` contains one JSON file per cycle ### Issues Each issue directory is named: ```text theme={null} <issue-key>__<issue-id> ``` Each issue directory contains: * `issue.json` -- normalized issue metadata with command-aligned fields such as `issue_id`, `issue_key`, `team_id`, `state_id`, and `assignee_id` * `comments.jsonl` -- normalized comment stream ordered by `created_at` `comments.jsonl` is a Mirage representation chosen for shell-friendly workflows. It is not a native Linear file format. ### Members Each member file is named: ```text theme={null} <display-name>__<user-id>.json ``` Member JSON includes command-aligned identifiers such as `user_id` and `email` so the value can be reused directly in commands like `linear issue assign`. ### Projects and Cycles Project and cycle files are named: ```text theme={null} <name>__<id>.json ``` Project JSON includes lightweight related issue references. Cycle JSON includes cycle metadata such as start and end dates. ### Documents Each team has a `documents/` folder with one JSON file per Linear document: ```text theme={null} <title>__<document-id>.json ``` Document JSON includes the title, markdown content, the linked project, and the creator. ## Integration What Linear answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Linear | | - | - | | `grep -r`, `rg` | Issues: Linear search, for whole words. Other files: the text the listing keeps. It can miss recent issue writes. | `grep -rw` and `rg -w` ask Linear's issue search for each word and read only the issues that hold every word, where the search names it or the listing keeps it. The listing keeps the issue's other fields (team, project, cycle, state, people, labels, dates, link) and each title or description word the search can miss, such as one inside a link. Every issue is read when the word is a key of the issue JSON (`title`, `priority`) or a JSON literal, has a digit or only the letters a to f, which an id can hold, and when a search fails, returns 250 issues or finds nothing. `walk_limit: -1` in the mount's `"@all"` [command limit](/home/core/output-limits) reads every file instead, since Linear indexes a write some time after it lands. Members, projects, cycles and documents are listed with their whole JSON, so `grep -r` and `rg` list them once more and read only the files whose text holds the pattern's text in any case, whatever `walk_limit` is. The issues are listed once more too, so a change since the last listing is still found. A file over 8 KiB, and every file for a text that is not ASCII, is read as usual. Comments are always read: they are fetched per issue, and Linear's comment search can miss a word inside a link. ## Cache The Linear VFS uses `IndexCacheStore` (same as Discord and other mounts). File bytes go through the workspace file cache. ## Example See [`examples/python/vfs/linear/linear.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/vfs/linear/linear.py) for the full working example. ```bash theme={null} # List teams ls /linear/teams/ # Read team metadata cat /linear/teams/ENG__Engineering__abc123/team.json # List issues ls /linear/teams/ENG__Engineering__abc123/issues/ # Read an issue cat /linear/teams/ENG__Engineering__abc123/issues/ENG-123__iss_001/issue.json # Read issue comments cat /linear/teams/ENG__Engineering__abc123/issues/ENG-123__iss_001/comments.jsonl # Extract issue ID with jq cat /linear/teams/ENG__Engineering__abc123/issues/ENG-123__iss_001/issue.json \ | jq '.issue_id' # Read last 5 comments tail -n 5 /linear/teams/ENG__Engineering__abc123/issues/ENG-123__iss_001/comments.jsonl # List members ls /linear/teams/ENG__Engineering__abc123/members/ # Read a project with its issues cat /linear/teams/ENG__Engineering__abc123/projects/Mirage__proj_001.json \ | jq '.issues' # Tree view tree -L 2 /linear/teams/ ``` ## Finding IDs IDs are embedded in directory and file names after `__`: ```bash theme={null} # Team ID -- embedded in directory name ls /linear/teams/ # -> ENG__Engineering__abc123 <- team_id = abc123 # Issue ID -- embedded in issue directory name ls /linear/teams/ENG__Engineering__abc123/issues/ # -> ENG-123__iss_001 <- issue_id = iss_001 # Member ID -- embedded in member file name ls /linear/teams/ENG__Engineering__abc123/members/ # -> alice__usr_001.json <- user_id = usr_001 # Use stat for structured metadata stat /linear/teams/ENG__Engineering__abc123/issues/ENG-123__iss_001/issue.json # Extract fields with jq cat /linear/teams/ENG__Engineering__abc123/issues/ENG-123__iss_001/issue.json \ | jq '{issue_id, issue_key, team_id, state_id, assignee_id}' ``` ## Shell Commands Standard commands available on the mounted Linear tree: | Command | Notes | | - | - | | `ls` | List teams, issues, members, projects | | `cat` | Read .json metadata or .jsonl comments | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search (file or directory level) | | `jq` | Query JSON fields | | `wc` | Line/word/byte counts | | `stat` | File metadata (name, size, type) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `basename` | Extract file name from path | | `dirname` | Extract directory from path | | `realpath` | Resolve path to absolute form | ## Acting on Linear Reads and writes on Linear entities (issues, comments, projects, cycles, labels, users, documents, search) go through the [linear CLI](/python/cli/linear) when installed; the mounted tree serves the same entities as normalized JSON files. # Mem0 Source: https://docs.mirage.strukto.ai/python/vfs/mem0 Mount a Mem0 memory scope as a read-only virtual filesystem. The Mem0 VFS exposes the memories of a single scope — a `user_id`, `agent_id`, or `run_id` — as JSON files mounted at a prefix such as `/memory/`. Each memory is one file named `<memory_id>.json`. For API key setup, see [Mem0 Setup](/home/setup/mem0). Install the extra: ```bash theme={null} pip install "mirage-ai[mem0]" ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.mem0 import Mem0Config, Mem0VFS config = Mem0Config( api_key=os.environ["MEM0_API_KEY"], user_id=os.environ.get("MEM0_USER_ID"), ) vfs = Mem0VFS(config=config) ws = Workspace({"/memory/": vfs}, mode=MountMode.READ) ``` The VFS is read-only. A snapshot keeps its config, and a load needs the mount handed back through `mounts=`; it has no drift detection, so restored cache entries are served as saved and other reads reach the live backend. Set exactly one of `user_id`, `agent_id`, or `run_id` (see [Setup](/home/setup/mem0)). | Field | Description | | - | - | | `timeout` default `30` | 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. | | `api_key` required, secret | Mem0 Platform API key. | | `host` default `'https://api.mem0.ai'` | Mem0 API base URL. | | `user_id` | Mount this user's memories. Set exactly one of `user_id`, `agent_id` and `run_id`. | | `agent_id` | Mount this agent's memories. Set exactly one of `user_id`, `agent_id` and `run_id`. | | `run_id` | Mount this run's memories. Set exactly one of `user_id`, `agent_id` and `run_id`. | | `default_page_size` default `100` | Memories fetched per request while listing the scope. | | `default_search_limit` default `10` | How many results `search` returns unless the line sets `top_k`. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Mem0 mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `mem0`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > <memory-id>.json > ``` > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `mem0`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > <memory-id>.json > ``` > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ```` The tree is flat: the mount root lists one `<memory_id>.json` file per memory in the configured scope. `cat` returns the full memory JSON, including `memory`, `categories`, `metadata`, `created_at`, `updated_at`, and `structured_attributes`: ```json theme={null} { "id": "6d1ba0fc-1f0c-495b-b5b1-9141b2674b37", "memory": "User's name is Alex, follows a vegetarian diet, allergic to nuts", "categories": ["personal_details"], "created_at": "2026-06-15T00:34:18-07:00", "updated_at": "2026-06-15T00:34:22-07:00" } ``` `stat` reports `updated_at` (falling back to `created_at`) as the modified time and exposes both timestamps. ## Reading Memories ```bash theme={null} ls /memory/ find /memory/ -type f cat /memory/6d1ba0fc-1f0c-495b-b5b1-9141b2674b37.json jq '.memory' /memory/6d1ba0fc-1f0c-495b-b5b1-9141b2674b37.json wc /memory/6d1ba0fc-1f0c-495b-b5b1-9141b2674b37.json ``` ### grep and rg search the JSON files `grep` and `rg` follow normal filesystem semantics and search the same JSON bytes that `cat` returns. A match can therefore come from the memory text or from metadata such as categories and timestamps. Because the mount is a directory, plain `grep` needs `-r` (or a glob); `rg` recurses by default: ```bash theme={null} grep -r "banana" /memory/ grep "banana" /memory/*.json rg "banana" /memory/ ``` ## Search The [`search` CLI](/python/cli/search) asks Mem0's semantic search API within the configured scope. Use it when meaning matters more than exact text. Register it on the workspace: ```python theme={null} from mirage.commands.cli.builtin.search import SEARCH ws.register_cli("search", SEARCH) ``` ```bash theme={null} search "what does the user eat for breakfast" /memory/ search --top-k 5 "morning routine" /memory/ search --threshold 0.4 "movie preferences" /memory/ ``` `--top-k` defaults to `default_search_limit` (10). `--threshold` must be between `0` and `1`. Results are emitted one hit per block, ranked by score: ```text theme={null} /memory/6d1ba0fc-1f0c-495b-b5b1-9141b2674b37.json:0.91 User asked for food recommendations to stay full in the morning ``` ## Cache The VFS uses Mirage's index cache for the virtual tree. The first `ls` fetches the scope's memories (following Mem0 pagination) and primes the cache; read commands reuse the cached metadata and rendered bytes until the cache expires or the workspace is recreated. `search` always calls the Mem0 API directly and is not cached. ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.commands.cli.builtin.search import SEARCH from mirage.vfs.mem0 import Mem0Config, Mem0VFS load_dotenv(".env.development") config = Mem0Config( api_key=os.environ["MEM0_API_KEY"], user_id=os.environ.get("MEM0_USER_ID"), ) vfs = Mem0VFS(config=config) async def main() -> None: ws = Workspace({"/memory/": vfs}, mode=MountMode.READ) ws.register_cli("search", SEARCH) r = await ws.shell("ls /memory/") print(await r.stdout_str()) r = await ws.shell("grep -r -i 'allergic' /memory/") print(await r.stdout_str()) r = await ws.shell('search --top-k 5 "morning routine" /memory/') print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Shell Commands | Command | Notes | | - | - | | `ls` | List the memory files in the scope | | `cat` | Read a memory's full JSON | | `jq` | Query a memory's JSON fields | | `head` / `tail` | Read the first or last lines/bytes of a memory JSON | | `grep` | Search rendered JSON (use `-r` on a directory) | | `rg` | Search rendered JSON, recursive by default | | `find` | Search the virtual tree by name, type, depth, and size | | `wc` | Count lines, words, bytes, characters, and max line length | | `stat` | Show a memory's size and timestamps | # MinIO Source: https://docs.mirage.strukto.ai/python/vfs/minio Mount a self-hosted MinIO bucket as a virtual filesystem. The MinIO VFS is a thin wrapper over the [S3 VFS](/python/vfs/s3). It maps a `MinIOConfig` to an `S3Config` and reuses the exact same backend, commands, and behavior as S3, it just points at your MinIO `endpoint_url` and uses path-style addressing by default. One difference is MinIO's: it ignores copy and delete conditions, so under `write: conditional` mirage refuses what would copy or delete on a MinIO mount (such as a `cp` or `mv` within the mount, a `mv` out of it, `rm`, or `find -delete`), where AWS S3 runs them; a `cp` or `mv` into it from another mount is a write, and goes through. MinIO is self-hosted, so `endpoint_url` is **required** (there is no region-derived host). Uses aioboto3 against MinIO's S3-compatible API. Install the extra: ```bash theme={null} pip install "mirage-ai[s3]" ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.minio import MinIOConfig, MinIOVFS config = MinIOConfig( bucket=os.environ["MINIO_BUCKET"], endpoint_url=os.environ.get("MINIO_ENDPOINT", "http://localhost:9000"), access_key_id=os.environ["MINIO_ACCESS_KEY"], secret_access_key=os.environ["MINIO_SECRET_KEY"], # Optional: # region="us-east-1", # default # path_style=True, # default; MinIO requires path-style addressing # timeout=30, # proxy="http://proxy:8080", ) vfs = MinIOVFS(config) ws = Workspace({"/minio": vfs}, mode=MountMode.WRITE) ``` Both `READ` and `WRITE` modes are supported. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `bucket` required | Name of the bucket to mount. | | `region` default `'us-east-1'` | Region requests are signed for; the gateway's endpoint does not depend on it. | | `endpoint_url` required | URL of the self-hosted S3 gateway, such as `http://localhost:9000`. | | `access_key_id` secret | Access key ID; set it with `secret_access_key`. Unset uses the AWS credential chain. | | `secret_access_key` secret | Secret access key paired with `access_key_id`. | | `session_token` secret | Session token for temporary credentials, sent with the access key pair. | | `aws_profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `path_style` default `True` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `key_prefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | Fields marked secret are redacted in snapshots. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with MinIO mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.vfs.minio import MinIOConfig, MinIOVFS load_dotenv(".env.development") config = MinIOConfig( bucket=os.environ.get("MINIO_BUCKET", "mirage-demo"), endpoint_url=os.environ.get("MINIO_ENDPOINT", "http://localhost:9000"), access_key_id=os.environ.get("MINIO_ACCESS_KEY", "minioadmin"), secret_access_key=os.environ.get("MINIO_SECRET_KEY", "minioadmin"), ) vfs = MinIOVFS(config) async def main() -> None: ws = Workspace({"/minio/": vfs}, mode=MountMode.READ) r = await ws.shell("ls /minio/") print(await r.stdout_str()) r = await ws.shell("tree /minio/") print(await r.stdout_str()) r = await ws.shell("cat /minio/data/config.json") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Notes * MinIO registers under its own `VFSName` and routes through the same `core/s3` implementation, so the full S3 shell-command set applies (`ls`, `cat`, `head`, `tail`, `grep`, `rg`, `wc`, `find`, `tree`, `jq`, `stat`). See the [S3 VFS](/python/vfs/s3) for the complete command reference, range reads, streaming, and the index cache fast path. * For credential setup, see [MinIO Setup](/home/setup/minio). # MongoDB Source: https://docs.mirage.strukto.ai/python/vfs/mongodb Mount MongoDB databases, collections, and documents as a Mirage filesystem with JSON access for Python agents. The MongoDB VFS exposes MongoDB databases, collections, and documents as a virtual filesystem mounted at some prefix such as `/mongodb/`. For connection setup, see [MongoDB Setup](/home/setup/mongodb). Install the extra: ```bash theme={null} pip install "mirage-ai[mongodb]" ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.mongodb import MongoDBConfig, MongoDBVFS config = MongoDBConfig( uri=os.environ["MONGODB_URI"], max_doc_limit=5000, elide_fields={"sample_mflix.movies": ["plot_embedding"]}, ) vfs = MongoDBVFS(config=config) ws = Workspace({"/mongodb": vfs}, mode=MountMode.READ) ``` | Field | Description | | - | - | | `timeout` default `30` | 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. | | `uri` required, secret | MongoDB connection URI. | | `databases` | Databases to mount; others are hidden. Unset or empty mounts every database except `admin`, `config` and `local`. | | `max_doc_limit` default `5000` | Most documents one `tail -n` read of `documents.jsonl` fetches; a larger count on a collection that holds more is refused (`File too large`). | | `elide_fields` default `{}` | Fields dropped from `documents.jsonl`, keyed by `<database>.<collection>` (a view's name works too); a dotted path such as `nested.path` drops a nested field. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with MongoDB mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `mongodb`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > <database>/ > database.json # collection and view names > collections/<collection>/ > schema.json # sampled field types, validator, indexes > documents.jsonl # streamed BSON Extended JSON documents > views/<view>/ > schema.json > documents.jsonl > ``` > > * Read `database.json` first to discover entities, and `schema.json` > before reading a large document stream. > * `head`, `tail`, `wc`, `grep`, `rg` and `jq` understand > `documents.jsonl`; `grep` and `rg` fetch only the documents that may > match. > * An unknown size displays as `-`; `wc -c` measures bytes and `wc -l` > counts documents on demand. These counts may scan the collection. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep` and `rg` ask `mongodb` for the matching lines. `tail` and `wc -l` ask `mongodb` instead of reading a file. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `mongodb`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > <database>/ > database.json # collection and view names > collections/<collection>/ > schema.json # sampled field types, validator, indexes > documents.jsonl # streamed BSON Extended JSON documents > views/<view>/ > schema.json > documents.jsonl > ``` > > - Read `database.json` first to discover entities, and `schema.json` > before reading a large document stream. > - `head`, `tail`, `wc`, `grep`, `rg` and `jq` understand > `documents.jsonl`; `grep` and `rg` fetch only the documents that may > match. > - An unknown size displays as `-`; `wc -c` measures bytes and `wc -l` > counts documents on demand. These counts may scan the collection. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep` and `rg` ask `mongodb` for the matching lines. `tail` and `wc -l` ask `mongodb` instead of reading a file. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ```` The mount mirrors MongoDB's `cluster → database → collection / view` model. The database directory always appears in the path, even when `databases` filters to a single entry. Discovery lists databases, collections, views, and their fixed file names. It does not enumerate one filesystem entry per document. Schema inspection is separate from bulk document reads, so discovering a collection does not require exporting it. These paths and read contracts are shared by Python and TypeScript. ### documents.jsonl One JSON object per line, encoded with BSON [Relaxed Extended JSON](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/). BSON-specific types round-trip through their canonical `$` wrappers: ```json theme={null} {"_id":{"$oid":"573a1390f29313caabcd4135"},"title":"Casablanca","released":{"$date":"1943-01-23T00:00:00Z"},"runtime":102} ``` `cat` / `head` / `tail` / `grep` / `jq` can read this file through the same streaming interface. The cursor fetches documents in batches; `head` can stop after a prefix. Commands that need the whole input, such as `sort` or `jq -s`, can still buffer it. Use bounded reads when exploring a large collection. Because the file is rendered on demand, `stat` / `ls -l` report no size and `du` returns `0` for it (computing the real size would require rendering the whole collection). Use `wc -c documents.jsonl` for the actual rendered byte count, or `wc -l documents.jsonl` for an exact document count (which can scan the collection). `stat -c %s` prints `-` for an unknown size and `0` only for a known empty file. Missing dates also display as `-`. Long directory listings include a `total` row. GNU `ls` reports allocated disk blocks there; the VFS does not expose allocation metadata, so Mirage prints `total ?` for nonempty listings and `total 0` for empty listings. This is an intentional divergence from GNU output, not a sum of rendered file sizes. `stat` checks existence and type without counting documents, sampling fields, or fetching indexes. This keeps `ls`, `find`, and opening a stream independent of the collection size. The same unknown-size convention applies to Postgres row exports and other rendered VFS files. ### schema.json Generated from the first 100 documents in `_id` order. Includes: * field path → observed BSON type frequencies (nested paths unioned across the sample) * index definitions from `listIndexes`, without volatile access counters * the `$jsonSchema` validator if one is registered Repeated reads of unchanged data produce identical bytes. Schema reads do not include document counts or `$indexStats`, so reading a schema cannot change its own content. Views skip indexes. ### database.json Lists collection and view names using two catalog listings, without a per-collection count. Useful for `cat /mongodb/<db>/database.json` to get an overview without recursing into each entity. ### Elided fields Fields listed under `elide_fields` are dropped entirely from `documents.jsonl` output. The type stays documented in `schema.json`, so heavy fields (embeddings, large binary, raw text blobs) can be hidden from agent reads without losing the schema signal: ```python theme={null} config = MongoDBConfig( uri=os.environ["MONGODB_URI"], elide_fields={ "sample_mflix.movies": ["plot_embedding"], "rag.docs": ["metadata.embedding"], }, ) ``` Nested paths use dot notation. Elision applies to both `cat` (one-shot streaming reads) and `tail -f` (live change-stream follows). ## Streaming and Limits `cat`, `grep`, `head`, and `tail -f` consume documents lazily through a batched PyMongo async cursor (or change stream); the consumer cancels to stop fetching. Direct output is capped at 2,000 lines by default, with a truncation notice on stderr. Pipes and redirects bypass this output cap. See [command output limits](/home/core/output-limits) to change the bound. | Command | Behavior | | - | - | | `cat` | Streams the collection sorted by `_id`; direct output uses the command limit above | | `head -n K` | Streams from `_id` order and stops after K documents | | `tail -n K` | Server-side sort + limit; a K past `max_doc_limit` on a collection that long is `File too large` | | `tail -f` | Prints the last lines, then opens a change stream and yields each new insert as a JSONL line | | `grep` (file level) | Streams from `documents.jsonl`; supports `-m` for short-circuit | | `grep -r` (collection/db level) | Every file under the directory; MongoDB sends only the documents that may match | | `jq` | Inherits the streaming `cat` source | | `wc -l` | Uses `countDocuments()` server-side; zero download | | `stat` | Existence and type only; no counts or index queries | ## Smart Commands ### grep and rg For one plain text in a collection's or view's `documents.jsonl`, grep and rg ask MongoDB for the documents that may hold it, in the `_id` order a plain read takes, and search their lines instead of the whole collection. The filter matches the text in any case against every key and string of a document, eight levels deep; a document nested deeper, or holding a value it cannot look into (binary, a regex, code), is always sent. MongoDB still scans the collection, but only those documents are sent. The file is read as usual when the text holds anything but ASCII letters and spaces, or could match an Extended JSON key (`$oid`, `$date`, `$numberLong`), a JSON literal (`true`, `null`) or an id (a word of hex letters only, such as `ada`). `schema.json` and `database.json` are always read, and `-m` stops the cursor early. ```bash theme={null} grep "Godfather" "/mongodb/sample_mflix/collections/movies/documents.jsonl" grep -r "Godfather" "/mongodb/sample_mflix/" ``` ### head / tail / tail -f `tail` uses server-side `sort` + `limit`. A count past `max_doc_limit` on a collection that long is refused with `File too large` rather than printing fewer lines than asked. `head` streams in `_id` order and stops after the count. `tail -f` on a collection reads the last lines at one snapshot, then opens a Mongo change stream of the inserts after it and yields each new document as a JSONL line in the same format as `cat`; on a view it polls. See [Lines](/home/integration/lines): ```bash theme={null} # First 10 docs (sorted by _id ascending) head -n 10 "/mongodb/sample_mflix/collections/movies/documents.jsonl" # Last 10 docs (sorted by _id descending) tail -n 10 "/mongodb/sample_mflix/collections/movies/documents.jsonl" # Live-follow new inserts; consumer cancels to stop tail -f "/mongodb/sample_mflix/collections/movies/documents.jsonl" ``` `tail -f` follows inserts on a replica set on MongoDB 5.0 or later, for the snapshot read and the change stream; Atlas already satisfies this. On a server outside a replica set it polls, and so does a view, which has no change stream. ## Cache The MongoDB VFS lists database names, collection names, and document counts. These listings are not cached by default (`index_ttl = 0`); a workspace or mount `index:` caches them for its `ttl`. Document content is **not** cached. The VFS leaves `caches_reads` at its default of `False`, so `cat`, `grep`, `head`, and `tail` always query the live collection instead of serving a stored snapshot. This keeps reads consistent with a mutable database and ensures `tail -f` follows the live change stream rather than replaying cached bytes. ## Integration What MongoDB answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On MongoDB | | - | - | | `grep`, `rg` on one file | A filter on the server sends only the documents that may match | | `tail -n N` | The last N documents by `_id` | | `wc -l` | `countDocuments()` on the server | | `tail -f` | A change stream yields each new insert | ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.vfs.mongodb import MongoDBConfig, MongoDBVFS load_dotenv(".env.development") config = MongoDBConfig(uri=os.environ["MONGODB_URI"]) vfs = MongoDBVFS(config=config) async def main(): ws = Workspace({"/mongodb": vfs}, mode=MountMode.READ) # List all databases r = await ws.shell("ls /mongodb/") print(await r.stdout_str()) # List the entities under a database (database.json, collections/, views/) r = await ws.shell("ls /mongodb/sample_mflix/") print(await r.stdout_str()) # List collections r = await ws.shell("ls /mongodb/sample_mflix/collections/") print(await r.stdout_str()) # Read first 5 movies r = await ws.shell( 'head -n 5 "/mongodb/sample_mflix/collections/movies/documents.jsonl"') print(await r.stdout_str()) # Read last 5 movies r = await ws.shell( 'tail -n 5 "/mongodb/sample_mflix/collections/movies/documents.jsonl"') print(await r.stdout_str()) # Inspect the sampled schema and indexes r = await ws.shell( 'cat "/mongodb/sample_mflix/collections/movies/schema.json"') print(await r.stdout_str()) # Extract titles with jq r = await ws.shell( 'jq -r ".title" "/mongodb/sample_mflix/collections/movies/documents.jsonl"' ) print(await r.stdout_str()) # Search across a database r = await ws.shell('grep -r "Godfather" "/mongodb/sample_mflix/"') print(await r.stdout_str()) # Count documents (server-side, no download) r = await ws.shell( 'wc -l "/mongodb/sample_mflix/collections/movies/documents.jsonl"') print(await r.stdout_str()) # View the database overview without recursing r = await ws.shell('cat "/mongodb/sample_mflix/database.json"') print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Runnable examples Three working examples live under `examples/python/vfs/mongodb/`: * [`mongodb.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/vfs/mongodb/mongodb.py) — agent-shell workflow: `ls`, `tree`, `cat`, `head`, `tail`, `wc`, `stat`, `grep`/`rg` at every scope, `jq`, `find`, `cd` + relative paths. * [`mongodb_vfs.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/vfs/mongodb/mongodb_vfs.py) — in-process VFS: `os.listdir` and `open()` walk every readdir level (root, database, `collections/`, `views/`, entity) and read `database.json`, `schema.json`, `documents.jsonl` (collection + view). * [`mongodb_fuse.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/vfs/mongodb/mongodb_fuse.py) — same coverage as the VFS example, but the tree is mounted as a real filesystem so other processes can `cat`/`ls`/`head` the mountpoint directly. All three default to the `mirage_test` database seeded by `scripts/seed_mongodb_test.py`. ## Finding IDs `_id` is serialized as `{"$oid": "..."}` under Extended JSON: ```bash theme={null} # List the first 10 ObjectId values jq -r '._id["$oid"]' \ "/mongodb/sample_mflix/collections/movies/documents.jsonl" | head -n 10 # Find a specific document by ID grep "573a1390f29313caabcd42e8" \ "/mongodb/sample_mflix/collections/movies/documents.jsonl" # Extract a few fields together jq -r '"\(._id["$oid"]) \(.title) \(.year)"' \ "/mongodb/sample_mflix/collections/movies/documents.jsonl" ``` ## Working with Large Collections Streaming is the default; reach for these patterns when you want to keep the round trip small: ```bash theme={null} # Document count (server-side, no download) wc -l "/mongodb/sample_mflix/collections/comments/documents.jsonl" # Most recent documents (sorted by _id desc) tail -n 10 "/mongodb/sample_mflix/collections/comments/documents.jsonl" # MongoDB sends only the comments that may hold the word grep -r "love" "/mongodb/sample_mflix/collections/comments/" # Drop heavy fields via elide_fields, then take the slice you want head -n 20 "/mongodb/sample_mflix/collections/movies/documents.jsonl" ``` Hide embeddings or large blobs from agent reads with `elide_fields`; `schema.json` still documents the original type so the agent can decide when to ask for the raw bytes through a different path. ## Shell Commands Standard commands available on the mounted MongoDB tree: | Command | Notes | | - | - | | `ls` | List databases, collections, views, and per-entity files | | `cat` | Stream `documents.jsonl` (or read `schema.json` / `database.json`) | | `head` / `tail` | `head` streams and stops early; `tail` sorts and limits server-side, up to `max_doc_limit` | | `tail -f` | Live-follow new inserts via Mongo change stream | | `grep` / `rg` | A directory operand searches every file under it (documents, schema.json, database.json, views); a file streams | | `jq` | Query JSON; runs once per line of a JSONL file (`-s` for all) | | `wc` | Smart: `-l` uses `countDocuments()` server-side | | `stat` | Existence and type only; no counts or index queries | | `find` | List databases/collections/views with `-name`, `-maxdepth` | | `tree` | Directory tree view | # Adding a New VFS Source: https://docs.mirage.strukto.ai/python/vfs/new Mount a service Mirage does not ship by writing one class. A VFS is a class that extends `BaseVFS`. Define `readdir`, `read` and `stat`, and `ls`, `cat`, `grep`, `find`, `head`, `wc` and the other read commands work on the service. [Custom VFS](/home/setup/custom-vfs) lists every method, with examples for a writable VFS and for grep on the service's own search. ## Write one ```python theme={null} from pydantic import BaseModel, ConfigDict, SecretStr from mirage import Accessor, BaseVFS, FileStat, PathSpec, Workspace class JiraConfig(BaseModel): model_config = ConfigDict(extra="forbid") site: str token: SecretStr class JiraAccessor(Accessor): def __init__(self, config: JiraConfig) -> None: self.client = make_client(config) async def close(self) -> None: await self.client.close() class JiraVFS(BaseVFS): CONFIG_CLS = JiraConfig accessor: JiraAccessor def __init__(self, config: JiraConfig) -> None: super().__init__( name="jira", accessor=JiraAccessor(config), vfs_md="Issues rendered as .json files.", ) async def readdir(self, path: PathSpec) -> list[FileStat]: ... async def read(self, path: PathSpec) -> bytes: ... async def stat(self, path: PathSpec) -> FileStat: ... ws = Workspace({"/jira/": JiraVFS(JiraConfig(site="acme", token="..."))}) await ws.shell("grep -rl outage /jira/") ``` `readdir` returns each child's `FileStat` with `name` set to the base name. The mount keeps the listing and answers a later `stat` from it, so `ls -l` costs one request. Use `path.vfs_path` to address the service and `path.virtual` for the workspace path. Set `FileStat.size` to the length of the bytes `read` returns, or `None` when it is unknown. ## Add functions as the service grows Every other function is optional. Define one, and the commands that need it start working; leave it out, and those commands answer `Operation not supported`. | Functions | Enables | | - | - | | `write`, `append`, `create`, `truncate` | `>`, `>>`, `touch`, `truncate`, `sed -i` | | `mkdir`, `rmdir`, `unlink`, `rm_r`, `rename`, `copy`, `dir_copy`, `setattr` | `mkdir`, `rm`, `mv`, `cp`, `chmod`, `touch -d` | | `files_containing`, `lines_containing` | [Search](/home/integration/search) for `grep` and `rg` from the service's own index | | `first_lines`, `last_lines`, `line_count`, `checksum`, `read_tree` | Fast `head`, `tail`, `wc -l`, `md5sum`, `find` ([Lines](/home/integration/lines), [Walks](/home/integration/walks)) | | `delta_hook` | [Notifications](/home/notifications/support) from the service's change feed | The mount mode still decides whether a write may run. `read` may return an async iterator of bytes for a large file, and `write` receives one when a program's output streams into the mount. ## Plug in the service's search `files_containing` and `lines_containing` hand Mirage the service's own search. `grep` and `rg` ask them which files or lines can hold the text and read only those; they still match every line themselves, so the output is the same as a full read. `before_full_walk` can refuse a command that would walk the whole tree. For example, an S3 bucket whose objects are indexed in Elasticsearch under their keys, by whatever indexes the bucket (such as a function on S3 events). Subclass the built-in `S3VFS` and answer from the index: ```python theme={null} from elasticsearch import AsyncElasticsearch from mirage import MountMode, PathSpec, Workspace from mirage.utils.key_prefix import mounted_path from mirage.vfs.s3 import S3Config, S3VFS class IndexedS3VFS(S3VFS): whole_word_search = True def __init__(self, config: S3Config, es: AsyncElasticsearch) -> None: super().__init__(config) self.es = es async def files_containing( self, path: PathSpec, text: str, *, whole_word: bool, ignore_case: bool ) -> list[PathSpec] | None: if not whole_word: return None found = await self.es.search( index=self.config.bucket, query={"match_phrase": {"body": text}}, size=1000, track_total_hits=True, ) hits = found["hits"] if hits["total"]["value"] > len(hits["hits"]): return None return [mounted_path(path, "/" + hit["_id"]) for hit in hits["hits"]] async def close(self) -> None: if self.is_closed: return try: await self.es.close() finally: await super().close() vfs = IndexedS3VFS(S3Config(bucket="docs"), AsyncElasticsearch("http://localhost:9200")) ws = Workspace({"/s3/": (vfs, MountMode.READ)}) await ws.shell("grep -rlw outage /s3/") ``` `grep -rlw outage /s3/` reads only the objects Elasticsearch names. Elasticsearch ignores case, so it may name more than grep prints; grep checks each line and drops the rest. `grep -rl outage` without `-w` gets `None` and reads every object, so `outages` still matches. The mount is read-only because a write through Mirage would leave the index behind. The answer is only as complete as the index: grep skips an object written elsewhere that Elasticsearch has not indexed yet, so return `None` while the indexer lags. | Function | Asked by | Answers | | - | - | - | | `files_containing(path, text, *, whole_word, ignore_case)` | `grep -r`, `rg` on a folder | The files under `path` that may hold `text`, or `None` to read every file | | `lines_containing(path, text, *, ignore_case)` | `grep`, `rg` on one file | The lines that may hold `text`, in file order, or `None` to read the file | | `before_full_walk(path, *, files)` | `tar -c`, `cp -r`, `rm -r`, `chmod -R`, `diff -r` | Nothing to let the walk run; raise `ValueError` to refuse it | * Answer more files than needed, never fewer: an extra file costs one read, a missing one is a wrong answer. Return `None` whenever the answer may be incomplete, such as a truncated result or an index that lags writes. * A search that matches only whole words, as Elasticsearch does, returns `None` unless `whole_word` is set, and sets `whole_word_search = True` so the mount's VFS.md tells the agent to use `grep -w`. * Set `searchable` to the globs the search covers, such as `("*/*.json",)`; a file outside them is always read. * `walk_limit` caps how many files one command walks, 1000 by default. [Search](/home/integration/search) lists which patterns and flags reach these functions, and which built-in VFSs answer them. A service action that is not a file, such as a JQL search or adding a comment to an issue, belongs in a [CLI](/python/cli/custom), next to the mount. ## Use it in YAML A workspace YAML mounts the class by its file and name: ```yaml theme={null} mounts: /jira: vfs: ./jira.py:JiraVFS config: site: acme token: ${JIRA_TOKEN} ``` To write `vfs: jira` instead, register the class once: ```python theme={null} from mirage import register_vfs register_vfs("jira", JiraVFS, JiraConfig) ``` ## Examples Runnable, each with a TypeScript twin: | Example | Shows | | - | - | | [`custom_vfs.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/vfs/new/custom_vfs.py) | A complete backend in one file: grep on its search, a snapshot and a load | | [`basevfs_views.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/vfs/new/basevfs_views.py) | A read-only VFS beside a nested mount, a symlink and a CLI | | [`custom_command.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/vfs/new/custom_command.py) | A command of the VFS's own | | [`filetype.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/vfs/new/filetype.py) | A renderer for one file type | # Nextcloud Source: https://docs.mirage.strukto.ai/python/vfs/nextcloud Mount Nextcloud over WebDAV as a filesystem and read or write your files with shell commands. The Nextcloud VFS mounts a [WebDAV](http://www.webdav.org/specs/rfc4918.html) server (Nextcloud, ownCloud, Hetzner Storage Share, or any generic WebDAV endpoint) at some prefix such as `/nc/`. Reads are async and streaming, with range requests for partial reads. For credential setup, see [Nextcloud Setup](/home/setup/nextcloud). ## Install ```bash theme={null} uv add "mirage-ai[nextcloud]" ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.nextcloud import NextcloudConfig, NextcloudVFS config = NextcloudConfig( url=os.environ["NEXTCLOUD_URL"], username=os.environ["NEXTCLOUD_USERNAME"], password=os.environ["NEXTCLOUD_PASSWORD"], # Optional: # verify_ssl=True, # timeout=30, ) vfs = NextcloudVFS(config) ws = Workspace({"/nc/": vfs}, mode=MountMode.WRITE) ``` `NextcloudVFS(config)` takes a `NextcloudConfig` object with the WebDAV URL plus optional Basic Auth credentials. Both `READ` and `WRITE` modes are supported. Use an **app password** (Settings → Security in Nextcloud) rather than your account password. | Field | Description | | - | - | | `url` required | WebDAV URL of the user's files, such as `https://cloud.example.com/remote.php/dav/files/alice/`. | | `username` | Basic Auth user name; unset sends requests without credentials. | | `password` secret | Basic Auth password; use an app password (Settings → Security) rather than the account password. | | `verify_ssl` default `True` | Verify the server's TLS certificate on the WebDAV requests mirage sends itself (copy, checksum, quota, properties, search, the chunks of a large write); reads, other writes and listings go through OpenDAL, which always verifies. | | `timeout` default `30` | Seconds one WebDAV request mirage sends itself (copy, checksum, quota, properties, search, the chunks of a large write) may take; reads, other writes and listings go through OpenDAL and its own timeouts. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Nextcloud mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` WebDAV resources map directly to virtual paths under the mount prefix. For example, if your Nextcloud root contains: ```text theme={null} Documents/notes.md Documents/contract.pdf Photos/2024/cat.jpg ``` Then mounting at `/nc/` exposes: ```text theme={null} /nc/ Documents/ notes.md contract.pdf Photos/ 2024/ cat.jpg ``` Path mapping: virtual `/nc/Documents/notes.md` issues HTTP requests against `<NEXTCLOUD_URL>/Documents/notes.md`. ## Cache The Nextcloud VFS uses `IndexCacheStore`. Directory listings come from a single `PROPFIND Depth: 1` and populate file size, type, and ETag entries that `stat` reads via a fast path, so a `readdir` followed by per-entry `stat` calls (which is what `ls`, FUSE `getattr`, and most shell commands trigger) costs one HTTP request instead of N. ## Snapshots A snapshot restores a Nextcloud mount's settings (hand it back at load when it has a password, which is not saved); its files are not checked for drift. ## Integration What Nextcloud answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Nextcloud | | - | - | | `md5sum`, `sha256sum` and the other hash commands | The digest Nextcloud keeps (`oc:checksums`), when the uploading client set one | | `find`, `du`, `ls -R`, `tree` | One recursive listing | ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.vfs.nextcloud import NextcloudConfig, NextcloudVFS load_dotenv(".env.development") config = NextcloudConfig( url=os.environ["NEXTCLOUD_URL"], username=os.environ["NEXTCLOUD_USERNAME"], password=os.environ["NEXTCLOUD_PASSWORD"], ) vfs = NextcloudVFS(config) async def main() -> None: ws = Workspace({"/nc/": vfs}, mode=MountMode.WRITE) r = await ws.shell("ls /nc/") print(await r.stdout_str()) r = await ws.shell("tree /nc/") print(await r.stdout_str()) r = await ws.shell("find /nc/ -name '*.md'") print(await r.stdout_str()) r = await ws.shell("cat /nc/Documents/notes.md") print(await r.stdout_str()) r = await ws.shell("grep TODO /nc/Documents/notes.md") print(await r.stdout_str()) r = await ws.shell("stat /nc/Documents/notes.md") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Shell Commands The Nextcloud VFS supports the full set of shell commands since it operates on real file content (text, binary, JSON, CSV, etc.). Reads benefit from HTTP `Range` requests so commands like `head -c BYTES` don't pull the whole file. ### Read Commands | Command | Notes | | - | - | | `cat` | Read file content | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search (file or directory level) | | `jq` | Query JSON fields | | `wc` | Line/word/byte counts | | `stat` | File metadata (name, size, type, modified) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `nl` | Number lines | | `du` | Disk usage summary | | `file` | Detect file type | | `strings` | Extract printable strings from binary | | `xxd` | Hex dump | | `md5` | MD5 checksum | | `sha256sum` | SHA-256 checksum | ### Text Processing | Command | Notes | | - | - | | `awk` | Pattern scanning and processing | | `sed` | Stream editor | | `tr` | Translate or delete characters | | `sort` | Sort lines | | `uniq` | Remove duplicate lines | | `cut` | Extract fields/columns | | `join` | Join lines on a common field | | `paste` | Merge lines side by side | | `column` | Columnate output | | `fold` | Wrap lines to a specified width | | `expand` | Convert tabs to spaces | | `unexpand` | Convert spaces to tabs | | `fmt` | Simple text formatter | | `rev` | Reverse lines | | `tac` | Concatenate and print in reverse | | `look` | Display lines beginning with a given string | | `shuf` | Shuffle lines | | `tsort` | Topological sort | | `comm` | Compare two sorted files | | `cmp` | Compare two files byte by byte | | `diff` | Compare files line by line | | `patch` | Apply a diff patch | | `iconv` | Character encoding conversion | ### File Operations | Command | Notes | | - | - | | `cp` | Copy files (WebDAV `COPY` method) | | `mv` | Move/rename files (WebDAV `MOVE` method) | | `rm` | Remove files (WebDAV `DELETE`; recursive for directories) | | `mkdir` | Create directories (WebDAV `MKCOL`) | | `touch` | Create empty file or update timestamp | | `ln` | Create symbolic links | | `tee` | Write stdin to file and stdout | | `mktemp` | Create temporary file | | `split` | Split file into pieces | | `csplit` | Split file by context | ### Path Utilities | Command | Notes | | - | - | | `basename` | Strip directory from path | | `dirname` | Strip filename from path | | `realpath` | Resolve path | | `readlink` | Print symbolic link target | | `ls` | List directory contents | ### Compression | Command | Notes | | - | - | | `gzip` | Compress files | | `gunzip` | Decompress gzip files | | `zip` | Create zip archives | | `unzip` | Extract zip archives | | `tar` | Archive files | | `zcat` | Cat compressed files | | `zgrep` | Grep compressed files | ### Encoding | Command | Notes | | - | - | | `base64` | Base64 encode/decode | ## Streaming * **Reads**: streamed in chunks. Downstream commands like `head -n 1` early-cancel, so you only pay for the first chunk over the wire. * **Range reads**: `head -c BYTES` and other partial reads issue HTTP `Range` requests that Nextcloud and most WebDAV servers honor. * **Writes**: buffer the payload before upload. Streaming uploads (Nextcloud's `uploads/` resumable protocol) are a possible future follow-up. ## Use Cases * **AI agents accessing personal cloud storage**: Mount Nextcloud so agents can read documents, notes, and structured data on a self-hosted cloud. * **Self-hosted alternative to Dropbox/Box**: Same shell-command surface, with full read+write support. * **Multi-protocol WebDAV**: Works against any RFC 4918-compliant server, not just Nextcloud. * **FUSE mounting**: Expose Nextcloud through a virtual FUSE mount for external tools. # Notion Source: https://docs.mirage.strukto.ai/python/vfs/notion Mount Notion pages as a virtual filesystem. The Notion VFS exposes a Notion workspace as a virtual filesystem mounted at a prefix such as `/notion/`. For API key setup, see [Notion Setup](/home/setup/notion). ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.notion import NotionConfig, NotionVFS config = NotionConfig(api_key=os.environ["NOTION_API_KEY"]) vfs = NotionVFS(config=config) ws = Workspace({"/notion": vfs}, mode=MountMode.READ) ``` | Field | Description | | - | - | | `timeout` default `30` | 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. | | `api_key` required, secret | Notion integration token. | | `base_url` default `'https://api.notion.com/v1'` | Notion API root; override to point at a fake or proxy. | | `api_version` | `Notion-Version` header sent with every request. Unset sends `2025-09-03`; `ntn --notion-version` overrides it per line. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Notion mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `notion`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > pages/ # the page tree > <page-title>__<page-id>/ > page.json > <child-page-title>__<child-id>/ > page.json > databases/ # shared databases > <database-title>__<database-id>/ > database.json > <data-source-title>__<data-source-id>/ > data_source.json > rows.jsonl > ``` > > * `page.json` holds the page's metadata, its body rendered as Markdown > and its raw blocks (nested blocks under `children`). > * A database is a container plus one or more data sources. > `database.json` holds the container's identity and its `data_sources` > stubs, `data_source.json` the typed property schema, and `rows.jsonl` > the rows, one JSON line each: the row page's `page.json` without the > body, plus `path`, that `page.json`'s path below the data source > directory. Row directories are not listed; open one by its path. > * Titles are sanitized. Don't construct paths: `ls` the parent > directory, or take a row's `path` from `rows.jsonl`. > * `ntn` takes ids as positional operands, not flags: > `ntn pages get <page-id>`, `ntn datasources query <data-source-id>`, > `ntn datasources resolve <database-id>`. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `head` asks `notion` instead of reading a file. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `notion`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > pages/ # the page tree > <page-title>__<page-id>/ > page.json > <child-page-title>__<child-id>/ > page.json > databases/ # shared databases > <database-title>__<database-id>/ > database.json > <data-source-title>__<data-source-id>/ > data_source.json > rows.jsonl > ``` > > - `page.json` holds the page's metadata, its body rendered as Markdown > and its raw blocks (nested blocks under `children`). > - A database is a container plus one or more data sources. > `database.json` holds the container's identity and its `data_sources` > stubs, `data_source.json` the typed property schema, and `rows.jsonl` > the rows, one JSON line each: the row page's `page.json` without the > body, plus `path`, that `page.json`'s path below the data source > directory. Row directories are not listed; open one by its path. > - Titles are sanitized. Don't construct paths: `ls` the parent > directory, or take a row's `path` from `rows.jsonl`. > - `ntn` takes ids as positional operands, not flags: > `ntn pages get <page-id>`, `ntn datasources query <data-source-id>`, > `ntn datasources resolve <database-id>`. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `head` asks `notion` instead of reading a file. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ```` The `pages/` hierarchy mirrors Notion's standalone page tree. Each page directory contains a `page.json` with the page metadata and content, and child pages appear as nested directories. The `databases/` hierarchy is one level deeper than the page tree, because the `2025-09-03` API generation split a database into a container plus one or more **data sources**. The column schema and the rows both live on the data source: `data_source.json` and `rows.jsonl`. The name stutters for a single-source database because Notion names the auto-created data source after its database; that disappears the moment a database holds two. A data source lists its rows as one file, not as a directory each. A query answers a hundred rows' cells in one call, while every row directory costs calls of its own to enter, so a `grep -r` or `find` over a large database would cost calls per row. A row is still a page with a `page.json`, at `<data-source-dir>/<row-title>__<page-id>/page.json`: it is not listed, and its path is on the row's line in `rows.jsonl`. ### database.json The container's identity. It carries `database_id`, `title`, `url`, timestamps, `parent`, `archived`, `is_inline`, and the `data_sources` stubs that name the directories beneath it. It **does not carry `properties`**: at this API version the column schema lives on the data source, and `GET /v1/databases/{id}` no longer returns one. ```json theme={null} { "database_id": "eeee1111-2222-3333-4444-555566667777", "title": "Tasks", "url": "https://www.notion.so/eeee1111222233334444555566667777", "created_time": "2026-01-01T00:00:00.000Z", "last_edited_time": "2026-01-02T00:00:00.000Z", "parent": { "type": "workspace", "workspace": true }, "archived": false, "is_inline": false, "data_sources": [ { "id": "d5000000-2222-3333-4444-555566667777", "name": "Tasks" } ] } ``` ### data\_source.json The typed column schema (Notion's own property objects), with no rows inline: ```json theme={null} { "data_source_id": "d5000000-2222-3333-4444-555566667777", "database_id": "eeee1111-2222-3333-4444-555566667777", "title": "Tasks", "created_time": "2026-01-01T00:00:00.000Z", "last_edited_time": "2026-01-02T00:00:00.000Z", "database_parent": { "type": "workspace", "workspace": true }, "archived": false, "properties": { "Name": { "id": "title", "type": "title", "title": {} }, "Priority": { "id": "pri", "type": "number", "number": { "format": "number" } }, "Due": { "id": "du", "type": "date", "date": {} } } } ``` A data source id is **not** its database id. Turn one into the other with `ntn datasources resolve <database-id>`. ### rows.jsonl Every row of the data source, one JSON object per line, in the order the query returns them. A line is the row's `page.json` without the body, which a query does not carry, plus `path`, where that `page.json` is below the data source directory: ```json theme={null} {"page_id":"ffff1111-2222-3333-4444-555566667777","title":"Write spec","path":"Write_spec__ffff1111-2222-3333-4444-555566667777/page.json","url":"https://www.notion.so/ffff1111222233334444555566667777","created_time":"2026-01-01T00:00:00.000Z","last_edited_time":"2026-01-02T00:00:00.000Z","parent_type":"data_source_id","parent_id":"d5000000-2222-3333-4444-555566667777","archived":false,"created_by":"faa6ebe0-0686-466d-96b3-2480ddda715b","last_edited_by":"faa6ebe0-0686-466d-96b3-2480ddda715b","properties":{"Name":{"id":"title","type":"title","title":[{"type":"text","plain_text":"Write spec"}]},"Priority":{"id":"pri","type":"number","number":2},"Done":{"id":"dn","type":"checkbox","checkbox":true}}} ``` Reading it costs one query call per hundred rows, however many rows match. ### page.json A page, including a database row. Notion blocks render to `markdown` and stay available raw under `blocks`; a row's cell values are under `properties`, as Notion's own property objects, answering to the schema in the `data_source.json` one level up: ```json theme={null} { "page_id": "ffff1111-2222-3333-4444-555566667777", "title": "Write spec", "url": "https://www.notion.so/ffff1111222233334444555566667777", "created_time": "2026-01-01T00:00:00.000Z", "last_edited_time": "2026-01-02T00:00:00.000Z", "parent_type": "data_source_id", "parent_id": "d5000000-2222-3333-4444-555566667777", "archived": false, "created_by": "faa6ebe0-0686-466d-96b3-2480ddda715b", "last_edited_by": "faa6ebe0-0686-466d-96b3-2480ddda715b", "properties": { "Name": { "id": "title", "type": "title", "title": [{ "type": "text", "plain_text": "Write spec" }] }, "Priority": { "id": "pri", "type": "number", "number": 2 }, "Done": { "id": "dn", "type": "checkbox", "checkbox": true } }, "markdown": "", "blocks": [] } ``` So a table's cells are readable with the ordinary tools, and a row's body by the path its line carries: ```bash theme={null} jq -r 'select(.properties.Priority.number > 1) | .title' "$DS/rows.jsonl" grep -c '"checkbox":true' "$DS/rows.jsonl" cat "$DS/$(jq -r 'select(.title == "Write spec") | .path' "$DS/rows.jsonl")" ``` Blocks with children embed them recursively under a `children` key, and the Markdown renders nested blocks with indentation. A standalone page's `properties` holds only its title, which is what the API returns for one. ## Cache Uses `IndexCacheStore` for page metadata. File bytes go through the workspace file cache. ## Integration What Notion answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Notion | | - | - | | `head -n N` | Renders only the first N rows | ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.commands.cli.builtin.ntn import NTN from mirage.vfs.notion import NotionConfig, NotionVFS load_dotenv(".env.development") config = NotionConfig(api_key=os.environ["NOTION_API_KEY"]) vfs = NotionVFS(config=config) async def main(): ws = Workspace({"/notion": vfs}, mode=MountMode.READ) ws.register_cli("ntn", NTN, config.model_dump()) # List top-level pages r = await ws.shell("ls /notion/pages/") print(await r.stdout_str()) # List shared databases, then their data sources and row files r = await ws.shell("ls /notion/databases/") print(await r.stdout_str()) r = await ws.shell("tree -L 3 /notion/databases/") print(await r.stdout_str()) # Read a page r = await ws.shell( 'cat "/notion/pages/Project_Roadmap__a1b2c3d4/page.json"' ) print(await r.stdout_str()) # Read every row's cells r = await ws.shell( 'jq -r ".title" ' '"/notion/databases/Tasks__4a3b21915e77' '/Tasks__d5000000-2222-3333-4444-555566667777/rows.jsonl"' ) print(await r.stdout_str()) # Search across all pages r = await ws.shell('grep -r "deadline" /notion/pages/') print(await r.stdout_str()) # Tree view r = await ws.shell("tree -L 2 /notion/") print(await r.stdout_str()) # Search pages with the Notion search API r = await ws.shell('ntn api v1/search -d \'{"query":"Roadmap"}\'') print(await r.stdout_str()) # Create a new page from Markdown r = await ws.shell( "ntn pages create --content '# New Page' --parent page:a1b2c3d4" ) print(await r.stdout_str()) # Replace an existing page's body r = await ws.shell( "ntn pages edit a1b2c3d4 --content '# Replaced body'") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Shell Commands Standard commands available on the mounted Notion tree: | Command | Notes | | - | - | | `ls` | List pages and child pages | | `cat` | Read page.json content | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Search across pages | | `jq` | Query page JSON fields | | `wc` | Line/word/byte counts | | `stat` | File metadata | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | Acting on Notion (creating, editing and trashing pages, querying data sources, and every route that has no typed verb) goes through the [ntn CLI](/python/cli/ntn) when installed. Ids are positional: use the `<page-id>` / `<database-id>` / `<data-source-id>` from a path segment as the operand. # OCI Object Storage Source: https://docs.mirage.strukto.ai/python/vfs/oci Mount Oracle Cloud Infrastructure Object Storage as a virtual filesystem. The OCI VFS mounts an Oracle Cloud Infrastructure Object Storage bucket at some prefix such as `/oci/`. All operations involve network I/O to the remote object store. Uses aioboto3 against OCI's S3-compatible API. For credential setup, see [OCI Setup](/home/setup/oci). Install the extra: ```bash theme={null} pip install "mirage-ai[oci]" ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.oci import OCIConfig, OCIVFS config = OCIConfig( bucket=os.environ["OCI_BUCKET"], namespace=os.environ["OCI_NAMESPACE"], region=os.environ["OCI_REGION"], access_key_id=os.environ["OCI_ACCESS_KEY_ID"], secret_access_key=os.environ["OCI_SECRET_ACCESS_KEY"], # Optional: # endpoint_url="https://{namespace}.compat.objectstorage.{region}.oci.customer-oci.com", # timeout=30, # proxy="http://proxy:8080", ) vfs = OCIVFS(config=config) ws = Workspace({"/oci": vfs}, mode=MountMode.READ) ``` `OCIVFS(config)` takes an `OCIConfig` object with the bucket name, OCI tenancy `namespace`, `region`, and Customer Secret Key credentials. The S3-compatible endpoint is auto-built from `namespace` + `region` unless `endpoint_url` is supplied. Both `READ` and `WRITE` modes are supported. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `bucket` required | Name of the bucket to mount. | | `region` required | Provider region every request is signed for. Most providers also build their endpoint URL from it unless `endpoint_url` is set. | | `endpoint_url` | Endpoint URL that replaces the one the provider derives. | | `access_key_id` secret | Access key ID; set it with `secret_access_key`. Unset uses the AWS credential chain. | | `secret_access_key` secret | Secret access key paired with `access_key_id`. | | `session_token` secret | Session token for temporary credentials, sent with the access key pair. | | `aws_profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `path_style` default `True` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `key_prefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | | `namespace` required | Object Storage namespace of the tenancy. With `region` it builds the endpoint `https://<namespace>.compat.objectstorage.<region>.oci.customer-oci.com` unless `endpoint_url` is set. | Fields marked secret are redacted in snapshots. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with OCI Object Storage mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` The OCI VFS maps object keys to virtual paths under the mount prefix. OCI "directories" are prefix-based — there are no real directory objects. For example, if bucket `my-bucket` contains: ```text theme={null} data/users.csv data/logs/2026-04-01.jsonl config.json ``` Then mounting at `/oci/` exposes: ```text theme={null} /oci/ data/ users.csv logs/ 2026-04-01.jsonl config.json ``` Path mapping: virtual `/oci/data/users.csv` maps to OCI key `data/users.csv`. ## Cache The OCI VFS uses `IndexCacheStore` with `index_ttl = 600` (10 minutes). Directory listings are cached for up to 600 seconds before being refreshed from OCI. A configured `index:` replaces this lifetime with its own `ttl`, and the mount's `ttl:` caps it. ## Integration What OCI answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On OCI | | - | - | | `find`, `du`, `ls -R`, `tree` | One recursive listing | ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.vfs.oci import OCIConfig, OCIVFS load_dotenv(".env.development") config = OCIConfig( bucket=os.environ["OCI_BUCKET"], namespace=os.environ["OCI_NAMESPACE"], region=os.environ["OCI_REGION"], access_key_id=os.environ["OCI_ACCESS_KEY_ID"], secret_access_key=os.environ["OCI_SECRET_ACCESS_KEY"], ) vfs = OCIVFS(config=config) async def main() -> None: ws = Workspace({"/oci/": vfs}, mode=MountMode.READ) r = await ws.shell("ls /oci/") print(await r.stdout_str()) r = await ws.shell("cat /oci/data/users.csv | head -n 5") print(await r.stdout_str()) r = await ws.shell("tree /oci/") print(await r.stdout_str()) r = await ws.shell("find /oci/ -name '*.jsonl'") print(await r.stdout_str()) r = await ws.shell("stat /oci/config.json") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Shell Commands The OCI VFS supports the full set of shell commands since it operates on real file content (text, binary, JSON, CSV, etc.). Large files benefit from range reads to avoid downloading entire objects. ### Read Commands | Command | Notes | | - | - | | `cat` | Read file content | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search (file or directory level) | | `jq` | Query JSON fields | | `wc` | Line/word/byte counts | | `stat` | File metadata (name, size, type, modified) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `nl` | Number lines | | `du` | Disk usage summary | | `file` | Detect file type | | `strings` | Extract printable strings from binary | | `xxd` | Hex dump | | `md5` | MD5 checksum | | `sha256sum` | SHA-256 checksum | ### Text Processing | Command | Notes | | - | - | | `awk` | Pattern scanning and processing | | `sed` | Stream editor | | `tr` | Translate or delete characters | | `sort` | Sort lines | | `uniq` | Remove duplicate lines | | `cut` | Extract fields/columns | | `join` | Join lines on a common field | | `paste` | Merge lines side by side | | `column` | Columnate output | | `fold` | Wrap lines to a specified width | | `expand` | Convert tabs to spaces | | `unexpand` | Convert spaces to tabs | | `fmt` | Simple text formatter | | `rev` | Reverse lines | | `tac` | Concatenate and print in reverse | | `look` | Display lines beginning with a given string | | `shuf` | Shuffle lines | | `tsort` | Topological sort | | `comm` | Compare two sorted files | | `cmp` | Compare two files byte by byte | | `diff` | Compare files line by line | | `patch` | Apply a diff patch | | `iconv` | Character encoding conversion | ### File Operations | Command | Notes | | - | - | | `cp` | Copy files | | `mv` | Move/rename files | | `rm` | Remove files | | `mkdir` | Create directories | | `touch` | Create empty file or update timestamp | | `ln` | Create symbolic links | | `tee` | Write stdin to file and stdout | | `mktemp` | Create temporary file | | `split` | Split file into pieces | | `csplit` | Split file by context | ### Path Utilities | Command | Notes | | - | - | | `basename` | Strip directory from path | | `dirname` | Strip filename from path | | `realpath` | Resolve path | | `readlink` | Print symbolic link target | | `ls` | List directory contents | ### Compression | Command | Notes | | - | - | | `gzip` | Compress files | | `gunzip` | Decompress gzip files | | `zip` | Create zip archives | | `unzip` | Extract zip archives | | `tar` | Archive files | | `zcat` | Cat compressed files | | `zgrep` | Grep compressed files | ### Encoding | Command | Notes | | - | - | | `base64` | Base64 encode/decode | ## Use Cases * **AI agents accessing OCI data**: Mount OCI buckets for agents to read and process datasets * **Data pipelines**: Read and write OCI objects with shell-like commands * **FUSE mounting**: Expose OCI buckets through a virtual FUSE mount for external tools # OneDrive Source: https://docs.mirage.strukto.ai/python/vfs/onedrive Mount Microsoft OneDrive or SharePoint document libraries as a Mirage filesystem with async access, versioning, and shell commands. The OneDrive VFS mounts a Microsoft OneDrive (or SharePoint document library) at some prefix such as `/onedrive/`. All operations involve network I/O to Microsoft Graph. Files are served as raw bytes (no Office filetype conversion). Uses aiohttp for async Graph access. Compatible with: personal OneDrive, OneDrive for Business, and SharePoint document libraries (driveItems on Microsoft Graph v1.0). For credential setup (tokens, drive ids, app vs delegated auth), see the [OneDrive Setup](/home/setup/onedrive) guide. ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.onedrive import OneDriveVFS, OneDriveConfig config = OneDriveConfig( access_token=os.environ["MS_GRAPH_DRIVE_TOKEN"], # Optional: # Name at most one drive: # drive_id="b!...", # target a specific drive # site_id="contoso.sharepoint.com,...", # a SharePoint site's default drive # group_id="...", # a Teams / Microsoft 365 group's library # user_id="user@contoso.com", # another user's drive (app-only) # graph_base_url="https://graph.microsoft.us/v1.0", # non-worldwide root # key_prefix="Documents/", # mount a sub-folder as the root # timeout=30, ) vfs = OneDriveVFS(config) ws = Workspace({"/onedrive": vfs}, mode=MountMode.WRITE) ``` `OneDriveVFS(config)` takes an `OneDriveConfig` object with a Microsoft Graph bearer token and optional drive/site targeting. Both `READ` and `WRITE` modes are supported. ### Config Reference | Field | Description | | - | - | | `access_token` required, secret | Microsoft Graph bearer token, or a callable that returns one; it is called for each request and again after a `401`. | | `graph_base_url` | Full Graph service root, version segment included, for any deployment but the worldwide one: a sovereign cloud, a private endpoint or a test server. Unset uses `https://graph.microsoft.com/v1.0`. | | `timeout` default `30` | Seconds a Graph request may wait to connect, or between two reads of its answer, before it fails; also how long a server-side copy is polled before it fails as unconfirmed. | | `max_retries` default `5` | Times a request is retried after a `429`, `503` or `504` response. Each retry waits what `Retry-After` asks or an exponential backoff, at most 30 seconds. | | `drive_id` | Graph drive ID of the drive to mount. Set at most one of `drive_id`, `site_id`, `group_id` and `user_id`; with none the mount uses the signed-in user's drive. | | `site_id` | Graph site ID whose default document library the mount uses. | | `group_id` | Microsoft 365 or Teams group ID whose document library the mount uses. | | `user_id` | User ID or UPN whose drive the mount uses, under app-only auth. | | `key_prefix` | Folder path from the drive root that the mount uses as its root. | Fields marked secret are redacted in snapshots. ### Naming the drive `drive_id`, `site_id`, `group_id` and `user_id` are four ways of saying which drive the mount is, so set **at most one**. Setting two raises at config time rather than silently addressing whichever came first, which otherwise surfaces much later as an unexplained 404. Setting none means `/me/drive`, the signed-in user's own drive, which requires delegated auth; app-only auth must set one selector and the permissions to read that target. ### The service root Mounts address `https://graph.microsoft.com/v1.0` unless `graph_base_url` says otherwise. Set it to reach anything else: a sovereign cloud, a private endpoint, or a test server. Give the full root including the version segment, for example `https://graph.microsoft.us/v1.0`. This matters most for the sovereign deployments, which are network-isolated instances rather than regions: a token minted for one is rejected by the others, so a mount pointed at the wrong root fails outright rather than degrading. mirage does not ship a table of their hostnames, since it has no way to verify one; take the root from Microsoft's national cloud documentation for your tenant. Because the root is read from the config rather than a module constant, two mounts in one process can address different deployments. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with OneDrive mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `onedrive`, write | > > #### 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 `onedrive` 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>` | `onedrive`, write | > > ## 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 `onedrive` 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. > ``` The OneDrive VFS maps Graph driveItems (path-addressed) to virtual paths under the mount prefix. Folders are real driveItems, so the tree matches what you see in OneDrive. For example, if the drive contains: ```text theme={null} Documents/file.txt Documents/config.json Reports/q1.csv Reports/q2.csv ``` Then mounting at `/onedrive/` exposes: ```text theme={null} /onedrive/ Documents/ file.txt config.json Reports/ q1.csv q2.csv ``` Path mapping: virtual `/onedrive/Documents/file.txt` maps to the driveItem at `/root:/Documents/file.txt`. ## Versioning and Snapshots OneDrive keeps per-file version history. The VFS exposes it the same way the S3 backend does: * **Fingerprint** is the driveItem `cTag`, so normal reads and `stat` reflect the current content without extra Graph calls. * **Snapshots** pin each file the agent read to its driveItem version id. Replaying a snapshot reads `/versions/{id}/content`, giving the exact bytes captured at snapshot time. A file the agent wrote carries no version and is not checked on replay. ## Cache The OneDrive VFS caches directory listings via `IndexCacheStore` to reduce repeated Graph calls during traversal. ## Example ```python theme={null} import asyncio import os from mirage import MountMode, Workspace from mirage.vfs.onedrive import OneDriveVFS, OneDriveConfig config = OneDriveConfig( access_token=os.environ["MS_GRAPH_DRIVE_TOKEN"], drive_id=os.environ.get("MS_GRAPH_DRIVE_ID") or None, ) vfs = OneDriveVFS(config) async def main() -> None: ws = Workspace({"/onedrive/": vfs}, mode=MountMode.WRITE) r = await ws.shell("ls /onedrive/") print(await r.stdout_str()) await ws.shell("echo 'hello from mirage' > /onedrive/note.txt") r = await ws.shell("cat /onedrive/note.txt") print(await r.stdout_str()) r = await ws.shell("stat /onedrive/note.txt") print(await r.stdout_str()) r = await ws.shell("tree /onedrive/") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` A runnable version lives at `examples/python/vfs/onedrive/onedrive.py`. ## Shell Commands The OneDrive VFS supports the full set of shell commands since it operates on real file content (text, binary, JSON, CSV, etc.). Large files benefit from range reads to avoid downloading entire items. ### Read Commands | Command | Notes | | - | - | | `cat` | Read file content | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search (file or directory level) | | `jq` | Query JSON fields | | `wc` | Line/word/byte counts | | `stat` | File metadata (name, size, type, modified) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `nl` | Number lines | | `du` | Disk usage summary | | `file` | Detect file type | | `strings` | Extract printable strings from binary | | `xxd` | Hex dump | | `md5` | MD5 checksum | | `sha256sum` | SHA-256 checksum | ### File Operations | Command | Notes | | - | - | | `cp` | Copy files | | `mv` | Move/rename files | | `rm` | Remove files | | `mkdir` | Create directories | | `touch` | Create empty file or update timestamp | | `tee` | Write stdin to file and stdout | ### Path Utilities | Command | Notes | | - | - | | `basename` | Strip directory from path | | `dirname` | Strip filename from path | | `realpath` | Resolve path | | `ls` | List directory contents | ## Use Cases * **AI agents accessing org documents**: Mount OneDrive/SharePoint for agents to read and process files * **Versioned document workflows**: Snapshot and replay exact file states over time * **Sandboxed access**: Restrict agent operations to a specific drive and sub-folder via `key_prefix` * **FUSE mounting**: Expose a OneDrive through a virtual FUSE mount for external tools ## Integration What OneDrive answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On OneDrive | | - | - | | `grep -r`, `rg` | Microsoft Graph search, for whole words. It can miss Office files, PDFs, archives, the end of large files, words Graph splits differently (`foo.bar`) and recent writes. | | `find`, `du`, `ls -R`, `tree` | One recursive listing | `grep -rw` and `rg -w` read only the files Microsoft Graph search names; every file is read when the search fails or finds nothing. `walk_limit: -1` in the mount's `"@all"` [command limit](/home/core/output-limits) reads every file instead, since Graph searches the text it extracted, not the bytes `grep` reads, and indexes a write some time after it lands, so a file that holds the word can be left out: an office file, PDF or archive, the end of a large file, or a word Graph splits differently (`foo.bar`). ## Scoping a VFS to a folder Pass `key_prefix: str | None = None` to `OneDriveConfig` to transparently scope every operation to a sub-folder of the drive: ```python theme={null} OneDriveVFS(OneDriveConfig( access_token=token, drive_id=drive_id, key_prefix=f"users/{user_id}/", )) ``` When set, every read/write/list/stat/copy/rename/delete operation is scoped to that sub-folder. Agents see clean paths like `/data/notes.md`; the underlying driveItem is `users/{user_id}/data/notes.md`. Useful for multi-tenant systems. **Normalization:** leading slashes are stripped and a trailing slash is added automatically. Both `None` and an empty string are treated as "no prefix." # Postgres Source: https://docs.mirage.strukto.ai/python/vfs/postgres Mount a Postgres database as a read-only filesystem of schemas, tables, and rows. `PostgresVFS` connects to a Postgres database via a DSN and exposes its schemas and tables as a tree the agent can list, read, and grep. Install the extra: ```bash theme={null} pip install "mirage-ai[postgres]" ``` ## Config ```python theme={null} from mirage import MountMode, Workspace from mirage.vfs.postgres import PostgresConfig, PostgresVFS vfs = PostgresVFS(PostgresConfig( dsn="postgres://user:pass@host:5432/db?sslmode=require", schemas=["public", "analytics"], # optional allowlist default_row_limit=1000, max_read_rows=10_000, max_read_bytes=10 * 1024 * 1024, )) ws = Workspace({"/pg": vfs}, mode=MountMode.READ) ``` For DSN format and permissions, see [Postgres Setup](/home/setup/postgres). To inspect data, run `find /pg/ -name rows.jsonl`, then `head -n 3` on a returned path. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `dsn` required, secret | Postgres connection string. | | `schemas` | Schemas to show in the tree; others are hidden. Unset shows every schema except `pg_catalog`, `information_schema` and `pg_*`. | | `default_row_limit` default `1000` | Rows a windowed read returns when it passes an offset but no limit, and the rows one page of a streamed `rows.jsonl` fetches. | | `max_read_rows` default `10000` | Most rows one read returns. A whole read past it is refused, and so is a `head -n` / `tail -n` count past it on a table that long (`File too large`); `wc -l` counts past it. | | `max_read_bytes` default `10485760` (10 MiB) | Most bytes of `rows.jsonl` one read returns; a whole read past it is refused (`File too large`). | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Postgres mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `postgres`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > database.json # cross-schema graph and sizes > <schema>/ # a Postgres schema (namespace) > tables/<table>/ > schema.json # column types, PK/FK, indexes > semantic.json # descriptions, roles, sample values > rows.jsonl # data (size-guarded) > views/<view>/ > schema.json > semantic.json > rows.jsonl > ``` > > * Read `database.json` first to plan joins. > * Read `semantic.json` to learn what a table means: it splits columns > into dimensions (group by), time\_dimensions and facts (aggregate), and > carries COMMENTs, enum domains and example values. > * Reading `rows.jsonl` is refused for a table above the configured row > or byte threshold. Use `head`, `tail` or `wc`, which ask SQL for only > what they need, or `grep`, which fetches only the matching rows when > SQL can find every match. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep` and `rg` ask `postgres` for the matching lines. `head`, `tail` and `wc -l` ask `postgres` instead of reading a file. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `postgres`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > database.json # cross-schema graph and sizes > <schema>/ # a Postgres schema (namespace) > tables/<table>/ > schema.json # column types, PK/FK, indexes > semantic.json # descriptions, roles, sample values > rows.jsonl # data (size-guarded) > views/<view>/ > schema.json > semantic.json > rows.jsonl > ``` > > - Read `database.json` first to plan joins. > - Read `semantic.json` to learn what a table means: it splits columns > into dimensions (group by), time_dimensions and facts (aggregate), and > carries COMMENTs, enum domains and example values. > - Reading `rows.jsonl` is refused for a table above the configured row > or byte threshold. Use `head`, `tail` or `wc`, which ask SQL for only > what they need, or `grep`, which fetches only the matching rows when > SQL can find every match. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep` and `rg` ask `postgres` for the matching lines. `head`, `tail` and `wc -l` ask `postgres` instead of reading a file. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ```` ## Mount mode `read` only. Postgres mounts are read-only at the VFS level. ## Snapshot behavior The DSN is redacted on snapshot. Hand the mount back at load (`mounts=`, or a config over the server and CLI). ## File size and `du` `rows.jsonl` is rendered on demand. `stat -c %s` and `ls -l` show `-` when its rendered byte length is unknown; physical table storage is never used as a file size. `stat` checks existence and type without fetching columns, row counts, or relation sizes. Planner counts cannot identify content changes, so they are not used as a content fingerprint. The metadata JSON files expose explicitly named row and storage estimates. Use `wc -c rows.jsonl` for the rendered byte count; reading the whole export is subject to the configured row and byte limits. ## Integration What PostgreSQL answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On PostgreSQL | | - | - | | `grep`, `rg` on one file | `LIKE` (`ILIKE` for `-i`) fetches only the rows that may match | | `head -n N` | `LIMIT N` | | `tail -n N` | The last N rows by one query | | `wc -l` | `COUNT(*)` | | `tail -f` | Polls for rows past the last key, on a table with a primary key | For one plain text in a table's or view's `rows.jsonl`, grep and rg ask Postgres for the rows that hold it, with a `LIKE` over each column (`ILIKE` under `-i`), in the order a plain read returns them, and search those rows instead of the whole relation. A column is searched through its cast when a line spells it the same way: text, an integer, a boolean, a uuid, an enum, `jsonb`, `char(n)` for a text without a space, and an array of text, integers or uuids. A number, date or time column is left out when the text holds a character it never spells (`ada` in a `float8`). The file is read as usual when another column type is present (`json`, `interval`, `bytea`), when the text could lie inside one of those values, match a key, `null` or the JSON between values, or when more than `max_read_rows` rows match. Since only the matching rows are fetched, a relation too large to read can still be searched when the output shows no line numbers or context. # Qdrant Source: https://docs.mirage.strukto.ai/python/vfs/qdrant Mount a Qdrant collection as a Mirage filesystem, with payload folders, multimodal blobs, and semantic search through the search CLI for Python agents. The Qdrant VFS exposes a [Qdrant](https://qdrant.tech/) collection as a virtual filesystem mounted at some prefix such as `/q/`. Group-by payload fields become nested folders, each point becomes a `.json` payload file (plus a `.txt` text file and an optional blob), and semantic search is the [`search` CLI](/python/cli/search), which returns ranked points as canonical file paths. For connection setup (self-hosted, Qdrant Cloud, search), see [Qdrant Setup](/home/setup/qdrant). Install the extra: ```bash theme={null} pip install "mirage-ai[qdrant]" ``` ## Config ```python theme={null} from mirage import MountMode, Workspace from mirage.vfs.qdrant import QdrantConfig, QdrantVFS config = QdrantConfig( url="https://xyz.cloud.qdrant.io", api_key="...", collection="fashion", group_by=["gender", "articleType", "baseColour"], id_field="id", text_field="productDisplayName", blob_field="image_b64", blob_ext="jpg", cloud_inference=True, search_limit=5, ) vfs = QdrantVFS(config) ws = Workspace({"/fashion/": vfs}, mode=MountMode.READ) ``` The mapping is config-driven; nothing about the dataset is hardcoded. Point `group_by` at different payload fields and the folder tree changes. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `url` | Full URL of the Qdrant server, such as a Qdrant Cloud cluster URL; when set, `host`, `port` and `https` are ignored. | | `host` default `'localhost'` | Host name of the Qdrant server when `url` is unset. | | `port` default `6333` | Port of the Qdrant server when `url` is unset. | | `https` default `False` | Connect to `host` over HTTPS when `url` is unset. | | `api_key` secret | Qdrant API key, required by Qdrant Cloud. | | `collection` | Collection the mount root shows; unset lists every collection as a top-level folder. | | `group_by` default `[]` | Payload fields that become folder levels, one per field in order; dotted paths reach nested keys. Unset puts every point's files directly under the collection. | | `basename_fields` default `[]` | `group_by` fields whose folder names keep only the last path or URL segment of the value; two values with one basename under the same parent are refused as a collision. | | `id_field` default `'id'` | Key the point id is written under in a point's `.json`; it replaces a payload field of that name. | | `name_field` | Payload field whose value prefixes each point's file stem as `<name>__<id>`; unset names files by point id alone. | | `text_field` | Payload field served as the point's `.txt` file and printed by `search`; unset leaves no `.txt`, and `search` returns the `.json`. | | `blob_field` | Payload field of raw or base64 bytes served as `<id>.<blob_ext>` and left out of the `.json`; unset adds no blob file. | | `blob_ext` default `'bin'` | File extension of the blob file, without the dot. | | `vector_field` | Payload field holding a copy of the vector, left out of the `.json`. | | `search_limit` default `10` | Results `search` returns when `--top-k` is not given. | | `max_rows` default `1000` | Most points one folder listing scrolls; points past it are left out, and a group folder lists only the values those points carry. | | `embedding_model` default `'sentence-transformers/all-MiniLM-L6-v2'` | Model the server embeds a `search` query with under `cloud_inference`; it must match the model the stored vectors came from. | | `cloud_inference` default `False` | Send the `search` query text to the server to embed, which needs a cluster with inference enabled (Qdrant Cloud). `embed` takes precedence; with neither, `search` refuses the query. | | `embed` secret | Async function that turns a `search` query into a vector in-process, `(text: str) -> list[float]`. | Fields marked secret are redacted in snapshots. ### Document and chunk lineage Config fields use Qdrant's dotted nested-key syntax. For example, a LangChain-style point can be mounted by source document and named by page: ```json theme={null} { "page_content": "Refunds are processed within 14 days…", "metadata": { "source": "s3://docs/policies/refund-2026.pdf", "page": "004" } } ``` ```python theme={null} config = QdrantConfig( collection="company_docs", group_by=["metadata.source"], basename_fields=["metadata.source"], name_field="metadata.page", text_field="page_content", ) ``` This produces `refund-2026.pdf/004__<point-id>.txt`. The readable prefix comes from `name_field`; the Qdrant point id remains as a stable suffix so duplicate page labels cannot collide and a direct read never depends on a warm listing cache. Only the stem the listing publishes opens: another label in front of the same id reads as absent. A label that is not a string spells as compact JSON (`true`, `1`, `1e-7`), the same in Python and TypeScript. `basename_fields` strips URL/path parents from the named `group_by` fields. Leave a field out to preserve its complete value in one path-safe segment: `/` renders as `∕`, and a blank or dot-led value is led by `⁄`, so every value has its own segment that lists and opens. A basename longer than 255 bytes, which ext4 and APFS refuse, is cut to fit and ends in `__` plus the md5 of the whole name, so two long leaves stay two directories. Basenames must be unique within their parent group; Mirage refuses an ambiguous listing instead of silently merging two source documents, and opening a basename directory checks every point of its parent group, so a second source past `max_rows` is refused rather than hidden. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Qdrant mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `qdrant`, read | > > #### VFS Layout > > ##### `/<path>` > > * A Qdrant vector database, exposed as a filesystem. > * At the root each directory is a collection, unless config pins a > single collection. > * Inside a collection, directories are the configured group-by payload > fields; descending one narrows a filter. > * Each matching point appears as files named by its Qdrant point id: > `<id>.json` (the full payload), `<id>.txt` (the embedded source text) > when a text field is configured, and `<id>.<ext>` (raw blob bytes) > when a blob field is configured. The embedding vector is never shown. > * `ls`, `cd`, `cat`, `tree`, `find`, `wc`, `grep` and `rg` work as > usual. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `qdrant` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `qdrant`, read | > > ## VFS Layout > > ### `/<path>` > > - A Qdrant vector database, exposed as a filesystem. > - At the root each directory is a collection, unless config pins a > single collection. > - Inside a collection, directories are the configured group-by payload > fields; descending one narrows a filter. > - Each matching point appears as files named by its Qdrant point id: > `<id>.json` (the full payload), `<id>.txt` (the embedded source text) > when a text field is configured, and `<id>.<ext>` (raw blob bytes) > when a blob field is configured. The embedding vector is never shown. > - `ls`, `cd`, `cat`, `tree`, `find`, `wc`, `grep` and `rg` work as > usual. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `qdrant` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ``` Every path is translated into a Qdrant query. Descending a folder adds one payload filter; the leaf level lists points. ```text theme={null} / # list collections (omitted when `collection` is pinned) /<collection>/ # distinct group_by[0] values <v1>/ # distinct group_by[1] where group_by[0]=v1 .../<vN>/ # all group-by fields bound -> point files <id>.json # full payload (the metadata) <id>.txt # embedded source text (when text_field set) <id>.<ext> # raw blob / image bytes (when blob_field set) ``` `<id>` is the Qdrant point id. When `name_field` is set, leaf stems instead use `<name>__<id>`. When `collection` is set the collection level is elided, so the mount root is that collection: ```text theme={null} /fashion/ Men/ Shoes/ White/ 3.json 3.txt 3.jpg ``` ### Point files A point is shown as its underlying data in its original format, never as the embedding vector: * `<id>.txt` is the embedded source text (the `text_field` value), exactly what the vector was built from. * `<id>.json` is the full payload as compact JSON (the metadata), with the vector and the raw blob omitted. * `<id>.<ext>` is the raw blob bytes when `blob_field` is configured. ```text theme={null} $ cat /fashion/Men/Shoes/White/3.txt Nike Men White Running Sneakers $ cat /fashion/Men/Shoes/White/3.json {"gender":"Men","articleType":"Shoes","baseColour":"White","productDisplayName":"Nike Men White Running Sneakers","id":3} ``` ## Semantic search Search is the [`search` CLI](/python/cli/search), not a path. Register it on the workspace: ```python theme={null} from mirage.commands.cli.builtin.search import SEARCH ws.register_cli("search", SEARCH) ``` It returns each ranked point as its **canonical content path** (the `.txt`, or `.json` when no `text_field` is set) annotated with the similarity score, followed by the content: ```text theme={null} $ search "white running sneakers" /fashion /fashion/Men/Shoes/White/3.txt:0.7421 Nike Men White Running Sneakers ``` Flags: `--top-k <n>` (default `search_limit`), `--threshold <min-score>`, `--method semantic` (the only supported method; `grep`/`rg` stay lexical). ### Search embedding `search` needs a vector for the query, and the config decides where it comes from. With `embed` set, an async `(text: str) -> list[float]` the caller brings, the query is vectorized in-process, so a self-hosted Qdrant works and mirage depends on no model runtime; `examples/python/vfs/qdrant/qdrant_vfs.py` feeds it a dependency-free bag of words, and any model that returns a vector plugs in the same way. Without it, `cloud_inference=True` sends the query text to the server, so the cluster must have inference enabled (Qdrant Cloud) and store vectors from the same `embedding_model` (default `sentence-transformers/all-MiniLM-L6-v2`). With neither, `search` refuses the query. The hook never lands in a snapshot: a restored mount asks for a fresh VFS. ## Supported commands All commands delegate to Mirage's shared implementations. | Command | Behaviour on a Qdrant mount | | - | - | | `ls` | list collections, payload folders, or point files | | `cd` | navigate (each level narrows the filter) | | `tree` | render the folder hierarchy | | `cat` | print a point's text/JSON, or dump raw blob/image bytes | | `stat` | directory vs file, blob size, image mime type | | `find` | walk the tree (e.g. `find /fashion -name '*.txt'`) | | `grep` / `rg` | lexical search over the text/JSON files ([below](#integration)) | | `head` / `tail` | first/last lines of a file | | `wc` | count lines/bytes of a file | ## Integration What Qdrant answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Qdrant | | - | - | | `grep -r`, `rg` | The payload text the listing keeps, for ASCII text. It misses nothing. | A folder listing scrolls every point's payload anyway, so `grep -r` and `rg` scroll each folder once more, as a listing does, and read only the `.json` and `.txt` files whose text holds the pattern's text in any case. A point changed since the last listing is still found. A blob, a `.json` or `.txt` over 8 KiB, and every file for a text that is not ASCII are read as usual. ## Access pattern The mount is **read-only** (`MountMode.READ`); writes are not supported. The two read modes are: * **Browse** by payload folders: scroll filters on `group_by` fields, no embedding. * **Search** by meaning: the `search` CLI's `search "<query>" <path>` runs vector search and returns canonical point paths. Folder listings are capped by `max_rows`. A filtered listing scrolls first and only creates keyword payload indexes for the `group_by` fields if Qdrant reports one is required, so already-indexed collections work under read-only keys. Keep `group_by` to low-cardinality fields for large collections. # QingStor Source: https://docs.mirage.strukto.ai/python/vfs/qingstor Mount a QingStor (QingCloud) Object Storage bucket via its S3-compatible API. The QingStor VFS is a thin wrapper over the [S3 VFS](/python/vfs/s3). It maps a `QingStorConfig` to an `S3Config` and reuses the exact same backend, commands, and behavior as S3, it just derives the right endpoint from `region` (the QingStor zone). Uses aioboto3 against QingStor's S3-compatible API. The endpoint is computed from `region` as `s3.<region>.qingstor.com` (e.g. `s3.pek3a.qingstor.com`). This is QingStor's S3-compatible host, distinct from the native `<zone>.qingstor.com` API. Pass `endpoint_url` to override. Install the extra: ```bash theme={null} pip install "mirage-ai[s3]" ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.qingstor import QingStorConfig, QingStorVFS config = QingStorConfig( bucket=os.environ["QINGSTOR_BUCKET"], region=os.environ.get("QINGSTOR_ZONE", "pek3a"), access_key_id=os.environ["QINGSTOR_ACCESS_KEY_ID"], secret_access_key=os.environ["QINGSTOR_SECRET_ACCESS_KEY"], # Optional: # endpoint_url="https://s3.pek3a.qingstor.com", # timeout=30, # proxy="http://proxy:8080", ) vfs = QingStorVFS(config) ws = Workspace({"/data": vfs}, mode=MountMode.READ) ``` Both `READ` and `WRITE` modes are supported. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `bucket` required | Name of the bucket to mount. | | `region` required | Provider region every request is signed for. Most providers also build their endpoint URL from it unless `endpoint_url` is set. | | `endpoint_url` | Endpoint URL that replaces the one the provider derives. | | `access_key_id` secret | Access key ID; set it with `secret_access_key`. Unset uses the AWS credential chain. | | `secret_access_key` secret | Secret access key paired with `access_key_id`. | | `session_token` secret | Session token for temporary credentials, sent with the access key pair. | | `aws_profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `path_style` default `False` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `key_prefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | Fields marked secret are redacted in snapshots. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with QingStor mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.vfs.qingstor import QingStorConfig, QingStorVFS load_dotenv(".env.development") config = QingStorConfig( bucket=os.environ["QINGSTOR_BUCKET"], region=os.environ.get("QINGSTOR_ZONE", "pek3a"), endpoint_url=os.environ.get("QINGSTOR_ENDPOINT_URL"), access_key_id=os.environ["QINGSTOR_ACCESS_KEY_ID"], secret_access_key=os.environ["QINGSTOR_SECRET_ACCESS_KEY"], ) vfs = QingStorVFS(config) async def main() -> None: ws = Workspace({"/data/": vfs}, mode=MountMode.READ) r = await ws.shell("ls /data/") print(await r.stdout_str()) r = await ws.shell("find /data/ -name '*.json' | head -n 5") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Notes * QingStor registers under its own `VFSName` and routes through the same `core/s3` implementation, so the full S3 shell-command set applies. See the [S3 VFS](/python/vfs/s3) for the complete command reference, range reads, streaming, and the index cache fast path. * For credential setup, see [QingStor Setup](/home/setup/qingstor). # Cloudflare R2 Source: https://docs.mirage.strukto.ai/python/vfs/r2 Mount Cloudflare R2 storage as a virtual filesystem. The R2 VFS mounts a Cloudflare R2 bucket at some prefix such as `/r2/`. All operations involve network I/O to the remote object store. Uses aioboto3 against R2's S3-compatible API. For credential setup, see [R2 Setup](/home/setup/r2). Install the extra: ```bash theme={null} pip install "mirage-ai[r2]" ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.r2 import R2Config, R2VFS config = R2Config( bucket=os.environ["R2_BUCKET"], account_id=os.environ["R2_ACCOUNT_ID"], access_key_id=os.environ["R2_ACCESS_KEY_ID"], secret_access_key=os.environ["R2_SECRET_ACCESS_KEY"], # Optional: # endpoint_url="https://...r2.cloudflarestorage.com", # aws_profile="my-profile", # region="auto", # timeout=30, # proxy="http://proxy:8080", ) vfs = R2VFS(config=config) ws = Workspace({"/r2": vfs}, mode=MountMode.READ) ``` `R2VFS(config)` takes an `R2Config` object with the bucket name and either `account_id` (endpoint is auto-built as `https://{account_id}.r2.cloudflarestorage.com`) or an explicit `endpoint_url`. Both `READ` and `WRITE` modes are supported. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `bucket` required | Name of the bucket to mount. | | `region` default `'auto'` | Region requests are signed for; R2 addresses a bucket by account, not by region. | | `endpoint_url` | Endpoint URL that replaces the one the provider derives. | | `access_key_id` secret | Access key ID; set it with `secret_access_key`. Unset uses the AWS credential chain. | | `secret_access_key` secret | Secret access key paired with `access_key_id`. | | `session_token` secret | Session token for temporary credentials, sent with the access key pair. | | `aws_profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `path_style` default `False` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `key_prefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | | `account_id` | Cloudflare account ID. It builds the endpoint `https://<account_id>.r2.cloudflarestorage.com` unless `endpoint_url` is set; one of the two is required. | Fields marked secret are redacted in snapshots. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Cloudflare R2 mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` The R2 VFS maps object keys to virtual paths under the mount prefix. R2 "directories" are prefix-based — there are no real directory objects. For example, if bucket `my-bucket` contains: ```text theme={null} assets/logo.png assets/style.css data/export.parquet data/metrics.csv ``` Then mounting at `/r2/` exposes: ```text theme={null} /r2/ assets/ logo.png style.css data/ export.parquet metrics.csv ``` Path mapping: virtual `/r2/assets/logo.png` maps to R2 key `assets/logo.png`. ## Cache The R2 VFS uses `IndexCacheStore` with `index_ttl = 600` (10 minutes). Directory listings are cached for up to 600 seconds before being refreshed from R2. This reduces API calls for repeated directory traversals. A configured `index:` replaces this lifetime with its own `ttl`, and the mount's `ttl:` caps it. ## Integration What R2 answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On R2 | | - | - | | `md5sum` | The object's ETag, when it is the MD5: a single-part upload, unencrypted or under SSE-S3 | | `find`, `du`, `ls -R`, `tree` | One recursive listing | ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.vfs.r2 import R2Config, R2VFS load_dotenv(".env.development") config = R2Config( bucket=os.environ["R2_BUCKET"], account_id=os.environ["R2_ACCOUNT_ID"], access_key_id=os.environ["R2_ACCESS_KEY_ID"], secret_access_key=os.environ["R2_SECRET_ACCESS_KEY"], ) vfs = R2VFS(config=config) async def main() -> None: ws = Workspace({"/r2/": vfs}, mode=MountMode.READ) r = await ws.shell("ls /r2/") print(await r.stdout_str()) r = await ws.shell("cat /r2/data/metrics.csv | head -n 10") print(await r.stdout_str()) r = await ws.shell("tree /r2/") print(await r.stdout_str()) r = await ws.shell("find /r2/ -name '*.csv'") print(await r.stdout_str()) r = await ws.shell("stat /r2/assets/logo.png") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Shell Commands The R2 VFS supports the full set of shell commands since it operates on real file content (text, binary, JSON, CSV, etc.). Large files benefit from range reads to avoid downloading entire objects. ### Read Commands | Command | Notes | | - | - | | `cat` | Read file content | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search (file or directory level) | | `jq` | Query JSON fields | | `wc` | Line/word/byte counts | | `stat` | File metadata (name, size, type, modified) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `nl` | Number lines | | `du` | Disk usage summary | | `file` | Detect file type | | `strings` | Extract printable strings from binary | | `xxd` | Hex dump | | `md5` | MD5 checksum | | `sha256sum` | SHA-256 checksum | ### Text Processing | Command | Notes | | - | - | | `awk` | Pattern scanning and processing | | `sed` | Stream editor | | `tr` | Translate or delete characters | | `sort` | Sort lines | | `uniq` | Remove duplicate lines | | `cut` | Extract fields/columns | | `join` | Join lines on a common field | | `paste` | Merge lines side by side | | `column` | Columnate output | | `fold` | Wrap lines to a specified width | | `expand` | Convert tabs to spaces | | `unexpand` | Convert spaces to tabs | | `fmt` | Simple text formatter | | `rev` | Reverse lines | | `tac` | Concatenate and print in reverse | | `look` | Display lines beginning with a given string | | `shuf` | Shuffle lines | | `tsort` | Topological sort | | `comm` | Compare two sorted files | | `cmp` | Compare two files byte by byte | | `diff` | Compare files line by line | | `patch` | Apply a diff patch | | `iconv` | Character encoding conversion | ### File Operations | Command | Notes | | - | - | | `cp` | Copy files | | `mv` | Move/rename files | | `rm` | Remove files | | `mkdir` | Create directories | | `touch` | Create empty file or update timestamp | | `ln` | Create symbolic links | | `tee` | Write stdin to file and stdout | | `mktemp` | Create temporary file | | `split` | Split file into pieces | | `csplit` | Split file by context | ### Path Utilities | Command | Notes | | - | - | | `basename` | Strip directory from path | | `dirname` | Strip filename from path | | `realpath` | Resolve path | | `readlink` | Print symbolic link target | | `ls` | List directory contents | ### Compression | Command | Notes | | - | - | | `gzip` | Compress files | | `gunzip` | Decompress gzip files | | `zip` | Create zip archives | | `unzip` | Extract zip archives | | `tar` | Archive files | | `zcat` | Cat compressed files | | `zgrep` | Grep compressed files | ### Encoding | Command | Notes | | - | - | | `base64` | Base64 encode/decode | ## Use Cases * **AI agents accessing R2 data**: Mount R2 buckets for agents to read and process datasets * **Data pipelines**: Read and write R2 objects with shell-like commands * **FUSE mounting**: Expose R2 buckets through a virtual FUSE mount for external tools # RAM Source: https://docs.mirage.strukto.ai/python/vfs/ram Use an in-memory Mirage filesystem for temporary files, tests, examples, and writable agent scratch space. The RAM VFS exposes an in-memory filesystem mounted at some prefix such as `/data/`. All data lives in process memory and is lost on exit. No setup or credentials required. ## Config ```python theme={null} from mirage import MountMode, Workspace from mirage.vfs.ram import RAMVFS vfs = RAMVFS() ws = Workspace({"/data": vfs}, mode=MountMode.WRITE) ``` `RAMVFS()` needs no configuration object. `RAMVFS(capacity="100MB")` caps the bytes the store holds; a write past it fails with "Disk quota exceeded". See [capacity](/home/configuration#capacity). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with RAM mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `grep -r`, `find` and `du` stop after 10000 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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `grep -r`, `find` and `du` stop after 10000 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. > ``` The RAM filesystem starts empty. Files and directories are created on demand via commands like `touch`, `mkdir`, `tee`, `cp`, etc. ```text theme={null} /data/ notes.txt config.json reports/ q1.csv q2.csv uploads/ image.png ``` Paths are normalized with a leading `/`. The root directory `/` always exists. ## Cache The RAM VFS uses `IndexCacheStore` with `index_ttl = 0`, so its listings are not cached: the data is in memory, and every listing reads it. A workspace or mount `index:` block still applies its `ttl` to this mount. ## Integration What RAM answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On RAM | | - | - | | `find`, `du`, `ls -R`, `tree` | One recursive listing | ## Example ```python theme={null} import asyncio from mirage import MountMode, Workspace from mirage.vfs.ram import RAMVFS vfs = RAMVFS() async def main() -> None: ws = Workspace({"/data": vfs}, mode=MountMode.WRITE) # Create files await ws.shell('echo "hello world" | tee /data/hello.txt') await ws.shell('echo \'{"name": "alice", "age": 30}\' | tee /data/user.json') await ws.shell("mkdir /data/reports") await ws.shell('echo "revenue,100" | tee /data/reports/q1.csv') # Read r = await ws.shell("cat /data/hello.txt") print(await r.stdout_str()) # List r = await ws.shell("ls /data/") print(await r.stdout_str()) # Query JSON r = await ws.shell('jq ".name" /data/user.json') print(await r.stdout_str()) # Search r = await ws.shell("grep hello /data/hello.txt") print(await r.stdout_str()) # Tree r = await ws.shell("tree /data/") print(await r.stdout_str()) # File info r = await ws.shell("stat /data/hello.txt") print(await r.stdout_str()) # Copy, move, remove await ws.shell("cp /data/hello.txt /data/hello_copy.txt") await ws.shell("mv /data/hello_copy.txt /data/renamed.txt") await ws.shell("rm /data/renamed.txt") await ws.close() if __name__ == "__main__": asyncio.run(main()) ``` ## Shell Commands The RAM VFS supports the full set of shell commands since it handles real file content (text, binary, JSON, CSV, etc.): ### Read Commands | Command | Notes | | - | - | | `cat` | Read file content | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search (file or directory level) | | `jq` | Query JSON fields | | `wc` | Line/word/byte counts | | `stat` | File metadata (name, size, type, modified) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `nl` | Number lines | | `du` | Disk usage summary | | `file` | Detect file type | | `strings` | Extract printable strings from binary | | `xxd` | Hex dump | | `md5` | MD5 checksum | | `sha256sum` | SHA-256 checksum | ### Text Processing | Command | Notes | | - | - | | `awk` | Pattern scanning and processing | | `sed` | Stream editor | | `tr` | Translate or delete characters | | `sort` | Sort lines | | `uniq` | Remove duplicate lines | | `cut` | Extract fields/columns | | `join` | Join lines on a common field | | `paste` | Merge lines side by side | | `column` | Columnate output | | `fold` | Wrap lines to a specified width | | `expand` | Convert tabs to spaces | | `unexpand` | Convert spaces to tabs | | `fmt` | Simple text formatter | | `rev` | Reverse lines | | `tac` | Concatenate and print in reverse | | `look` | Display lines beginning with a given string | | `shuf` | Shuffle lines | | `tsort` | Topological sort | | `comm` | Compare two sorted files | | `cmp` | Compare two files byte by byte | | `diff` | Compare files line by line | | `patch` | Apply a diff patch | | `iconv` | Character encoding conversion | ### File Operations | Command | Notes | | - | - | | `cp` | Copy files | | `mv` | Move/rename files | | `rm` | Remove files | | `mkdir` | Create directories | | `touch` | Create empty file or update timestamp | | `ln` | Create symbolic links | | `tee` | Write stdin to file and stdout | | `mktemp` | Create temporary file | | `split` | Split file into pieces | | `csplit` | Split file by context | ### Path Utilities | Command | Notes | | - | - | | `basename` | Strip directory from path | | `dirname` | Strip filename from path | | `realpath` | Resolve path | | `readlink` | Print symbolic link target | | `ls` | List directory contents | ### Compression | Command | Notes | | - | - | | `gzip` | Compress files | | `gunzip` | Decompress gzip files | | `zip` | Create zip archives | | `unzip` | Extract zip archives | | `tar` | Archive files | | `zcat` | Cat compressed files | | `zgrep` | Grep compressed files | ### Encoding | Command | Notes | | - | - | | `base64` | Base64 encode/decode | ## Use Cases * **Testing**: Fast filesystem for unit tests without I/O * **Staging**: Temporary data area during pipelines * **Prototyping**: Develop against a filesystem before switching to S3/disk * **Caching**: In-process data exchange between commands * **Ephemeral workspaces**: Create, process, discard - no cleanup needed # Redis Source: https://docs.mirage.strukto.ai/python/vfs/redis Mount a Redis-backed virtual filesystem. The Redis VFS creates a persistent virtual filesystem backed by Redis. It supports full read and write operations. Install the extra: ```bash theme={null} pip install "mirage-ai[redis]" ``` ## Config ```python theme={null} from mirage import MountMode, Workspace from mirage.vfs.redis import RedisVFS vfs = RedisVFS( url="redis://localhost:6379/0", key_prefix="mirage:fs:", ) ws = Workspace({"/redis": vfs}, mode=MountMode.WRITE) ``` | Parameter | Required | Default | Description | | - | - | - | - | | `url` | no | `redis://localhost:6379/0` | Redis connection URL | | `key_prefix` | no | `mirage:fs:` | Key namespace prefix | Keys are stored as: * `{prefix}file:{path}` - file content (raw bytes) * `{prefix}dir` - Redis set of directory paths * `{prefix}modified:{path}` - modification timestamps ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Redis mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ```text theme={null} /redis/ <file> <directory>/ <file> <subdirectory>/ <file> ``` The filesystem is fully user-defined - create any directory structure with `mkdir`, `touch`, `tee`, etc. Example: ```text theme={null} /redis/ config.json logs/ app.log error.log cache/ session-abc.json ``` ## Cache Index TTL is `0`, so listings are read from Redis every time. A workspace `index:` block still applies its `ttl` to this mount. ## Integration What Redis answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Redis | | - | - | | `find`, `du`, `ls -R`, `tree` | One recursive listing | ## Example ```python theme={null} import asyncio from mirage import MountMode, Workspace from mirage.vfs.redis import RedisVFS vfs = RedisVFS(url="redis://localhost:6379/0") async def main(): ws = Workspace({"/redis": vfs}, mode=MountMode.WRITE) # Create directories and files await ws.shell("mkdir -p /redis/data/") await ws.shell('echo "hello world" | tee /redis/data/hello.txt') # Read back r = await ws.shell("cat /redis/data/hello.txt") print(await r.stdout_str()) # List files r = await ws.shell("ls /redis/data/") print(await r.stdout_str()) # Copy and move await ws.shell("cp /redis/data/hello.txt /redis/data/copy.txt") await ws.shell("mv /redis/data/copy.txt /redis/data/renamed.txt") # Search r = await ws.shell('grep -r "hello" /redis/data/') print(await r.stdout_str()) # Clean up await ws.shell("rm -r /redis/data/") if __name__ == "__main__": asyncio.run(main()) ``` ## Shell Commands | Command | Notes | | - | - | | `ls` | List files and directories | | `cat` | Read file content | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search | | `wc` | Line/word/byte counts | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `mkdir` | Create directories | | `touch` | Create empty files | | `cp` / `mv` / `rm` | Copy, move, delete | | `tee` | Write stdin to file | | `diff` / `cmp` | Compare files | | `sort` / `cut` / `tr` | Text processing | | `tar` / `zip` / `gzip` | Compression | | `base64` / `md5` / `sha256sum` | Encoding and checksums | # S3 Source: https://docs.mirage.strukto.ai/python/vfs/s3 Mount AWS S3 or S3-compatible buckets as a Mirage filesystem with async access, caching, and shell commands. The S3 VFS mounts an Amazon S3 bucket (or any S3-compatible service) at some prefix such as `/s3/`. All operations involve network I/O to the remote object store. Uses aioboto3 for async S3 access. Compatible with: AWS S3, MinIO, Cloudflare R2, Supabase Storage, DigitalOcean Spaces, and any S3-compatible service. Install the extra: ```bash theme={null} pip install "mirage-ai[s3]" ``` ## Config ```python theme={null} from mirage import MountMode, Workspace from mirage.vfs.s3 import S3VFS, S3Config config = S3Config( bucket="my-bucket", region="us-east-1", # Optional: # aws_access_key_id="...", # aws_secret_access_key="...", # aws_profile="my-profile", # endpoint_url="http://localhost:9000", # MinIO # path_style=True, # For MinIO/R2 # timeout=30, # proxy="http://proxy:8080", ) vfs = S3VFS(config) ws = Workspace({"/s3": vfs}, mode=MountMode.READ) ``` `S3VFS(config)` takes an `S3Config` object with the bucket name and optional credentials, endpoint, and connection settings. Both `READ` and `WRITE` modes are supported. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `region` | AWS region requests are signed for and sent to. Unset leaves it to the AWS SDK's environment variables and profile. | | `aws_access_key_id` secret | Access key ID; set it with `aws_secret_access_key`. Unset uses the AWS credential chain. | | `aws_secret_access_key` secret | Secret access key paired with `aws_access_key_id`. | | `aws_session_token` secret | Session token for temporary credentials, sent with the access key pair. | | `aws_profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `bucket` required | Name of the bucket to mount. | | `endpoint_url` | Endpoint URL of an S3-compatible server. Unset uses `AWS_ENDPOINT_URL_S3` or `AWS_ENDPOINT_URL` when set, else AWS's endpoint for `region`; an endpoint set only in an AWS profile is not read. | | `path_style` default `False` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | | `key_prefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `default_content_type` | `Content-Type` stored with every object the mount writes. Unset sends none, so the store applies its own default. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with S3 mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` The S3 VFS maps S3 object keys to virtual paths under the mount prefix. S3 "directories" are prefix-based - there are no real directory objects. For example, if bucket `my-bucket` contains: ```text theme={null} data/file.txt data/config.json reports/q1.csv reports/q2.csv ``` Then mounting at `/s3/` exposes: ```text theme={null} /s3/ data/ file.txt config.json reports/ q1.csv q2.csv ``` Path mapping: virtual `/s3/data/file.txt` maps to S3 key `data/file.txt`. ## Cache The S3 VFS uses `IndexCacheStore` with `index_ttl = 600` (10 minutes). Directory listings are cached for up to 600 seconds before being refreshed from S3. This reduces API calls for repeated directory traversals. A configured `index:` replaces this lifetime with its own `ttl`, and the mount's `ttl:` caps it. ## Conditional writes Under `write: conditional` a write carries the version of the file mirage read, and S3 refuses it when the file has changed since. The endpoint decides which writes can be conditioned: AWS's conditions every write, copy and delete; any other `endpoint_url` (or `AWS_ENDPOINT_URL_S3`/`AWS_ENDPOINT_URL`) only a write, so mirage refuses what would copy or delete there. An endpoint set only in an AWS profile is not read: give a non-AWS server its `endpoint_url`. If the session last saw no file at the path, the write sends `If-None-Match: *` and fails if someone created the file in the meantime. A conditional single-file move attempts rollback when source deletion is refused. The move still fails and warns if the destination may remain. Cleanup uses the copy's S3 version or, for a new destination, its ETag. Unversioned overwrites, same-ETag replacements, retried versioned copies, and uncertain delete outcomes limit recovery; inspect both paths after a failure. An absent destination must remain absent until copying. This guard may add one metadata request; cleanup adds one delete and may require `s3:DeleteObjectVersion`. Directory and cross-mount moves do not use rollback. A directory `mv`, `rm -r` or `rmdir` looks at the directory again when it is done: a file written into it that the command never listed stays, and the command fails with `Directory not empty`. Under `write: conditional`, a directory `mv` that finds a file changed before it could copy it removes nothing from the source; the copies it made stay at the destination. An append or another rewrite that observes a missing file uses create-only commit under either write policy. S3 checks `If-None-Match: *` at PUT or final multipart completion, so a delayed creation cannot replace a competing writer's bytes. A lost condition returns an error without automatic retry. Existing-file appends under `unconditional` retain last-write-wins behavior. ## Refused keys When credentials cannot read an S3 object (S3 returns `AccessDenied`, or a bodiless HTTP 403 response on a `HEAD` request), Mirage reports `EACCES` (`Permission denied`) for that file operand. Shell commands follow standard POSIX conventions: * `cat a b c` prints the contents of `a` and `c`, writes a permission error for `b` to `stderr`, and exits with a non-zero status. * `grep -r` logs an error on inaccessible files and exits with status `2`. * `cp b x || fallback` triggers the fallback branch. * `test -e b` evaluates to false. ### IAM permissions and existence checks * **Scoped grants:** When access is granted below a specific prefix (for example, `s3:GetObject` on `bucket/dir/*` alongside `s3:ListBucket` on the bucket), Mirage treats `dir` as a directory during `stat`. * **Missing `ListBucket`:** Without `s3:ListBucket` permission, S3 returns HTTP 403 even for non-existent keys to avoid leaking existence. As a result, non-existent files report `Permission denied` (`EACCES`) instead of `No such file or directory` (`ENOENT`). * **Listed but unreadable keys:** If `ListObjectsV2` includes an object that your credentials cannot read, `stat` and `test -e` report that the file exists, while read attempts (`cat`) fail with `Permission denied`. ## Integration What S3 answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On S3 | | - | - | | `md5sum` | The object's ETag, when it is the MD5: a single-part upload, unencrypted or under SSE-S3 | | `find`, `du`, `ls -R`, `tree` | One recursive listing | ## Example ```python theme={null} import asyncio from mirage import MountMode, Workspace from mirage.vfs.s3 import S3VFS, S3Config config = S3Config( bucket="my-bucket", region="us-east-1", ) vfs = S3VFS(config) async def main() -> None: ws = Workspace({"/s3/": vfs}, mode=MountMode.READ) r = await ws.shell("ls /s3/") print(await r.stdout_str()) r = await ws.shell("cat /s3/data/file.txt") print(await r.stdout_str()) r = await ws.shell("tree /s3/") print(await r.stdout_str()) r = await ws.shell("find /s3/ -name '*.json'") print(await r.stdout_str()) r = await ws.shell("grep example /s3/data/config.json") print(await r.stdout_str()) r = await ws.shell("stat /s3/data/file.txt") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Shell Commands The S3 VFS supports the full set of shell commands since it operates on real file content (text, binary, JSON, CSV, etc.). Large files benefit from range reads to avoid downloading entire objects. ### Customize a builtin command The generic command definitions are available before a workspace is created. Copy the definition with the behavior you want to change, then register that copy on one mount: ```python theme={null} from dataclasses import replace from mirage import generic cat = generic("cat") async def logged_cat(accessor, paths, texts, opts): print("reading", [path.virtual for path in paths]) return await cat.fn(accessor, paths, texts, opts) ws.mount("/s3/").register(replace(cat, fn=logged_cat)) ``` The builtin definition and other mounts stay unchanged. Registration is a host application action; an agent can discover and run the resulting `cat` command, but cannot alter the command table. ### Read Commands | Command | Notes | | - | - | | `cat` | Read file content | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search (file or directory level) | | `jq` | Query JSON fields | | `wc` | Line/word/byte counts | | `stat` | File metadata (name, size, type, modified) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `nl` | Number lines | | `du` | Disk usage summary | | `file` | Detect file type | | `strings` | Extract printable strings from binary | | `xxd` | Hex dump | | `md5` | MD5 checksum | | `sha256sum` | SHA-256 checksum | ### Text Processing | Command | Notes | | - | - | | `awk` | Pattern scanning and processing | | `sed` | Stream editor | | `tr` | Translate or delete characters | | `sort` | Sort lines | | `uniq` | Remove duplicate lines | | `cut` | Extract fields/columns | | `join` | Join lines on a common field | | `paste` | Merge lines side by side | | `column` | Columnate output | | `fold` | Wrap lines to a specified width | | `expand` | Convert tabs to spaces | | `unexpand` | Convert spaces to tabs | | `fmt` | Simple text formatter | | `rev` | Reverse lines | | `tac` | Concatenate and print in reverse | | `look` | Display lines beginning with a given string | | `shuf` | Shuffle lines | | `tsort` | Topological sort | | `comm` | Compare two sorted files | | `cmp` | Compare two files byte by byte | | `diff` | Compare files line by line | | `patch` | Apply a diff patch | | `iconv` | Character encoding conversion | ### File Operations | Command | Notes | | - | - | | `cp` | Copy files | | `mv` | Move/rename files | | `rm` | Remove files | | `mkdir` | Create directories | | `touch` | Create empty file or update timestamp | | `ln` | Create symbolic links | | `tee` | Write stdin to file and stdout | | `mktemp` | Create temporary file | | `split` | Split file into pieces | | `csplit` | Split file by context | ### Path Utilities | Command | Notes | | - | - | | `basename` | Strip directory from path | | `dirname` | Strip filename from path | | `realpath` | Resolve path | | `readlink` | Print symbolic link target | | `ls` | List directory contents | ### Compression | Command | Notes | | - | - | | `gzip` | Compress files | | `gunzip` | Decompress gzip files | | `zip` | Create zip archives | | `unzip` | Extract zip archives | | `tar` | Archive files | | `zcat` | Cat compressed files | | `zgrep` | Grep compressed files | ### Encoding | Command | Notes | | - | - | | `base64` | Base64 encode/decode | ## Use Cases * **AI agents accessing cloud data**: Mount S3 buckets for agents to read and process remote datasets * **Data pipelines**: Read and write S3 objects with shell-like commands * **Sandboxed cloud storage access**: Restrict agent operations to a specific bucket and prefix * **FUSE mounting**: Expose S3 buckets through a virtual FUSE mount for external tools ## Scoping a VFS to a key prefix Pass `key_prefix: str | None = None` to `S3Config` to transparently scope every operation to a subpath of the bucket: ```python theme={null} S3VFS(S3Config( bucket="app-data", region="eu-west-1", key_prefix=f"users/{user_id}/", )) ``` When set, every read/write/list/stat/copy/rename/delete operation is transparently scoped to that bucket subpath. Agents see clean paths like `/data/notes.md`; the underlying bucket key is `users/{user_id}/data/notes.md`. Useful for multi-tenant systems. Pairs naturally with STS AssumeRole session policies for AWS-side enforcement. Unset behavior is unchanged. **Normalization:** leading slashes are stripped and a trailing slash is added automatically. Both `None` and an empty string are treated as "no prefix." # Scaleway Source: https://docs.mirage.strukto.ai/python/vfs/scaleway Mount a Scaleway Object Storage bucket via its S3-compatible API. The Scaleway VFS is a thin wrapper over the [S3 VFS](/python/vfs/s3). It maps a `ScalewayConfig` to an `S3Config` and reuses the exact same backend, commands, and behavior as S3, it just derives the right endpoint from `region`. Uses aioboto3 against Scaleway Object Storage's S3-compatible API. The endpoint is computed from `region` as `s3.<region>.scw.cloud` (e.g. `s3.fr-par.scw.cloud`). Pass `endpoint_url` to override. Install the extra: ```bash theme={null} pip install "mirage-ai[s3]" ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.scaleway import ScalewayConfig, ScalewayVFS config = ScalewayConfig( bucket=os.environ["SCW_BUCKET"], region=os.environ.get("SCW_REGION", "fr-par"), access_key_id=os.environ["SCW_ACCESS_KEY"], secret_access_key=os.environ["SCW_SECRET_KEY"], # Optional: # endpoint_url="https://s3.fr-par.scw.cloud", # timeout=30, # proxy="http://proxy:8080", ) vfs = ScalewayVFS(config) ws = Workspace({"/data": vfs}, mode=MountMode.READ) ``` Both `READ` and `WRITE` modes are supported. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `bucket` required | Name of the bucket to mount. | | `region` required | Provider region every request is signed for. Most providers also build their endpoint URL from it unless `endpoint_url` is set. | | `endpoint_url` | Endpoint URL that replaces the one the provider derives. | | `access_key_id` secret | Access key ID; set it with `secret_access_key`. Unset uses the AWS credential chain. | | `secret_access_key` secret | Secret access key paired with `access_key_id`. | | `session_token` secret | Session token for temporary credentials, sent with the access key pair. | | `aws_profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `path_style` default `False` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `key_prefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | Fields marked secret are redacted in snapshots. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Scaleway mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.vfs.scaleway import ScalewayConfig, ScalewayVFS load_dotenv(".env.development") config = ScalewayConfig( bucket=os.environ["SCW_BUCKET"], region=os.environ.get("SCW_REGION", "fr-par"), access_key_id=os.environ["SCW_ACCESS_KEY"], secret_access_key=os.environ["SCW_SECRET_KEY"], ) vfs = ScalewayVFS(config) async def main() -> None: ws = Workspace({"/data/": vfs}, mode=MountMode.READ) r = await ws.shell("ls /data/") print(await r.stdout_str()) r = await ws.shell("tree /data/") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Notes * Scaleway registers under its own `VFSName` and routes through the same `core/s3` implementation, so the full S3 shell-command set applies. See the [S3 VFS](/python/vfs/s3) for the complete command reference, range reads, streaming, and the index cache fast path. * For credential setup, see [Scaleway Setup](/home/setup/scaleway). # SeaweedFS Source: https://docs.mirage.strukto.ai/python/vfs/seaweedfs Mount a SeaweedFS bucket as a virtual filesystem. The SeaweedFS VFS is a thin wrapper over the [S3 VFS](/python/vfs/s3). It maps a `SeaweedFSConfig` to an `S3Config` and reuses the exact same backend, commands, and behavior as S3, it just points at your SeaweedFS S3 gateway `endpoint_url` and uses path-style addressing by default. SeaweedFS exposes an S3-compatible gateway (default port `8333`), so `endpoint_url` is **required** (there is no region-derived host). Uses aioboto3 against the SeaweedFS S3 API. Install the extra: ```bash theme={null} pip install "mirage-ai[s3]" ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.seaweedfs import SeaweedFSConfig, SeaweedFSVFS config = SeaweedFSConfig( bucket=os.environ["SEAWEEDFS_BUCKET"], endpoint_url=os.environ.get("SEAWEEDFS_ENDPOINT", "http://localhost:8333"), access_key_id=os.environ["SEAWEEDFS_ACCESS_KEY"], secret_access_key=os.environ["SEAWEEDFS_SECRET_KEY"], # Optional: # region="us-east-1", # default # path_style=True, # default; SeaweedFS uses path-style addressing # timeout=30, # proxy="http://proxy:8080", ) vfs = SeaweedFSVFS(config) ws = Workspace({"/seaweedfs": vfs}, mode=MountMode.WRITE) ``` Both `READ` and `WRITE` modes are supported. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `bucket` required | Name of the bucket to mount. | | `region` default `'us-east-1'` | Region requests are signed for; the gateway's endpoint does not depend on it. | | `endpoint_url` required | URL of the self-hosted S3 gateway, such as `http://localhost:9000`. | | `access_key_id` secret | Access key ID; set it with `secret_access_key`. Unset uses the AWS credential chain. | | `secret_access_key` secret | Secret access key paired with `access_key_id`. | | `session_token` secret | Session token for temporary credentials, sent with the access key pair. | | `aws_profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `path_style` default `True` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `key_prefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | Fields marked secret are redacted in snapshots. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with SeaweedFS mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.vfs.seaweedfs import SeaweedFSConfig, SeaweedFSVFS load_dotenv(".env.development") config = SeaweedFSConfig( bucket=os.environ.get("SEAWEEDFS_BUCKET", "mirage-demo"), endpoint_url=os.environ.get("SEAWEEDFS_ENDPOINT", "http://localhost:8333"), access_key_id=os.environ.get("SEAWEEDFS_ACCESS_KEY", "any"), secret_access_key=os.environ.get("SEAWEEDFS_SECRET_KEY", "any"), ) vfs = SeaweedFSVFS(config) async def main() -> None: ws = Workspace({"/seaweedfs/": vfs}, mode=MountMode.READ) r = await ws.shell("ls /seaweedfs/") print(await r.stdout_str()) r = await ws.shell("tree /seaweedfs/") print(await r.stdout_str()) r = await ws.shell("cat /seaweedfs/data/config.json") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Notes * SeaweedFS registers under its own `VFSName` and routes through the same `core/s3` implementation, so the full S3 shell-command set applies (`ls`, `cat`, `head`, `tail`, `grep`, `rg`, `wc`, `find`, `tree`, `jq`, `stat`). See the [S3 VFS](/python/vfs/s3) for the complete command reference, range reads, streaming, and the index cache fast path. * Blaxel Agent Drive is backed by SeaweedFS. To mount a drive's S3 gateway, point `endpoint_url` at the drive's `s3Url` and supply credentials for it. * For credential setup, see [SeaweedFS Setup](/home/setup/seaweedfs). # SharePoint Source: https://docs.mirage.strukto.ai/python/vfs/sharepoint Mount Microsoft SharePoint Online sites and document libraries as a Mirage filesystem with multi-site discovery, versioning, and shell commands. The SharePoint VFS mounts Microsoft SharePoint Online at some prefix such as `/sharepoint/`. Unlike the single-drive OneDrive VFS, it exposes the full enterprise topology: many sites, each with many document libraries. Site and drive names are resolved to Microsoft Graph ids automatically, so you mount once and browse everything you have access to. All operations involve network I/O to Microsoft Graph. Files are served as raw bytes (no Office filetype conversion). Uses aiohttp for async Graph access. For credential setup (tokens, app vs delegated auth, permissions), see the [SharePoint Setup](/home/setup/sharepoint) guide. ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.sharepoint import SharePointVFS, SharePointConfig config = SharePointConfig( access_token=os.environ["MS_GRAPH_DRIVE_TOKEN"], # Optional: # tenant_host="contoso.sharepoint.com", # restrict to one tenant host # site_filter="Engineering", # narrow the site search # site="Engineering", # mount one site # drive="Documents", # mount one library # key_prefix="team/reports", # mount one folder subtree # graph_base_url="https://graph.microsoft.us/v1.0", # non-worldwide root # timeout=30, # max_retries=5, ) vfs = SharePointVFS(config) ws = Workspace({"/sharepoint": vfs}, mode=MountMode.WRITE) ``` `SharePointVFS(config)` takes a `SharePointConfig` object with a Microsoft Graph bearer token. No drive id is required: the VFS discovers sites and drives for you. Both `READ` and `WRITE` modes are supported. ### Config Reference | Field | Description | | - | - | | `access_token` required, secret | Microsoft Graph bearer token, or a callable that returns one; it is called for each request and again after a `401`. | | `tenant_host` | SharePoint host, such as `contoso.sharepoint.com`; the `sharepoint` mount lists only the sites whose `webUrl` is on it. The `onedrive` mount ignores it. | | `graph_base_url` | Full Graph service root, version segment included, for any deployment but the worldwide one: a sovereign cloud, a private endpoint or a test server. Unset uses `https://graph.microsoft.com/v1.0`. | | `timeout` default `30` | Seconds a Graph request may wait to connect, or between two reads of its answer, before it fails; also how long a server-side copy is polled before it fails as unconfirmed. | | `max_retries` default `5` | Times a request is retried after a `429`, `503` or `504` response. Each retry waits what `Retry-After` asks or an exponential backoff, at most 30 seconds. | | `site_filter` | Search term passed to Graph's `/sites?search=` to choose which sites the mount lists. Unset searches `*`. | | `site` | Site, by display name or internal name, that scopes the mount to one document library together with `drive`. With either unset the mount lists every site as `/<site>/<library>/...`. | | `drive` | Document library in `site` that the mount uses as its root; takes effect only with `site` set. | | `key_prefix` | Folder path inside the scoped library that the mount uses as its root; takes effect only with `site` and `drive` set. `..` segments are rejected. | Fields marked secret are redacted in snapshots. `access_token` accepts either a static string or a `Callable[[], str]` provider. With a callable, the VFS refreshes the token on `401`, so long-running mounts survive token expiry. `graph_base_url` selects the Graph deployment, and means the same here as for OneDrive: see [The service root](/python/vfs/onedrive#the-service-root). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with SharePoint mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `sharepoint`, write | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > <site>/ # every SharePoint site you can reach > <library>/ # its document libraries (drives) > <path> # the drive's files and folders > ``` > > * SharePoint document libraries, discovered across sites and drives. An > unscoped mount reads `/{site_name}/{library_name}/{path_to_file}`: > `ls /` lists the sites, `ls /site/` a site's libraries, and > `ls /site/lib/...` a drive's files and folders. > * This is a remote mount: prefer targeted reads (`grep`, `head`) over > full scans, and pipe a large file to `head` or `tail` rather than > `cat` it whole. > * File versions are retained; a snapshot pins and reads prior > versions. > > #### 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 `sharepoint` 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>` | `sharepoint`, write | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > <site>/ # every SharePoint site you can reach > <library>/ # its document libraries (drives) > <path> # the drive's files and folders > ``` > > - SharePoint document libraries, discovered across sites and drives. An > unscoped mount reads `/{site_name}/{library_name}/{path_to_file}`: > `ls /` lists the sites, `ls /site/` a site's libraries, and > `ls /site/lib/...` a drive's files and folders. > - This is a remote mount: prefer targeted reads (`grep`, `head`) over > full scans, and pipe a large file to `head` or `tail` rather than > `cat` it whole. > - File versions are retained; a snapshot pins and reads prior > versions. > > ## 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 `sharepoint` 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. > ```` SharePoint paths follow the structure `/{site}/{library}/{path}`. The first two levels are virtual (sites and drives), and everything below is a real Graph driveItem. * **Level 0** (`/sharepoint/`): lists all accessible sites * **Level 1** (`/sharepoint/{site}/`): lists document libraries (drives) in that site * **Level 2+** (`/sharepoint/{site}/{library}/...`): lists files and folders Path mapping: virtual `/sharepoint/Engineering/Documents/spec.md` resolves the site `Engineering` to a site id, the library `Documents` to a drive id, then reads the driveItem at `/root:/spec.md`. When `site` and `drive` are configured, those two namespace levels disappear. Adding `key_prefix="team/reports"` makes that folder the mount root, so virtual `/sharepoint/q1.csv` resolves to the driveItem at `/root:/team/reports/q1.csv`. ## Versioning and Snapshots SharePoint keeps per-file version history. The VFS exposes it the same way the OneDrive and S3 backends do: * **Fingerprint** is the driveItem `cTag`, so normal reads and `stat` reflect the current content without extra Graph calls. * **Snapshots** pin each file the agent read to its driveItem version id. Replaying a snapshot reads `/versions/{id}/content`, giving the exact bytes captured at snapshot time. A file the agent wrote carries no version and is not checked on replay. ## Cache The SharePoint VFS caches site, drive, and directory listings via `IndexCacheStore` to reduce repeated Graph calls during traversal. ## Example ```python theme={null} import asyncio import os from mirage import MountMode, Workspace from mirage.vfs.sharepoint import SharePointVFS, SharePointConfig config = SharePointConfig(access_token=os.environ["MS_GRAPH_DRIVE_TOKEN"]) vfs = SharePointVFS(config) async def main() -> None: ws = Workspace({"/sharepoint/": vfs}, mode=MountMode.WRITE) # list sites, then drives in the first site r = await ws.shell("ls /sharepoint/") print(await r.stdout_str()) r = await ws.shell("ls /sharepoint/Engineering/") print(await r.stdout_str()) await ws.shell( "echo 'hello from mirage' > /sharepoint/Engineering/Documents/note.txt") r = await ws.shell("cat /sharepoint/Engineering/Documents/note.txt") print(await r.stdout_str()) r = await ws.shell("tree /sharepoint/Engineering/Documents/") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` Runnable versions live at `examples/python/vfs/sharepoint/sharepoint.py` (command matrix) and `examples/python/vfs/sharepoint/sharepoint_vfs.py` (an in-process `ws.shell()` run that writes a Markdown report). ## Shell Commands The SharePoint VFS supports the full set of shell commands since it operates on real file content (text, binary, JSON, CSV, etc.). Large files benefit from range reads to avoid downloading entire items. ### Read Commands | Command | Notes | | - | - | | `cat` | Read file content | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search (file or directory level) | | `jq` | Query JSON fields | | `wc` | Line/word/byte counts | | `stat` | File metadata (name, size, type, modified) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `nl` | Number lines | | `du` | Disk usage summary | | `file` | Detect file type | | `strings` | Extract printable strings from binary | | `xxd` | Hex dump | | `md5` | MD5 checksum | | `sha256sum` | SHA-256 checksum | ### File Operations | Command | Notes | | - | - | | `cp` | Copy files | | `mv` | Move/rename files | | `rm` | Remove files | | `mkdir` | Create directories | | `touch` | Create empty file or update timestamp | | `tee` | Write stdin to file and stdout | ### Path Utilities | Command | Notes | | - | - | | `basename` | Strip directory from path | | `dirname` | Strip filename from path | | `realpath` | Resolve path | | `ls` | List directory contents | ## Use Cases * **AI agents accessing org documents**: Mount enterprise SharePoint for agents to read and process files across many sites * **Multi-site discovery**: Browse every accessible site and library from a single mount, no drive ids to manage * **Versioned document workflows**: Snapshot and replay exact file states over time * **FUSE mounting**: Expose SharePoint through a virtual FUSE mount for external tools ## Integration What SharePoint answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On SharePoint | | - | - | | `grep -r`, `rg` | Microsoft Graph search within one document library, for whole words. It can miss Office files, PDFs, archives, the end of large files, words Graph splits differently (`foo.bar`) and recent writes. | | `find`, `du`, `ls -R`, `tree` | One recursive listing | `grep -rw` and `rg -w` read only the files Microsoft Graph search names, within one document library (a directory above one is read in full); every file is read when the search fails or finds nothing. `walk_limit: -1` in the mount's `"@all"` [command limit](/home/core/output-limits) reads every file instead, since Graph searches the text it extracted, not the bytes `grep` reads, and indexes a write some time after it lands, so a file that holds the word can be left out: an office file, PDF or archive, the end of a large file, or a word Graph splits differently (`foo.bar`). ## SharePoint vs OneDrive Both backends talk to Microsoft Graph driveItems and behave identically below the drive level. Choose by topology: * Use **[OneDrive](/python/vfs/onedrive)** for a single drive (personal OneDrive, OneDrive for Business, or one targeted SharePoint library via `drive_id` / `site_id`). * Use **SharePoint** for enterprise scenarios with many sites and libraries that you want to discover and traverse without knowing drive ids up front. # Slack Source: https://docs.mirage.strukto.ai/python/vfs/slack Mount Slack channels, DMs, messages, users, and shared files as a Mirage virtual filesystem for Python agents. The Slack VFS exposes a Slack workspace as a virtual filesystem mounted at some prefix such as `/slack/`. For token setup, see [Slack Setup](/home/setup/slack). ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.slack import SlackConfig, SlackVFS config = SlackConfig( token=os.environ["SLACK_BOT_TOKEN"], search_token=os.environ.get("SLACK_USER_TOKEN"), ) vfs = SlackVFS(config=config) ws = Workspace({"/slack": vfs}, mode=MountMode.READ) ``` | Field | Description | | - | - | | `start_time` | Start of the mount's time scope, inclusive: an RFC 3339 timestamp with an explicit timezone and at most millisecond precision. Unset leaves the start open. | | `end_time` | End of the mount's time scope, exclusive, in the same format as `start_time`, which it must follow. Unset leaves the end open. | | `timeout` default `30` | 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. | | `token` required, secret | Slack token every API call sends: a bot token (`xoxb-`) or a user token (`xoxp-`). | | `search_token` secret | User token (`xoxp-`) with `search:read`, used only for Slack's `search.*` methods, which refuse a bot token. Unset searches with `token`. | | `base_url` default `'https://slack.com/api'` | Slack Web API root; override to point at a fake or proxy. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Slack mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `slack`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > channels/ > <channel-name>__<channel-id>/ > <yyyy-mm-dd>/ > chat.jsonl # messages for that date > files/ # attachments shared that day > <name>__<F-id>.<ext> # cat downloads the bytes > dms/ > <user-name>__<dm-id>/ > <yyyy-mm-dd>/ > chat.jsonl > files/ > <name>__<F-id>.<ext> > users/ > <username>__<user-id>.json # user profile > ``` > > * A channel, DM or user name is `<display-name>__<id>`. The display name > keeps Slack's spelling; only `/` becomes `∕` (U+2215). `ls` the parent > first to find exact names, and quote a name that has spaces. > * Messages are JSONL; use `jq` for fields such as `.text`, `.user`, > `.ts` and `.files`. A day's `files/` may be empty. > * `.user` is a user ID (`U…`), not a username; resolve it through > `users/<username>__<user-id>.json` and filter messages by the ID. > * Without `start_time`/`end_time`, a channel lists the latest 90 days up > to its newest message; a date glob finds earlier days. > * With `start_time`/`end_time`, listings cover that scope; messages and > attachments outside it are absent, direct paths included, and `grep` > and `rg` see only the in-scope files. Users and channel metadata stay > available as context. > * Unless `walk_limit` is -1, `grep -rw` and `rg -w` read only the channel > and DM days Slack search names; attachments under `files/` are always > read. > > Time scope: `start_time=unbounded` (inclusive), `end_time=unbounded` (exclusive). Explicit paths and globs cannot escape this scope. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` with `-w` ask `slack` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. Without `-w`, `grep -r` and `rg` read every file. `slack` answers only for `channels/*/*/chat.jsonl` and `dms/*/*/chat.jsonl`; `grep -r` and `rg` read every other 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>` | `slack`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > channels/ > <channel-name>__<channel-id>/ > <yyyy-mm-dd>/ > chat.jsonl # messages for that date > files/ # attachments shared that day > <name>__<F-id>.<ext> # cat downloads the bytes > dms/ > <user-name>__<dm-id>/ > <yyyy-mm-dd>/ > chat.jsonl > files/ > <name>__<F-id>.<ext> > users/ > <username>__<user-id>.json # user profile > ``` > > - A channel, DM or user name is `<display-name>__<id>`. The display name > keeps Slack's spelling; only `/` becomes `∕` (U+2215). `ls` the parent > first to find exact names, and quote a name that has spaces. > - Messages are JSONL; use `jq` for fields such as `.text`, `.user`, > `.ts` and `.files`. A day's `files/` may be empty. > - `.user` is a user ID (`U…`), not a username; resolve it through > `users/<username>__<user-id>.json` and filter messages by the ID. > - Without `start_time`/`end_time`, a channel lists the latest 90 days up > to its newest message; a date glob finds earlier days. > - With `start_time`/`end_time`, listings cover that scope; messages and > attachments outside it are absent, direct paths included, and `grep` > and `rg` see only the in-scope files. Users and channel metadata stay > available as context. > - Unless `walk_limit` is -1, `grep -rw` and `rg -w` read only the channel > and DM days Slack search names; attachments under `files/` are always > read. > > Time scope: `start_time=unbounded` (inclusive), `end_time=unbounded` (exclusive). Explicit paths and globs cannot escape this scope. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` with `-w` ask `slack` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. Without `-w`, `grep -r` and `rg` read every file. `slack` answers only for `channels/*/*/chat.jsonl` and `dms/*/*/chat.jsonl`; `grep -r` and `rg` read every other 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. > ```` Directory names embed the Slack ID so that write commands (`slack send-message --channel`, etc.) can reference the correct VFS without extra lookups. ### Channels `/slack/channels/` lists public and private channels the bot has access to. The channel ID is appended after `__`. Each channel directory contains day-partitioned directories for the last 90 days (or since channel creation, whichever is shorter). Each date directory contains `chat.jsonl` plus a `files/` directory for attachments shared that day. The date range is derived from the channel's `created` timestamp. ### DMs `/slack/dms/` lists direct message conversations. The DM ID is appended after `__`. Like channels, DM directories contain daily directories with `chat.jsonl` and `files/`. ### Users `/slack/users/` lists one `.json` file per non-deleted, non-bot user. Reading a user file calls `get_user_profile()` and returns the full profile JSON from the Slack API. ## Cache The Slack VFS uses `IndexCacheStore` (same as Discord and other mounts). Index entries store channel IDs, DM IDs, user IDs, and channel creation timestamps for date range computation. File bytes go through the workspace file cache. ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.vfs.slack import SlackConfig, SlackVFS load_dotenv(".env.development") config = SlackConfig( token=os.environ["SLACK_BOT_TOKEN"], search_token=os.environ.get("SLACK_USER_TOKEN"), ) vfs = SlackVFS(config=config) async def main(): ws = Workspace({"/slack": vfs}, mode=MountMode.READ) # List structure r = await ws.shell("ls /slack/") print(await r.stdout_str()) # List channels r = await ws.shell("ls /slack/channels/") print(await r.stdout_str()) ch = (await r.stdout_str()).strip().splitlines()[0] base = f"/slack/channels/{ch}" # Discover an available day, then read a few messages r = await ws.shell(f'ls "{base}/" | tail -n 1') day = (await r.stdout_str()).strip() r = await ws.shell(f'head -n 3 "{base}/{day}/chat.jsonl"') print(await r.stdout_str()) # Extract message text with jq r = await ws.shell( f'cat "{base}/{day}/chat.jsonl"' ' | jq -r ".text" | head -n 5') print(await r.stdout_str()) # Search across channel (scans all date files) r = await ws.shell(f'rg message "{base}/"') print(await r.stdout_str()) # Tree view r = await ws.shell("tree -L 1 /slack/") print(await r.stdout_str()) # Navigate with cd/pwd await ws.shell(f'cd "{base}"') r = await ws.shell("pwd") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` See `examples/python/vfs/slack/slack.py` for the full working example. ## Finding IDs VFS-specific commands require Slack IDs (`channel_id`, `user_id`, `ts`). These can be extracted from the filesystem: ```bash theme={null} # Channel ID - embedded in directory name after "__" ls /slack/channels/ # → general__C04KEPWF6V7 ← channel_id = C04KEPWF6V7 # User ID - embedded in filename after "__" ls /slack/users/ # → alice__U04K21SEVR9.json ← user_id = U04K21SEVR9 # Message timestamp (ts) - inside JSONL messages jq -r '"\(.ts) [\(.user)] \(.text)"' \ "/slack/channels/general__C04KEPWF6V7/2026-04-04/chat.jsonl" # → 1712345678.123456 [U04K21SEVR9] hello world # Find a specific message then reply jq -r 'select(.text | test("hello")) | .ts' \ "/slack/channels/general__C04KEPWF6V7/2026-04-04/chat.jsonl" # → 1712345678.123456 slack send-message --channel C04KEPWF6V7 \ --thread-ts 1712345678.123456 --text "Reply to hello" ``` ## Working with Large Channels Channels with many messages produce large `chat.jsonl` files per day. Tips for efficient access: ```bash theme={null} # Check message count per day wc -l "/slack/channels/general__C04KEPWF6V7/2026-04-04/chat.jsonl" # Read only recent messages tail -n 10 "/slack/channels/general__C04KEPWF6V7/2026-04-04/chat.jsonl" # Search across all dates (scans each file) rg "keyword" "/slack/channels/general__C04KEPWF6V7/" # Extract specific fields to reduce output jq -r '"\(.ts) [\(.user)] \(.text)"' \ "/slack/channels/general__C04KEPWF6V7/2026-04-04/chat.jsonl" | head -n 20 # Count messages per user cat "/slack/channels/general__C04KEPWF6V7/2026-04-04/chat.jsonl" \ | jq -r '.user' | sort | uniq -c ``` ## Shell Commands Standard commands available on the mounted Slack tree: | Command | Notes | | - | - | | `ls` | List channels, DMs, users, dates | | `cat` | Read `chat.jsonl`, user `.json`, or files | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search (file or directory level) | | `jq` | Query JSON, once per JSONL line (`-s` all) | | `wc` | Line/word/byte counts | | `stat` | File metadata (name, size, type) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | Acting on Slack (sending, reacting, pins, member info, search) goes through the [slack CLI](/python/cli/slack) when installed; the mounted tree stays read-oriented. The `<name>__<id>` path segments supply the channel and user IDs the CLI flags take. ## Integration What Slack answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Slack | | - | - | | `grep -r`, `rg` | Slack search, for whole words, with a user token. It can miss recent messages, words only in other fields (bot names and link previews). | | `tail -f` | Each new message as it is posted | With a user token, `grep -rw` and `rg -w` read only the channel and DM days Slack search names, and print what reading every day would. Search covers message text, file names and titles (`search.files`) and reactions (`has::name:`); listing a day already fetches its history, so this saves the second fetch of each day it rules out. A file hit names each day the file was shared. Users, file blobs and a day searched on its own are always read. Every day is read when the word is a key or fixed value of the message JSON, a file-type or URL word, a join or leave message word, or part of a user's name or of the workspace's domain, and when a search fails, returns more than 1,000 messages or finds nothing. With a separate `search_token`, every day is also read when the scope holds a private channel or a DM that token's user is not in (a bot's own DMs), since their search never sees it; that token needs `channels:read`, `groups:read`, `im:read` and `mpim:read` to list the conversations it sees. `walk_limit: -1` in the mount's `"@all"` [command limit](/home/core/output-limits) reads every file instead, since Slack indexes a message some time after it is posted, and a word held only in another field of a message (a bot's username, an unfurled link) is not searched. ## Time scope Set `start_time` and/or `end_time` in the mount's YAML `config` (or pass `start_time`/`end_time` to Python; `startTime`/`endTime` to the TypeScript constructor). Bounds are RFC3339 timestamps with an explicit timezone and at most millisecond precision. Start is inclusive; end is exclusive. An omitted or null bound is open. Start must precede end. ```yaml theme={null} mounts: /history: vfs: slack mode: read config: token: "<bot-token>" start_time: "2026-06-01T10:00:00Z" end_time: "2026-06-02T00:00:00Z" ``` With a bound configured, channel listings cover the selected period rather than the default recent window. Day directories use UTC. Messages are selected by creation time, and attachments follow their parent messages. Direct paths, `stat`, date globs, and `grep`/`rg` cannot escape the scope: a search only rules out files, so scoped searches scan the filtered files. User/member and channel/server metadata remain visible as context. These settings apply to the VFS, not to separately installed account CLIs. `mode: read` prevents mount writes; it does not freeze upstream edits or deletions. Rebuild/remount the VFS to change its scope so cached listings and bytes are cleared. # SQL Source: https://docs.mirage.strukto.ai/python/vfs/sql Keep a Mirage filesystem in SQL tables. The SQL VFS keeps a filesystem in a database's tables. It supports full read and write operations and needs no extra for a SQLite file: it uses Python's own `sqlite3`. ## Config ```python theme={null} from mirage import MountMode, Workspace from mirage.vfs.sql import SqlVFS vfs = SqlVFS("./workspace.db") ws = Workspace({"/sql": vfs}, mode=MountMode.WRITE) ``` | Parameter | Required | Default | Description | | - | - | - | - | | `path` | no | in memory | The SQLite file, opened and closed with the mount | | `capacity` | no | none | The most bytes the files may hold, like `100MB` | | `driver` | no | none | A `SqlDriver` to borrow instead of a file; you close it | The tables are laid out as [AgentFS](https://github.com/tursodatabase/agentfs)'s: * `fs_inode`: one row per file and directory, with its size and mtime * `fs_dentry`: each entry's name under its parent directory * `fs_data`: a file's bytes, in rows of the database's chunk size (4 KiB unless the database says otherwise) * `fs_config`: the chunk size One database holds one filesystem. The TypeScript mount reads and writes the same tables, so a Python and a Node process on one file serve one filesystem. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with SQL mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Cache Index TTL is `0`, so listings are read from the database every time. A workspace `index:` block still applies its `ttl` to this mount. ## Example ```python theme={null} import asyncio from mirage import MountMode, Workspace from mirage.vfs.sql import SqlVFS async def main(): ws = Workspace({"/sql": SqlVFS("./workspace.db")}, mode=MountMode.WRITE) try: await ws.shell("mkdir -p /sql/data/") await ws.shell('echo "hello world" | tee /sql/data/hello.txt') r = await ws.shell("cat /sql/data/hello.txt") print(await r.stdout_str()) finally: await ws.close() if __name__ == "__main__": asyncio.run(main()) ``` # SSH Source: https://docs.mirage.strukto.ai/python/vfs/ssh Mount a remote filesystem over SSH/SFTP. The SSH VFS mounts a remote server's filesystem over SFTP. It supports full read and write operations. Install the extra: ```bash theme={null} pip install "mirage-ai[ssh]" ``` ## Config ```python theme={null} from mirage import MountMode, Workspace from mirage.vfs.ssh import SSHConfig, SSHVFS config = SSHConfig( host="myserver", username="deploy", identity_file="~/.ssh/id_ed25519", root="/var/data", ) vfs = SSHVFS(config=config) ws = Workspace({"/remote": vfs}, mode=MountMode.WRITE) ``` | Field | Description | | - | - | | `host` required | Host name, IP address or `~/.ssh/config` alias of the remote. | | `hostname` | Address to connect to instead of `host`. | | `port` | SSH port; unset uses the client's default, `22` unless `~/.ssh/config` sets one for the host. | | `username` | Login user; unset uses the local user name unless `~/.ssh/config` sets one for the host. | | `identity_file` | Path to a private key; `~` is expanded. Unset tries the SSH agent and the default keys in `~/.ssh`. | | `private_key` secret | A private key's own text, such as one a credential pointer reads from a secret store; offered after `identity_file`'s. | | `password` secret | Password for password authentication; prefer `identity_file`. | | `passphrase` secret | Passphrase of an encrypted `identity_file` or `private_key`; ignored when both are unset. | | `root` default `'/'` | Path on the remote that becomes the mount root. | | `timeout` default `30` | Seconds to wait for the TCP connection, and again for authentication. | | `known_hosts` | Path to a `known_hosts` file the server's host key is checked against; unset disables host-key checking. | Fields marked secret are redacted in snapshots. The `host` field matches entries in `~/.ssh/config`, so existing SSH configurations are automatically picked up. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with SSH mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `ssh`, write | > > #### 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` ask `ssh` which files may match. `wc -l` asks `ssh` instead of reading a file. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | `ssh`, write | > > ## 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` ask `ssh` which files may match. `wc -l` asks `ssh` instead of reading a file. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ```text theme={null} /remote/ <remote-directory-tree> ``` The mounted tree mirrors the remote filesystem starting at `root`. Example with `root="/var/data"`: ```text theme={null} /remote/ logs/ app.log nginx/ access.log error.log config/ app.yaml uploads/ image.png ``` ## Cache Directory listings are cached for 60 seconds by default (a configured `index:` uses its own `ttl`, and the mount's `ttl:` caps it). File bytes are cached and served without a check until the mount's `ttl:`; SSH does not accept `read: fresh`. ## Example ```python theme={null} import asyncio from mirage import MountMode, Workspace from mirage.vfs.ssh import SSHConfig, SSHVFS config = SSHConfig( host="myserver", username="deploy", identity_file="~/.ssh/id_ed25519", root="/var/log", ) vfs = SSHVFS(config=config) async def main(): ws = Workspace({"/logs": vfs}, mode=MountMode.READ) # List remote directory r = await ws.shell("ls /logs/") print(await r.stdout_str()) # Read last 20 lines of a log r = await ws.shell("tail -n 20 /logs/nginx/access.log") print(await r.stdout_str()) # Search across log files r = await ws.shell('grep "ERROR" /logs/app.log') print(await r.stdout_str()) # Find large files r = await ws.shell("find /logs/ -name '*.log'") print(await r.stdout_str()) # File metadata r = await ws.shell("stat /logs/app.log") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Integration What SSH answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On SSH | | - | - | | `grep -r`, `rg` | `grep` on the server, for any text. It misses nothing. | | `wc -l` | `wc -l` on the server | | `tail -f` | `tail -f` on the server | | `md5sum`, `sha256sum` and the other hash commands | The matching sum tool on the server | | `find`, `du`, `ls -R`, `tree` | One `find` on the server | `grep -r` and `rg` run `grep` on the server to find which files hold the text, then read only those. The answer is exact. Every file is read when the server runs no commands (an SFTP-only account), its `grep` refuses an option (busybox), or it cannot read a file. ## Shell Commands | Command | Notes | | - | - | | `ls` | List remote files and directories | | `cat` | Read remote file content | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search; `-r` asks the server's grep which files to read | | `wc` | Line/word/byte counts | | `stat` | File metadata (size, mtime) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `mkdir` | Create remote directories | | `touch` | Create empty remote files | | `cp` / `mv` / `rm` | Copy, move, delete on remote | | `tee` | Write stdin to remote file | | `diff` / `cmp` | Compare remote files | | `sort` / `cut` / `tr` | Text processing | | `tar` / `zip` / `gzip` | Compression | # Supabase Storage Source: https://docs.mirage.strukto.ai/python/vfs/supabase Mount Supabase Storage as a virtual filesystem. The Supabase VFS mounts a Supabase Storage bucket at some prefix such as `/supabase/`. All operations involve network I/O to the remote object store. Uses aioboto3 against Supabase's S3-compatible API. For credential setup, see [Supabase Setup](/home/setup/supabase). Install the extra: ```bash theme={null} pip install "mirage-ai[s3]" ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.supabase import SupabaseConfig, SupabaseVFS config = SupabaseConfig( bucket=os.environ["SUPABASE_BUCKET"], region=os.environ["SUPABASE_REGION"], project_ref=os.environ["SUPABASE_PROJECT_REF"], access_key_id=os.environ["SUPABASE_ACCESS_KEY_ID"], secret_access_key=os.environ["SUPABASE_SECRET_ACCESS_KEY"], # Optional: # endpoint_url="https://{project_ref}.storage.supabase.co/storage/v1/s3", # session_token="...", # timeout=30, # proxy="http://proxy:8080", ) vfs = SupabaseVFS(config=config) ws = Workspace({"/supabase": vfs}, mode=MountMode.READ) ``` `SupabaseVFS(config)` takes a `SupabaseConfig` object with the bucket name, `region`, and either `project_ref` (endpoint is auto-built as `https://{project_ref}.storage.supabase.co/storage/v1/s3`) or an explicit `endpoint_url`. Both `READ` and `WRITE` modes are supported. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `bucket` required | Name of the bucket to mount. | | `region` required | Provider region every request is signed for. Most providers also build their endpoint URL from it unless `endpoint_url` is set. | | `endpoint_url` | Endpoint URL that replaces the one the provider derives. | | `access_key_id` secret | Access key ID; set it with `secret_access_key`. Unset uses the AWS credential chain. | | `secret_access_key` secret | Secret access key paired with `access_key_id`. | | `session_token` secret | Session token for temporary credentials, sent with the access key pair. | | `aws_profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `path_style` default `True` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `key_prefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | | `project_ref` | Supabase project reference. It builds the endpoint `https://<project_ref>.storage.supabase.co/storage/v1/s3` unless `endpoint_url` is set; one of the two is required. | Fields marked secret are redacted in snapshots. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Supabase Storage mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` The Supabase VFS maps object keys to virtual paths under the mount prefix. Supabase "directories" are prefix-based — there are no real directory objects. For example, if bucket `my-bucket` contains: ```text theme={null} avatars/user-001.png avatars/user-002.png documents/report.pdf documents/data.csv ``` Then mounting at `/supabase/` exposes: ```text theme={null} /supabase/ avatars/ user-001.png user-002.png documents/ report.pdf data.csv ``` Path mapping: virtual `/supabase/avatars/user-001.png` maps to Supabase key `avatars/user-001.png`. ## Cache The Supabase VFS uses `IndexCacheStore` with `index_ttl = 600` (10 minutes). Directory listings are cached for up to 600 seconds before being refreshed from Supabase. A configured `index:` replaces this lifetime with its own `ttl`, and the mount's `ttl:` caps it. ## Integration What Supabase Storage answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Supabase Storage | | - | - | | `find`, `du`, `ls -R`, `tree` | One recursive listing | ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.vfs.supabase import SupabaseConfig, SupabaseVFS load_dotenv(".env.development") config = SupabaseConfig( bucket=os.environ["SUPABASE_BUCKET"], region=os.environ["SUPABASE_REGION"], project_ref=os.environ["SUPABASE_PROJECT_REF"], access_key_id=os.environ["SUPABASE_ACCESS_KEY_ID"], secret_access_key=os.environ["SUPABASE_SECRET_ACCESS_KEY"], ) vfs = SupabaseVFS(config=config) async def main() -> None: ws = Workspace({"/supabase/": vfs}, mode=MountMode.READ) r = await ws.shell("ls /supabase/") print(await r.stdout_str()) r = await ws.shell("cat /supabase/documents/data.csv | head -n 10") print(await r.stdout_str()) r = await ws.shell("tree -L 2 /supabase/") print(await r.stdout_str()) r = await ws.shell("find /supabase/ -name '*.pdf'") print(await r.stdout_str()) r = await ws.shell("stat /supabase/avatars/user-001.png") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Shell Commands The Supabase VFS supports the full set of shell commands since it operates on real file content (text, binary, JSON, CSV, etc.). Large files benefit from range reads to avoid downloading entire objects. ### Read Commands | Command | Notes | | - | - | | `cat` | Read file content | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search (file or directory level) | | `jq` | Query JSON fields | | `wc` | Line/word/byte counts | | `stat` | File metadata (name, size, type, modified) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `nl` | Number lines | | `du` | Disk usage summary | | `file` | Detect file type | | `strings` | Extract printable strings from binary | | `xxd` | Hex dump | | `md5` | MD5 checksum | | `sha256sum` | SHA-256 checksum | ### Text Processing | Command | Notes | | - | - | | `awk` | Pattern scanning and processing | | `sed` | Stream editor | | `tr` | Translate or delete characters | | `sort` | Sort lines | | `uniq` | Remove duplicate lines | | `cut` | Extract fields/columns | | `join` | Join lines on a common field | | `paste` | Merge lines side by side | | `column` | Columnate output | | `fold` | Wrap lines to a specified width | | `expand` | Convert tabs to spaces | | `unexpand` | Convert spaces to tabs | | `fmt` | Simple text formatter | | `rev` | Reverse lines | | `tac` | Concatenate and print in reverse | | `look` | Display lines beginning with a given string | | `shuf` | Shuffle lines | | `tsort` | Topological sort | | `comm` | Compare two sorted files | | `cmp` | Compare two files byte by byte | | `diff` | Compare files line by line | | `patch` | Apply a diff patch | | `iconv` | Character encoding conversion | ### File Operations | Command | Notes | | - | - | | `cp` | Copy files | | `mv` | Move/rename files | | `rm` | Remove files | | `mkdir` | Create directories | | `touch` | Create empty file or update timestamp | | `ln` | Create symbolic links | | `tee` | Write stdin to file and stdout | | `mktemp` | Create temporary file | | `split` | Split file into pieces | | `csplit` | Split file by context | ### Path Utilities | Command | Notes | | - | - | | `basename` | Strip directory from path | | `dirname` | Strip filename from path | | `realpath` | Resolve path | | `readlink` | Print symbolic link target | | `ls` | List directory contents | ### Compression | Command | Notes | | - | - | | `gzip` | Compress files | | `gunzip` | Decompress gzip files | | `zip` | Create zip archives | | `unzip` | Extract zip archives | | `tar` | Archive files | | `zcat` | Cat compressed files | | `zgrep` | Grep compressed files | ### Encoding | Command | Notes | | - | - | | `base64` | Base64 encode/decode | ## Use Cases * **AI agents accessing Supabase data**: Mount Supabase buckets for agents to read and process datasets * **Data pipelines**: Read and write Supabase objects with shell-like commands * **FUSE mounting**: Expose Supabase buckets through a virtual FUSE mount for external tools # Tencent COS Source: https://docs.mirage.strukto.ai/python/vfs/tencent Mount a Tencent Cloud Object Storage bucket via its S3-compatible API. The Tencent VFS is a thin wrapper over the [S3 VFS](/python/vfs/s3). It maps a `TencentConfig` to an `S3Config` and reuses the exact same backend, commands, and behavior as S3, it just derives the right COS endpoint from `region`. Uses aioboto3 against Tencent COS's S3-compatible API. The endpoint is computed from `region` as `cos.<region>.myqcloud.com` (e.g. `cos.ap-guangzhou.myqcloud.com`). Pass `endpoint_url` to override. > [!NOTE] > > Tencent COS bucket names include the APPID suffix, e.g. > `my-bucket-1250000000`. Use the full name (with the suffix) for `bucket`. Install the extra: ```bash theme={null} pip install "mirage-ai[s3]" ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.tencent import TencentConfig, TencentVFS config = TencentConfig( bucket=os.environ["COS_BUCKET"], # e.g. my-bucket-1250000000 region=os.environ.get("COS_REGION", "ap-guangzhou"), access_key_id=os.environ["COS_SECRET_ID"], secret_access_key=os.environ["COS_SECRET_KEY"], # Optional: # endpoint_url="https://cos.ap-guangzhou.myqcloud.com", # timeout=30, # proxy="http://proxy:8080", ) vfs = TencentVFS(config) ws = Workspace({"/data": vfs}, mode=MountMode.READ) ``` Both `READ` and `WRITE` modes are supported. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `bucket` required | Name of the bucket to mount. | | `region` required | Provider region every request is signed for. Most providers also build their endpoint URL from it unless `endpoint_url` is set. | | `endpoint_url` | Endpoint URL that replaces the one the provider derives. | | `access_key_id` secret | Access key ID; set it with `secret_access_key`. Unset uses the AWS credential chain. | | `secret_access_key` secret | Secret access key paired with `access_key_id`. | | `session_token` secret | Session token for temporary credentials, sent with the access key pair. | | `aws_profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `path_style` default `False` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `key_prefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | Fields marked secret are redacted in snapshots. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Tencent COS mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.vfs.tencent import TencentConfig, TencentVFS load_dotenv(".env.development") config = TencentConfig( bucket=os.environ["COS_BUCKET"], region=os.environ.get("COS_REGION", "ap-guangzhou"), access_key_id=os.environ["COS_SECRET_ID"], secret_access_key=os.environ["COS_SECRET_KEY"], ) vfs = TencentVFS(config) async def main() -> None: ws = Workspace({"/data/": vfs}, mode=MountMode.READ) r = await ws.shell("ls /data/") print(await r.stdout_str()) r = await ws.shell("find /data/ -name '*.json' | head -n 5") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Notes * Tencent COS registers under its own `VFSName` and routes through the same `core/s3` implementation, so the full S3 shell-command set applies. See the [S3 VFS](/python/vfs/s3) for the complete command reference, range reads, streaming, and the index cache fast path. * For credential setup, see [Tencent COS Setup](/home/setup/tencent). # TiDB Cloud Filesystem Source: https://docs.mirage.strukto.ai/python/vfs/tidb_filesystem Mount a TiDB Cloud Filesystem, or a self-hosted drive9 server, as a filesystem. `TiDBFilesystemVFS` mounts a [TiDB Cloud Filesystem](https://www.pingcap.com/tidb/tidb-cloud-filesystem/) through its REST API. Agents list, read, write, move and remove files under the mount with ordinary shell commands, and no FUSE mount is needed. For tokens and regions, see [TiDB Cloud Filesystem Setup](/home/setup/tidb). ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.tidb_filesystem import ( TiDBFilesystemConfig, TiDBFilesystemVFS, ) vfs = TiDBFilesystemVFS(TiDBFilesystemConfig( host=os.environ["TIDB_FILESYSTEM_HOST"], token=os.environ["TIDB_FILESYSTEM_TOKEN"], root_path="/workspace", )) ws = Workspace({"/fs": vfs}, mode=MountMode.WRITE) ``` | Field | Description | | - | - | | `timeout` default `30` | 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. | | `host` required | The file system's endpoint, such as `https://aws-us-east-1.drive9.ai` for its region, or the origin of a self-hosted drive9 server. | | `token` required, secret | The file system token, sent as a bearer token. | | `root_path` default `'/'` | Directory inside the file system that becomes the mount root, such as `/projects/a` for a token scoped to it; `..` segments are refused. | Fields marked secret are redacted in snapshots. ## Mount mode `read`, `write` or `exec`. Use `exec` if `python3` or `js` should run scripts from the mount. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with TiDB Cloud Filesystem mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Behavior * A file under 50,000 bytes is written with one request; a larger one goes up in parts, a few at a time, and reads of it stream from object storage, ranged when a command reads only part of it. * `>>` onto a file of 50,000 bytes or more sends only the new bytes and the file's last part; a smaller file is read and written back. * `mv` is one server-side rename, for a file or a whole directory. `rm -r` is one recursive delete. * `cp` reads the file and writes the copy, so the two never share content. * Before a write, `mkdir` or `mv`, Mirage asks the file system what the destination and its parents are, so a missing parent, a file in the way or a directory target fails as it does on a local disk. * A file in the extent layout, which only the file system's FUSE client writes and reads, reads as `Operation not supported`. ## Example ```python theme={null} import asyncio import os from mirage import MountMode, Workspace from mirage.vfs.tidb_filesystem import ( TiDBFilesystemConfig, TiDBFilesystemVFS, ) vfs = TiDBFilesystemVFS(TiDBFilesystemConfig( host=os.environ["TIDB_FILESYSTEM_HOST"], token=os.environ["TIDB_FILESYSTEM_TOKEN"], )) async def main() -> None: ws = Workspace({"/fs": vfs}, mode=MountMode.WRITE) await ws.shell("mkdir -p /fs/notes && echo hello > /fs/notes/a.txt") r = await ws.shell("ls -l /fs/notes && cat /fs/notes/a.txt") print(await r.stdout_str()) await ws.close() if __name__ == "__main__": asyncio.run(main()) ``` See `examples/python/vfs/tidb_filesystem/tidb_filesystem.py`. # Trello Source: https://docs.mirage.strukto.ai/python/vfs/trello Mount Trello workspaces, boards, lists, cards, members, and labels as a Mirage filesystem for Python agents. The Trello VFS exposes workspaces, boards, lists, cards, members, and labels as a virtual filesystem mounted at some prefix such as `/trello/`. For API key setup, see [Trello Setup](/home/setup/trello). ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.trello import TrelloConfig, TrelloVFS config = TrelloConfig( api_key=os.environ["TRELLO_API_KEY"], api_token=os.environ["TRELLO_API_TOKEN"], ) vfs = TrelloVFS(config=config) ws = Workspace({"/trello": vfs}, mode=MountMode.READ) ``` | Field | Description | | - | - | | `timeout` default `30` | 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. | | `api_key` required, secret | Trello API key. | | `api_token` required, secret | Trello API token. | | `workspace_id` | Only this workspace and its boards are listed or readable. Unset shows every workspace of the token's member. | | `board_ids` | Only these boards are listed or readable. Unset shows every open board of the shown workspaces. | | `base_url` default `'https://api.trello.com/1'` | Trello API root; override to point at a fake or proxy. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Trello mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `trello`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > workspaces/ > <workspace-name>__<workspace-id>/ > workspace.json > boards/ > <board-name>__<board-id>/ > board.json > members/ > <full-name>__<member-id>.json > labels/ > <label-name>__<label-id>.json > lists/ > <list-name>__<list-id>/ > list.json > cards/ > <card-name>__<card-id>/ > card.json > comments.jsonl > ``` > > * `ls` directories first to discover exact names. > * To act on boards and cards (list boards, members, lists, labels, cards > and comments; create, update, move, assign, label and comment on > cards), use the `trello` CLI if installed (`trello --help`). > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` with `-w` ask `trello` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. Without `-w`, `grep -r` and `rg` read every file. `trello` answers only for `workspaces/*/boards/*/lists/*/cards/*/card.json`; `grep -r` and `rg` read every other 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>` | `trello`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > workspaces/ > <workspace-name>__<workspace-id>/ > workspace.json > boards/ > <board-name>__<board-id>/ > board.json > members/ > <full-name>__<member-id>.json > labels/ > <label-name>__<label-id>.json > lists/ > <list-name>__<list-id>/ > list.json > cards/ > <card-name>__<card-id>/ > card.json > comments.jsonl > ``` > > - `ls` directories first to discover exact names. > - To act on boards and cards (list boards, members, lists, labels, cards > and comments; create, update, move, assign, label and comment on > cards), use the `trello` CLI if installed (`trello --help`). > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` with `-w` ask `trello` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. Without `-w`, `grep -r` and `rg` read every file. `trello` answers only for `workspaces/*/boards/*/lists/*/cards/*/card.json`; `grep -r` and `rg` read every other 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. > ```` Directory and file names embed the Trello ID after `__` so that [trello CLI](/python/cli/trello) commands can take an ID without extra lookups. ### Workspaces Each workspace directory is named: ```text theme={null} <workspace-name>__<workspace-id> ``` Inside the workspace directory: * `workspace.json` is the normalized workspace metadata * `boards/` contains one directory per board ### Boards Each board directory is named: ```text theme={null} <board-name>__<board-id> ``` Inside the board directory: * `board.json` is the normalized board metadata * `members/` contains one JSON file per board member * `labels/` contains one JSON file per board label * `lists/` contains one directory per list ### Lists Each list directory is named: ```text theme={null} <list-name>__<list-id> ``` Each list directory contains: * `list.json` -- normalized list metadata with fields such as `list_id`, `list_name`, `board_id`, `closed`, `pos` * `cards/` contains one directory per card ### Cards Each card directory is named: ```text theme={null} <card-name>__<card-id> ``` Each card directory contains: * `card.json` -- normalized card metadata with command-aligned fields such as `card_id`, `board_id`, `list_id`, `member_ids`, `label_ids`, `due`, `url` * `comments.jsonl` -- normalized comment stream ordered by `created_at` `comments.jsonl` is a Mirage representation chosen for shell-friendly workflows. It is not a native Trello file format. ### Members Each member file is named: ```text theme={null} <full-name>__<member-id>.json ``` Member JSON includes command-aligned identifiers such as `member_id` and `username` so the value can be reused directly in commands like `trello card assign`. ### Labels Each label file is named: ```text theme={null} <label-name>__<label-id>.json ``` Label JSON includes `label_id`, `label_name`, `color`, and `board_id`. ## Integration What Trello answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Trello | | - | - | | `grep -r`, `rg` | Trello search and the text the listing keeps, for whole words. It can miss recent writes. | `grep -rw` and `rg -w` ask Trello search for each word and read only the cards that hold every word, where the search names it or the listing keeps it. The listing keeps the card's other fields (ids, due date, flags, link) and each name or description word the search can miss, such as one inside a link; the cards are listed once more for this, so a change since the last listing is still found. Comments and the board's other files are always read. Every card is read when the word is a key of the card JSON (`desc`, `due`) or a JSON literal, has a digit or only the letters a to f, which an id can hold, and when a search fails, returns 1,000 cards or finds nothing. `walk_limit: -1` in the mount's `"@all"` [command limit](/home/core/output-limits) reads every file instead, since Trello indexes a write some time after it lands. ## Cache Uses `IndexCacheStore` (same as other mounts). ## Example See [`examples/python/vfs/trello/trello.py`](https://github.com/strukto-ai/mirage/blob/main/examples/python/vfs/trello/trello.py) for the full working example. ```bash theme={null} # List workspaces ls /trello/workspaces/ # Read workspace metadata cat /trello/workspaces/engineering__abc123/workspace.json # List boards ls /trello/workspaces/engineering__abc123/boards/ # Read board metadata cat /trello/workspaces/engineering__abc123/boards/roadmap__brd_001/board.json # List lists ls /trello/workspaces/engineering__abc123/boards/roadmap__brd_001/lists/ # Read a card cat /trello/workspaces/engineering__abc123/boards/roadmap__brd_001/lists/backlog__lst_001/cards/fix-login__crd_001/card.json # Read card comments cat /trello/workspaces/engineering__abc123/boards/roadmap__brd_001/lists/backlog__lst_001/cards/fix-login__crd_001/comments.jsonl # Extract card ID with jq cat /trello/workspaces/engineering__abc123/boards/roadmap__brd_001/lists/backlog__lst_001/cards/fix-login__crd_001/card.json \ | jq '.card_id' # Read last 5 comments tail -n 5 /trello/workspaces/engineering__abc123/boards/roadmap__brd_001/lists/backlog__lst_001/cards/fix-login__crd_001/comments.jsonl # List members ls /trello/workspaces/engineering__abc123/boards/roadmap__brd_001/members/ # List labels ls /trello/workspaces/engineering__abc123/boards/roadmap__brd_001/labels/ # Tree view tree -L 2 /trello/workspaces/ ``` ## Finding IDs IDs are embedded in directory and file names after `__`: ```bash theme={null} # Workspace ID -- embedded in directory name ls /trello/workspaces/ # -> engineering__abc123 <- workspace_id = abc123 # Board ID -- embedded in board directory name ls /trello/workspaces/engineering__abc123/boards/ # -> roadmap__brd_001 <- board_id = brd_001 # List ID -- embedded in list directory name ls /trello/workspaces/engineering__abc123/boards/roadmap__brd_001/lists/ # -> backlog__lst_001 <- list_id = lst_001 # Card ID -- embedded in card directory name ls /trello/workspaces/engineering__abc123/boards/roadmap__brd_001/lists/backlog__lst_001/cards/ # -> fix-login__crd_001 <- card_id = crd_001 # Member ID -- embedded in member file name ls /trello/workspaces/engineering__abc123/boards/roadmap__brd_001/members/ # -> alice__mem_001.json <- member_id = mem_001 # Label ID -- embedded in label file name ls /trello/workspaces/engineering__abc123/boards/roadmap__brd_001/labels/ # -> bug__lbl_001.json <- label_id = lbl_001 # Use stat for structured metadata stat /trello/workspaces/engineering__abc123/boards/roadmap__brd_001/lists/backlog__lst_001/cards/fix-login__crd_001/card.json # Extract fields with jq cat /trello/workspaces/engineering__abc123/boards/roadmap__brd_001/lists/backlog__lst_001/cards/fix-login__crd_001/card.json \ | jq '{card_id, board_id, list_id, member_ids, label_ids}' ``` ## Shell Commands Standard commands available on the mounted Trello tree: | Command | Notes | | - | - | | `ls` | List workspaces, boards, lists, cards | | `cat` | Read .json metadata or .jsonl comments | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search (file or directory level) | | `jq` | Query JSON fields | | `wc` | Line/word/byte counts | | `stat` | File metadata (name, size, type) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `basename` | Extract file name from path | | `dirname` | Extract directory from path | | `realpath` | Resolve path to absolute form | ## Acting on Trello Reads and writes on Trello entities by ID (boards, members, lists, labels, cards, comments) go through the [trello CLI](/python/cli/trello) when installed; the mounted tree serves the same entities as normalized JSON files. The CLI takes `workspace_id` and `board_ids` in its own config, so it covers the boards the mount lists only when both are configured alike. # Weights & Biases Source: https://docs.mirage.strukto.ai/python/vfs/wandb Read experiment runs, configuration, summaries, history, and run files. The Weights & Biases (W\&B) VFS provides read-only access to experiments, run configurations, summaries, metric history, and logged artifacts. For API key setup and entity discovery, see [Weights & Biases Setup](/home/setup/wandb). For the TypeScript SDK, see [Weights & Biases (TypeScript)](/typescript/setup/wandb). ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.wandb import WandbConfig, WandbVFS config = WandbConfig( entities=["my-team"], api_key=os.environ["WANDB_API_KEY"], ) vfs = WandbVFS(config) ws = Workspace({"/wandb": vfs}, mode=MountMode.READ) ``` The mount exposes `/<entity>/<project>/<run-id>/` with `run.json`, `config.json`, `summary.json`, `history.jsonl`, and `files/`. Configure one or more entities explicitly; project and run listings are fetched on demand and follow service pagination. Run IDs identify directories; duplicate display names remain separate runs. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `entities` required | W\&B entities (users or teams) the mount shows as top-level directories; no other entity is reachable. | | `api_key` default `SecretStr('')`, secret | W\&B API key, sent as HTTP Basic auth. Empty sends no credentials. | | `base_url` default `'https://api.wandb.ai'` | W\&B API root. Queries go to its `/graphql`, and only downloads from the same origin carry the key. | | `page_size` default `100` | Items per GraphQL page, and steps per window when reading `history.jsonl`. | | `max_pages` default `10000` | The most pages one listing or history read fetches. Past it the read fails rather than return a partial result. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Weights & Biases mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `wandb`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > <entity>/ > <project>/ > <run-id>/ > run.json > config.json > summary.json > history.jsonl > files/ > ``` > > * Read only. Only configured entities are visible. Run IDs are stable; > display names may repeat. > * `run.json` holds identity, creator, sweep/group/job, tags, timestamps, > notes, system metrics, history keys and count, and file count. Its > `user` contains the creator's id, name, username and email, when > available; its `read_only` is W\&B's permission, not the mount mode. > Missing run metadata is `null`. > * `history.jsonl` scans unsampled history in original order, preserving > missing metrics and `_step`. Logged training-step keys are independent > of `_step`. History reads may be large; use `head` to stream a prefix. > * `summary.json` metrics are stored values, not history maxima. > * `files/` keeps run-relative paths; `files/wandb-metadata.json`, when > present, describes the machine and runtime environment. > * Listings and reads are lazy. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `wandb`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > <entity>/ > <project>/ > <run-id>/ > run.json > config.json > summary.json > history.jsonl > files/ > ``` > > - Read only. Only configured entities are visible. Run IDs are stable; > display names may repeat. > - `run.json` holds identity, creator, sweep/group/job, tags, timestamps, > notes, system metrics, history keys and count, and file count. Its > `user` contains the creator's id, name, username and email, when > available; its `read_only` is W&B's permission, not the mount mode. > Missing run metadata is `null`. > - `history.jsonl` scans unsampled history in original order, preserving > missing metrics and `_step`. Logged training-step keys are independent > of `_step`. History reads may be large; use `head` to stream a prefix. > - `summary.json` metrics are stored values, not history maxima. > - `files/` keeps run-relative paths; `files/wandb-metadata.json`, when > present, describes the machine and runtime environment. > - Listings and reads are lazy. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ```` ## Run data reference `run.json` contains the run metadata exposed by the supported W\&B API fields: | Fields | Contents | | - | - | | `entity`, `project`, `run`, `path` | Run identity and its `entity/project/run-id` path | | `storage_id`, `display_name`, `state` | W\&B's opaque storage ID, display name, and reported state | | `tags`, `sweep_name`, `group`, `job_type` | Experiment organization | | `commit`, `created_at`, `heartbeat_at` | Source revision, creation time, and last heartbeat | | `description`, `notes`, `user` | Run description, notes, and creator's `id`/`name`/`username`/`email` | | `read_only` | W\&B's reported edit permission; the Mirage mount remains read-only | | `system_metrics` | Latest system metrics decoded as JSON, retaining nested values | | `history_line_count`, `history_keys`, `file_count` | History row count, metric-key metadata including the last step, and file count | Unavailable metadata is `null`; empty tags, zero counts, false permissions, and original timestamp strings are preserved. These fields are fetched only when reading `run.json`, in one run query. Listing and stat do not fetch them. The `user` is the run's creator, not the identity associated with the API key. `config.json` unwraps W\&B's configuration `value` envelopes. `summary.json` contains the stored summary, which may differ from the best value in history. These documents have run-defined keys rather than a fixed Mirage field list. Nested objects, arrays, metric names containing `/` or `.`, and null values remain intact. `history.jsonl` scans full history in `_step` windows using the public SDK's unsampled scan protocol. It retains row order, missing keys, nulls, and logged training-step fields. `_step` and a training-step metric are separate values. The last step is captured when a read begins; rows appended later are visible on a subsequent read. Run files retain their relative paths and are downloaded as raw bytes. Listing and stat do not download histories or files. Rendered JSON and history have unknown sizes; raw file sizes come from W\&B's file metadata. Directory metadata uses Mirage's index cache (600 seconds by default). A project listing also establishes its runs' existence; a file catalog populates all nested directories, so traversing them reuses the same metadata. Config, summary, and history reads request their own fields. Downloads resolve the exact filename for a fresh URL on each read. File content and download URLs are not cached in the index. Reads and downloads stream, so `head` can stop before fetching the entire history. `page_size` defaults to 100 (maximum 1000); `max_pages` defaults to 10000. Exhausting a page budget raises an error instead of returning a complete-looking partial result. ## Example ```python theme={null} import asyncio import os from mirage import MountMode, Workspace from mirage.vfs.wandb import WandbConfig, WandbVFS async def main() -> None: config = WandbConfig( entities=["my-team"], api_key=os.environ["WANDB_API_KEY"], ) vfs = WandbVFS(config) ws = Workspace({"/wandb": vfs}, mode=MountMode.READ) # Discover runs res = await ws.shell("find /wandb/my-team -maxdepth 3 -name run.json") print(await res.stdout_str()) # Inspect a run configuration res = await ws.shell("cat /wandb/my-team/my-project/run-01/config.json") print(await res.stdout_str()) # Stream the first 10 steps of history res = await ws.shell("head -n 10 /wandb/my-team/my-project/run-01/history.jsonl") print(await res.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` # Wasabi Source: https://docs.mirage.strukto.ai/python/vfs/wasabi Mount a Wasabi cloud storage bucket as a virtual filesystem. The Wasabi VFS is a thin wrapper over the [S3 VFS](/python/vfs/s3). It maps a `WasabiConfig` to an `S3Config` and reuses the exact same backend, commands, and behavior as S3, it just derives the right Wasabi endpoint from `region`. Uses aioboto3 against Wasabi's S3-compatible API. The endpoint is computed from `region` as `s3.<region>.wasabisys.com` (`s3.wasabisys.com` for `us-east-1`). Pass `endpoint_url` to override. Install the extra: ```bash theme={null} pip install "mirage-ai[s3]" ``` ## Config ```python theme={null} import os from mirage import MountMode, Workspace from mirage.vfs.wasabi import WasabiConfig, WasabiVFS config = WasabiConfig( bucket=os.environ["WASABI_BUCKET"], region=os.environ.get("WASABI_REGION", "us-east-2"), access_key_id=os.environ["WASABI_ACCESS_KEY_ID"], secret_access_key=os.environ["WASABI_SECRET_ACCESS_KEY"], # Optional: # endpoint_url="https://s3.us-east-2.wasabisys.com", # timeout=30, # proxy="http://proxy:8080", ) vfs = WasabiVFS(config) ws = Workspace({"/data": vfs}, mode=MountMode.READ) ``` `region` defaults to `us-east-1`. Both `READ` and `WRITE` modes are supported. | Field | Description | | - | - | | `timeout` default `30` | 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. | | `bucket` required | Name of the bucket to mount. | | `region` default `'us-east-1'` | Wasabi region. It builds the endpoint `https://s3.<region>.wasabisys.com` (`https://s3.wasabisys.com` for `us-east-1`) unless `endpoint_url` is set, and signs every request. | | `endpoint_url` | Endpoint URL that replaces the one the provider derives. | | `access_key_id` secret | Access key ID; set it with `secret_access_key`. Unset uses the AWS credential chain. | | `secret_access_key` secret | Secret access key paired with `access_key_id`. | | `session_token` secret | Session token for temporary credentials, sent with the access key pair. | | `aws_profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `path_style` default `False` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `key_prefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | Fields marked secret are redacted in snapshots. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Wasabi mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Example ```python theme={null} import asyncio import os from dotenv import load_dotenv from mirage import MountMode, Workspace from mirage.vfs.wasabi import WasabiConfig, WasabiVFS load_dotenv(".env.development") config = WasabiConfig( bucket=os.environ["WASABI_BUCKET"], region=os.environ.get("WASABI_REGION", "us-east-2"), access_key_id=os.environ["WASABI_ACCESS_KEY_ID"], secret_access_key=os.environ["WASABI_SECRET_ACCESS_KEY"], ) vfs = WasabiVFS(config) async def main() -> None: ws = Workspace({"/data/": vfs}, mode=MountMode.READ) r = await ws.shell("ls /data/") print(await r.stdout_str()) r = await ws.shell("tree /data/") print(await r.stdout_str()) if __name__ == "__main__": asyncio.run(main()) ``` ## Notes * Wasabi registers under its own `VFSName` and routes through the same `core/s3` implementation, so the full S3 shell-command set applies. See the [S3 VFS](/python/vfs/s3) for the complete command reference, range reads, streaming, and the index cache fast path. * For credential setup, see [Wasabi Setup](/home/setup/wasabi). # In-app Source: https://docs.mirage.strukto.ai/typescript/access/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](/home/core/output-limits), keyed by command name. | | `new Mount(vfs, options)` | With any of `mode`, `backend`, `mountpoint`, `commandLimits`, `index`, `read` and `write`, as the [mount settings](/home/configuration#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](/home/policy/overview) a session can be created under. **options.profile** `string` The profile a session gets when it names none. **options.policies** `Policy[]` [Policies](/home/policy/overview) 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](/home/configuration#cache-index-and-store): symlinks and file attributes, command history, 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](/home/configuration) 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 processes runtimes 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](/home/policy/policies#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](/home/policy/overview), 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](/home/policy/policies#asks) ledger, which records pending approval requests for this session. ### session.shell ```ts theme={null} session.shell( command, { stdin?, cwd?, env?, signal?, record?, runtime?, 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. **runtime** `string` Run the line on this workspace [runtime](/home/setup/runtime/overview) entry, by name, instead of the one routing picks. 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](/home/policy/explain). ```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](/home/policy/explain#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](/typescript/agents/index) 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) ``` # Server Source: https://docs.mirage.strukto.ai/typescript/access/server The Mirage server in TypeScript, a Fastify app that holds workspaces and serves HTTP, MCP, RPC and SSH. The Mirage server is a Fastify app from `@struktoai/mirage-server`. It holds workspaces and serves them over the [HTTP](/home/access/http) routes, [MCP](/home/access/mcp) and [RPC](/home/access/rpc), and over [SSH](/home/access/ssh), on its own port when `ssh_port` is set and through its HTTP port either way. The Python server speaks the same protocol, so a client of one works against the other. ## Install ```bash npm theme={null} npm install @struktoai/mirage-server ``` ```bash with SSH theme={null} npm install @struktoai/mirage-server ssh2 ``` The SSH server runs on [ssh2](https://github.com/mscdex/ssh2), installed beside the server, needed only for SSH. ## Run it `buildApp` returns the Fastify instance; it serves until you stop it. ```ts theme={null} import { buildApp } from '@struktoai/mirage-server' const app = buildApp() await app.listen({ host: '127.0.0.1', port: 8765 }) ``` | Option | Default | Meaning | | - | - | - | | `authConfig` | from `MIRAGE_AUTH_MODE` | Token or JWT [configuration](/home/access/http#configure-authentication). | | `allowedHosts` | `MIRAGE_ALLOWED_HOSTS`, else loopback | `Host` headers accepted by the server. `['*']` turns the check off, safe only behind a trusted proxy. Browser requests from another origin are refused either way. | | `maxWorkspaces` | `MIRAGE_MAX_WORKSPACES`, else the `max_workspaces` key, else no cap | The most workspaces the app holds at once. A create, clone or load past it answers 503, and the ones it holds keep running. | | `policies` | none | The server's own [policies](/home/access/http#server-policies): each answers `preWorkspace` before a workspace is built, and is registered on every workspace the app builds. | | `policyFile` | `MIRAGE_POLICY_FILE`, else the `policy_file` key, else none | A file of policy programs that answer the same way. | | `maxSessions` | `MIRAGE_MAX_SESSIONS`, else the `max_sessions` key, else `16` | The most sessions each workspace holds, its default session among them. A new session past it, over HTTP or SSH, answers 429. | | `maxMemory` | `MIRAGE_MAX_MEMORY`, else the `max_memory` key, else none | The most any workspace's `max_memory` reaches, as a [size](/home/configuration#sizes). A workspace that sets more, or lifts its cap, gets this. | | `maxProcesses` | `MIRAGE_MAX_PROCESSES`, else the `max_processes` key, else none | The most any session's `processes.max` reaches, whatever a config or profile sets. | | `maxLineSeconds` | `MIRAGE_MAX_LINE_SECONDS`, else the `max_line_seconds` key, else none | The most seconds any line runs, whatever `@line` a config or profile sets. A line past it exits 124. | | `maxEnv` | `MIRAGE_MAX_ENV`, else the `max_env` key, else none | The most any workspace's `max_env` reaches, as a [size](/home/configuration#sizes). | | `rateLimits` | `MIRAGE_RATE_LIMITS`, else the `rate_limits` key, else `ip=1000/minute` | A list of `{ key, rate }`; an empty list disables limits. See [Rate limits](/home/access/http#rate-limits). | | `forwardedAllowIps` | `MIRAGE_FORWARDED_ALLOW_IPS`, else the `forwarded_allow_ips` key, else none | The proxies, addresses or networks, whose `X-Forwarded-For` names the client. `['*']` believes any. | | `gracefulTimeout` | `MIRAGE_GRACEFUL_TIMEOUT`, else the `graceful_timeout` key, else `0` | Seconds running lines get to finish on `app.close()` before they are cancelled. New work is refused meanwhile. | | `sshConfig` | from the `ssh_*` settings | The SSH server, opened when the app is ready; off unless a port is set. | | `snapshotStore` | none | An `S3Config`: the store a snapshot request may name a key in. Without one, a snapshot only goes back to the caller; the server never writes one to its own disk. | | `stateRoot` | under `$MIRAGE_HOME` | Where live state is kept. | | `idleGraceSeconds` | `30` | Seconds the last workspace may be gone before `onIdleExit` is called. | | `pidFile` | `$MIRAGE_HOME/daemon.pid` | PID file path, exposed as `app.pidFile`. Only the daemon writes it. | | `onIdleExit` | a no-op | Called when the last workspace has been gone `idleGraceSeconds` (30), or on `POST /v1/daemon/shutdown`. | ## Workers By default the daemon is one process, and one thread holds every workspace. With `workers` above 1 (`MIRAGE_WORKERS`, or the `workers` key), it runs that many workers, each the whole server on a Unix socket of its own, and its own server passes each request to the worker holding the workspace. A new workspace goes to a worker at random. The workspaces on one worker share its event loop, and the OS spreads the workers over the CPUs. `worker_type` (`MIRAGE_WORKER_TYPE`, or the `worker_type` key) is `thread` or `process`. TypeScript defaults to threads. Python defaults to threads on an interpreter without the GIL (3.14t) and to processes otherwise, since threads under the GIL take turns. The daemon answers `/v1/health` and `/v1/daemon/ready` itself, merges their `GET /v1/workspaces` lists, and holds `max_workspaces` across the workers. A worker that exits stays gone, and so do its workspaces. Each worker counts its own rate limits, so a limit keyed on the address or the account allows that many requests per worker. The SSH port is one server's, so it does not combine with workers yet. ## Started by the CLI `@struktoai/mirage-cli` runs the same app as a daemon, `mirage-daemon`, on `127.0.0.1:8765` in local auth mode, logging to `~/.mirage/daemon.log`. That entry adds the two daemon behaviors: it writes `$MIRAGE_HOME/daemon.pid` for `mirage daemon stop` and `kill`, and exits 30 seconds (`MIRAGE_IDLE_GRACE_SECONDS`) after its last running workspace stops or is deleted. It listens on `MIRAGE_DAEMON_PORT`, the `port` setting, or `8765`. Its settings are on the [CLI page](/home/access/cli#daemon-config). ## MCP and RPC on their own The [MCP](/home/access/mcp) and [RPC](/home/access/rpc) servers can run over a transport of your own, without the Mirage server. Both serve one session of a [workspace](/typescript/access/in-app). ```ts theme={null} import { StdioServerTransport } from '@modelcontextprotocol/server/stdio' import { createMirageMcpServer } from '@struktoai/mirage-server/mcp' const server = createMirageMcpServer(ws, { sessionId: 'agent' }) await server.connect(new StdioServerTransport()) ``` `createMirageMcpServer(ws, { sessionId?, operations?, name?, version?, staleWriteProtection?, allCalls? })` returns the MCP SDK's `McpServer`. `allCalls: true` adds the [VFS calls and explain](/home/access/mcp#vfs-calls). ```ts theme={null} import { MirageRpcServer } from '@struktoai/mirage-server/rpc' const server = new MirageRpcServer(ws, { sessionId: 'agent' }) const response = await server.handle({ jsonrpc: '2.0', id: 1, method: 'vfs/readdir', params: { path: '/' }, }) ``` `new MirageRpcServer(ws, { sessionId?, operations?, name?, version? })`. `handle(message)` processes a message and returns its response (`null` for a notification). `serve(lines, write)` processes each line of an async iterable until it ends. ## What is particular to this server The protocol is the same on both servers. These are the differences in how this one serves it: * **No legacy `scp -O`.** Modern `scp` uses SFTP, which is served; the old SCP protocol is not. * **`authorized_keys` options.** `mirage-profile` and `mirage-account` are read: the first binds the key to a [profile](/home/access/ssh#auth-optional), the second opens only that [account](/home/access/http#accounts)'s workspaces. A key line carrying any other option (`from=`, `command=`, ...) is skipped with a warning, rather than accepted as if it had none. * **Terminal line limit.** 1024 bytes. * **One event loop.** Every workspace shares Node's loop. Shell evaluation yields between steps, but a long synchronous step in a JavaScript callback or a CPU-heavy runtime holds every workspace until it returns, so run such work in a worker. ## Code map | Path | What | | - | - | | [`packages/server/src/app.ts`](https://github.com/strukto-ai/mirage/blob/main/typescript/packages/server/src/app.ts) | `buildApp`: routers, MCP and RPC endpoints, the SSH server. | | [`packages/server/src/bin/daemon.ts`](https://github.com/strukto-ai/mirage/blob/main/typescript/packages/server/src/bin/daemon.ts) | `mirage-daemon`, the daemon entry the CLI starts. | | [`packages/server/src/routers/`](https://github.com/strukto-ai/mirage/tree/main/typescript/packages/server/src/routers) | The HTTP routes: workspaces, sessions, shell, tools, jobs, asks. | | [`packages/server/src/mcp/`](https://github.com/strukto-ai/mirage/tree/main/typescript/packages/server/src/mcp) | `createMirageMcpServer`, the `/mcp` endpoint, and the stdio relay `mirage mcp` runs. | | [`packages/server/src/rpc/`](https://github.com/strukto-ai/mirage/tree/main/typescript/packages/server/src/rpc) | `MirageRpcServer`, the `/rpc` endpoint, and the stdio relay `mirage rpc` runs. | | [`packages/server/src/ssh/`](https://github.com/strukto-ai/mirage/tree/main/typescript/packages/server/src/ssh) | The SSH server: shell, exec and SFTP. | | [`packages/core/src/workspace/tools/`](https://github.com/strukto-ai/mirage/tree/main/typescript/packages/core/src/workspace/tools) | The agent tool table behind `session.tools`, which every interface calls. | | [`packages/cli/src/`](https://github.com/strukto-ai/mirage/tree/main/typescript/packages/cli/src) | The `mirage` CLI, one module per verb. | ## Custom VFS calls and streaming reads `POST /v1/workspaces/{id}/vfs/{name}` dispatches a registered VFS operation with JSON `{ "path": "/data/item", "kwargs": {} }` and returns its result as JSON. It uses the authenticated request's session and the ordinary dispatcher; callers cannot override session or admission fields. Binary values use the server's base64 JSON representation. `POST /v1/workspaces/{id}/vfs/read` with `{ "path": "/data/item", "stream": true }` streams `application/octet-stream`. It uses the same authentication and file policy as other VFS routes, with bounded reads and cancellation cleanup. # Claude Agent SDK Source: https://docs.mirage.strukto.ai/typescript/agents/claude-agent-sdk Run @anthropic-ai/claude-agent-sdk against a Mirage workspace through an in-process MCP server of Mirage's tools. The [Claude Agent SDK](https://code.claude.com/docs/en/agent-sdk/) builds agents on Claude. Mirage exposes any `Workspace` to the SDK as an in-process MCP server, so every file and shell operation the agent runs is routed through Mirage instead of the host filesystem. This is distinct from [Claude Code](/home/agents/claude-code), the `claude` CLI run as it is on a workspace. Use this SDK integration when you build your own agent with the SDK's `query()` and want Mirage tools rather than the built-in file tools. ## Install Use this integration from Node. The Claude Agent SDK launches the native Claude Code runtime, so the complete `query()` workflow does not run in a browser. ```bash theme={null} pnpm add @struktoai/mirage-claude-agent-sdk @struktoai/mirage-node @anthropic-ai/claude-agent-sdk ``` ## Usage `buildOptions` adds and preapproves Mirage tools, turns off the SDK's built-in tools, and describes the mounted paths in the system prompt. ```ts theme={null} import { MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node' import { query } from '@anthropic-ai/claude-agent-sdk' import { buildOptions } from '@struktoai/mirage-claude-agent-sdk' const ws = new Workspace({ '/': new RAMVFS() }, { mode: MountMode.WRITE }) for await (const msg of query({ prompt: "Write /hello.txt with 'hi from mirage', then cat it.", options: await buildOptions(ws), })) { console.log(msg) } ``` ## Composing with other MCP servers Use `MirageServer` directly to combine Mirage with other servers: ```ts theme={null} import { MirageServer, buildSystemPrompt } from '@struktoai/mirage-claude-agent-sdk' const options = { mcpServers: { mirage: MirageServer(ws), github: githubServer }, allowedTools: ['mcp__mirage__*', 'mcp__github__*'], tools: [], systemPrompt: await buildSystemPrompt({ workspace: ws }), } ``` ## Shell To keep Claude's own Bash tool and run it in a workspace, point the SDK at `mirage-bash`, as for [Claude Code](/home/agents/claude-code#shell), and give it Mirage's other tools over [`mirage mcp`](/home/access/mcp) in place of Claude's file tools. Both reach one workspace that the Mirage daemon serves: ```bash theme={null} mirage workspace create workspace.yaml --id demo ``` ```ts theme={null} import type { Options } from '@anthropic-ai/claude-agent-sdk' const options: Options = { cwd: '/Users/me/project', env: { ...process.env, CLAUDE_CODE_SHELL: '/Users/me/.local/bin/mirage-bash', MIRAGE_WORKSPACE: 'demo', }, mcpServers: { mirage: { type: 'stdio', command: 'mirage', args: ['mcp', '-w', 'demo'] }, }, allowedTools: ['Bash', 'mcp__mirage__*'], disallowedTools: ['Read', 'Edit', 'Write', 'Glob', 'Grep', 'mcp__mirage__shell'], } ``` `env` replaces the environment Claude Code starts with, so keep `process.env` in it. `command -v mirage-bash` prints the path. * Bash runs in the workspace, and Mirage's `read`, `write`, `edit`, `ls`, `grep` and `glob` take the place of Claude's Read, Edit, Write, Glob and Grep, so every file the agent touches goes through Mirage. * Mount the project and `/tmp` at their own paths, as the [Claude Code page](/home/agents/claude-code#shell) shows, so `cd` carries over. * To run under a [profile](/home/profiles), create a session with `mirage workspace session create -w demo -s agent -p reviewer`, then set `MIRAGE_SESSION` to `agent` and add `-s agent` to the `mirage mcp` arguments. ## Tools The server serves the session's seven tools, [`session.tools`](/typescript/access/in-app#session-tools): `shell`, `read`, `write`, `edit`, `ls`, `grep` and `glob`, named `mcp__mirage__<tool>` in the SDK. It carries the ones the session's profile leaves it (`session.tools.names()`). ## Exports | Symbol | Purpose | | - | - | | `MirageServer` | An in-process MCP server exposing the Mirage tools; pass it to `options.mcpServers`. | | `buildOptions` | Returns ready-to-use query `Options` backed by a workspace: the `MirageServer` tools as the `mirage` MCP server, preapproved, and a system prompt describing the mounts. The SDK's built-in tools are disabled, so the Mirage tools are the agent's only file access layer. | | `BuildOptionsOptions` | Options for `buildOptions`: `systemPrompt` replaces the generated prompt, and `sessionId` names the Mirage session the tools act as. | | `MIRAGE_SYSTEM_PROMPT` | The default system prompt: how the Mirage filesystem differs from a plain one. | | `buildSystemPrompt` | Returns `MIRAGE_SYSTEM_PROMPT` followed by a description of the mounted paths and any extra instructions, ready to use as an agent's system prompt. | | `EDIT_DESCRIPTION` `GLOB_DESCRIPTION` `GREP_DESCRIPTION` `LS_DESCRIPTION` `READ_DESCRIPTION` `SHELL_DESCRIPTION` `WRITE_DESCRIPTION` | The text a Mirage tool gives the model, shared by the MCP server and every adapter that serves Mirage's tool table. | # Claude Managed Agents Source: https://docs.mirage.strukto.ai/typescript/agents/claude-managed-agents Make a Mirage workspace the self-hosted environment of an agent on Claude Managed Agents. [Claude Managed Agents](https://platform.claude.com/docs/en/managed-agents/overview) runs the agent on Anthropic's servers. In a [self-hosted environment](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes), a worker you run answers its `bash`, `read`, `write`, `edit`, `glob` and `grep` calls. `mirageTools(ws)` gives that worker Mirage's versions, so every call runs in the workspace, under its profile, mounts and policies. The worker only connects out to Anthropic, so it can run inside your own server. ## Install ```bash theme={null} npm install @struktoai/mirage-claude-managed-agents @struktoai/mirage-node @anthropic-ai/sdk ``` ## Run a worker The workspace here keeps its files in Redis next to RAM, which needs a Redis server and the `redis` package: ```bash theme={null} docker run -d -p 6379:6379 redis npm install redis ``` Create a self-hosted environment and an agent with the `agent_toolset_20260401` toolset as [Anthropic's guide](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes) shows, then serve its sessions from the workspace: ```ts theme={null} import Anthropic from '@anthropic-ai/sdk' import { MountMode, RAMVFS, RedisVFS, Workspace } from '@struktoai/mirage-node' import { mirageTools } from '@struktoai/mirage-claude-managed-agents' const ws = new Workspace( { '/workspace': new RAMVFS(), '/redis': new RedisVFS({ url: 'redis://localhost:6379' }) }, { mode: MountMode.WRITE }, ) const worker = new Anthropic().beta.environments.work.worker({ environmentId: process.env.ANTHROPIC_ENVIRONMENT_ID!, environmentKey: process.env.ANTHROPIC_ENVIRONMENT_KEY!, tools: mirageTools(ws), }) await worker.run() ``` ## How it behaves * The tools keep the toolset's names. One the session's [profile](/home/policy/overview) would always refuse is left out: a read-only workspace gets no `write` or `edit`. * `bash` runs Mirage's shell, so a line sees the workspace's mounts and commands, not the worker's machine. A `restart` is refused, since the session keeps its directory and variables. A relative path resolves against the session's working directory, which `cd` moves. * `write` overwrites a file only after the agent read all of it, and `write` and `edit` refuse a file that changed since the agent read it. `staleWriteProtection: false` turns that off. * `sessionId` runs the tools as another session, with its profile. * `web_search` and `web_fetch` still run on Anthropic's servers. Turn them off in the agent's toolset to keep the agent to the workspace. ## Example [`examples/typescript/agents/claude_managed_agents/redis_report.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/agents/claude_managed_agents/redis_report.ts) creates the agent and a session, serves the session from a RAM and Redis workspace, asks the agent to total `/workspace/orders.csv` into `/redis/report.md`, and prints the report from Redis. # DeepSeek Harness Source: https://docs.mirage.strukto.ai/typescript/agents/dsh Register Mirage as the filesystem and shell of DeepSeek Harness (dsh), so its file tools and bash tool run on mounted data. [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (`dsh`) is a plugin-based agent harness on Cordis where the filesystem and the shell are swappable capability seams. `@struktoai/mirage-dsh` provides both seams over one Mirage workspace: `ctx.fs` for dsh's read/write/edit tools and `ctx.shell` for its bash tool. Anything Mirage mounts (S3, Gmail, Slack, Notion, Postgres) becomes the world those tools operate in. ## Install ```bash theme={null} npm install @struktoai/mirage-dsh @struktoai/mirage-node @struktoai/mirage-core @deepseek-ai/cordis @deepseek-ai/dsh-fs @deepseek-ai/dsh-shell @deepseek-ai/dsh-spill @deepseek-ai/dsh-subprocess @pydantic/monty redis ``` ## Compose Four Cordis plugins. `MirageService` owns the workspace; the providers inject it. Mix any mounts, such as Slack and Redis beside a scratch RAM mount: ```ts theme={null} import { Context } from '@deepseek-ai/cordis' import type { ShellExecRequest } from '@deepseek-ai/dsh-shell' import { buildRuntime, MountMode, RAMVFS, RedisVFS, SlackVFS, Workspace } from '@struktoai/mirage-node' import { MirageFileSystem, MirageService, MirageShellExecutor, MirageSpillStore, } from '@struktoai/mirage-dsh' const ws = new Workspace( { '/tmp': [new RAMVFS(), MountMode.EXEC], '/redis': [new RedisVFS({ url: redisUrl }), MountMode.WRITE], '/slack': [new SlackVFS({ token: slackBotToken }), MountMode.EXEC], }, { runtimes: [buildRuntime('monty', { captures: ['python', 'python3'] })] }, ) const ctx = new Context() await ctx.plugin(MirageService, { workspace: ws }).await() await ctx.plugin(MirageFileSystem, {}).await() await ctx.plugin(MirageShellExecutor, {}).await() await ctx.plugin(MirageSpillStore, {}).await() ``` `MirageSpillStore` is what keeps an oversized tool result recoverable. dsh replaces a result over its inline cap with a preview plus a locator and tells the model to read or grep it; without this plugin that locator names a file on the harness's own disk, which nothing in the workspace can open. Registered, the artifact is written through the same dispatcher as every other effect, so the locator is an ordinary workspace path. It defaults to `/tmp/dsh-spill`, so give it a `dir` on a writable mount if `/tmp` is not one. Mirage mounts are read-only by default; the mode ladder is `READ` \< `WRITE` \< `EXEC`, so mount with `MountMode.WRITE` where dsh's write tools should work and `MountMode.EXEC` where `python3` or `js` may run code. dsh's bash tool now spans every source in one line (`resolve` fills a request into a spec with the defaults, `execute` starts it and hands back the process, and `result()` waits for its outcome, the same calls dsh's own tools make): ```ts theme={null} const shell = ctx.shell const run = async (request: ShellExecRequest) => (await shell.execute(shell.resolve(request))).result() const sweep = await run({ command: 'grep -rln session /redis /tmp' }) ``` A caller that keeps the process instead of awaiting `result()` runs the command in the background: `readOutput()` drains what it printed so far, and `onExpiry: 'none'` lets it outlive `timeoutMs`. `MirageService` also accepts `mounts` instead of a live `workspace`; it then constructs the workspace itself and closes it when the plugin unloads. Each command is a clean slate: `cd`, `export`, and function definitions inside one bash call do not survive into the next, which is the one-shot contract of dsh's bash tool. For a persistent shell instead, bind the executor to a named workspace session: ```ts theme={null} await ctx.plugin(MirageShellExecutor, { sessionId: 'agent-1' }).await() ``` A bound session keeps its cwd, exports, and functions across calls. It is created on first use (an existing session is adopted as is), and two executors bound to different sessions stay fully apart on one workspace. While one command still runs in the session, such as one left in the background, the next runs beside it on a copy of the session instead of waiting for it to end, so that command's `cd` and `export` last for it alone. dsh sends a working directory and a set of managed `DSH_*` variables with every call, and in Mirage a per-call directory or environment forks a subshell. Taken at face value, a bound session would therefore have nothing left to persist, so both are checked first. The workdir dsh computed on its own machine is not a directory in this world, so it is ignored: the executor's own `workdir` when unbound, the session's cwd when bound, and `ctx.fs` resolves relative paths against the same base. The `DSH_*` variables are set in the session once instead of riding along per call. A workdir that does exist here, or any other per-call variable, still forks a subshell, which is what "only this command" should mean. ```ts theme={null} // dsh sends its own machine's cwd, a path this world does not contain const host = '/Users/somebody/host-project' await run({ command: 'cd /tmp && export TOKEN=abc', workdir: host }) const result = await run({ command: 'pwd; echo $TOKEN', workdir: host }) // result.stdout.text === '/tmp\nabc\n' ``` ## Run Python with monty The `runtimes` entry above sets [monty](https://github.com/pydantic/monty), a sandboxed Python interpreter with no host access, up to capture `python` and `python3`; the catch-all `workspace` runtime serving the shell commands is always present and needs no entry. A captured invocation (a script file, inline `-c` code, or code piped on stdin) runs inside the workspace, never on the machine. A script can live on any mount: upload `example.py` to a Slack channel and run it straight off the mount, with the shell's redirection filing its stdout back into Redis: ```ts theme={null} const script = await run({ command: 'python3 /slack/channels/general__C0.../2026-08-13/files/example__F0....py > /redis/report.txt', }) ``` [`examples/typescript/agents/dsh/dsh.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/agents/dsh/dsh.ts) is the runnable version of this whole page, with the script in [`example.py`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/agents/dsh/example.py). ## Install into a dsh profile The package is also a dsh bundle: its manifest carries a patch layer that swaps dsh's filesystem, bash and spill providers for the mirage ones and disables the host-subprocess surfaces the workspace does not contain (PowerShell, the ripgrep search tool). Stock dsh, including its web app, then runs on mounted data: ```bash theme={null} dsh plugin --profile web add @struktoai/mirage-dsh dsh --profile web ``` The bundle's default world is one RAM scratch mount at `/tmp`. Mount real sources by overriding the `mirage` row in the profile's own `cordis.patch.yml`, in declarative form (the VFS registry name, a mode, and the VFS's config; `!!js` expressions resolve at mount time): ```yaml theme={null} - id: mirage config: mounts: /tmp: { vfs: ram, mode: exec } /slack: vfs: slack mode: read config: { token: !!js process.env.SLACK_BOT_TOKEN } runtimes: - { name: monty, captures: [python, python3] } ``` A mount block takes `vfs`, `mode` and `config`, and refuses any other key. The same blocks work in code, beside live instances, in `MirageService`'s `mounts`. A runtime row also takes the runtime's own `config`, as a workspace file's does, and refuses a key the runtime does not have. Both seams tell dsh they are a `workspace-write` sandbox, which is what lets dsh's permission presets compose over them. The claim holds only while every runtime stays inside the VFS (each runtime's `reach` is `workspace`). Add a host-reaching one, such as `local` Python, and both seams drop the claim, since a script could then act outside the mounts: dsh is better told there is no sandbox than a false one. The claim is enforced per call, not merely advertised. dsh resolves a policy for every command and every file edit, and Mirage applies it. Under `read-only` the shell runs in a twin of its own session with every grant narrowed to read, so a session already confined to some mounts stays confined (the twin narrows, it never widens), and `ctx.fs` refuses a write or an edit with `FS_SANDBOX_DENIED`, the same error dsh's own sandboxed backend raises: ```ts theme={null} const policy = { mode: 'read-only', workspaceRoot: '/Users/somebody/host-project' } as const const denied = await run({ command: 'echo hi > /tmp/out.txt', sandboxPolicy: policy }) // nonzero exitCode, and denied.sandbox is { mode: 'read-only', denied: true, ... } await ctx.fs.writeText(await ctx.fs.resolve('/tmp/out.txt'), 'hi', undefined, undefined, policy) // throws FsError, code FS_SANDBOX_DENIED ``` So `DSH_PERMISSION_MODE=read-only` confines a Mirage world, and the result reports the mode the command actually ran under. The `/dev` null sink stays writable, as that mode requires. The policy's `workspaceRoot` is a directory on the host and is deliberately never consulted: here the mounts and their modes are the boundary. ## Permissions: allow, ask, deny A sandbox mode says where writes may land. It says nothing about which commands a session may run at all, and that is what a Mirage **permission document** is for. A role lists the tools it admits, the lines it refuses, and the lines a human has to sign off on: ```yaml theme={null} - id: mirage config: profiles: agent: commands: allow: [cat, ls, grep, rm] ask: - { commands: [rm], reason: deletes are reviewed } deny: - { commands: [rm -rf], reason: rm -rf is blocked } profile: agent ``` The same block works in code, as `MirageService`'s `profiles` and `profile`. Each role is validated as it loads, so a misspelled field is a startup error rather than a surprise on the first command. A word no `allow` entry covers is not a command here at all — the agent reads bash's own `command not found`, so an unlisted tool never leaks that it exists. `profiles` configures a workspace `MirageService` builds, so it pairs with `mounts` and is refused beside a live `workspace` — an adopted workspace's roles are the embedder's own, and so is how its asks get answered. Passing both would mean quietly taking over a seam that may already be filled. To adopt a workspace *and* route its asks through dsh, build the handler yourself and hand it to the workspace: ```ts theme={null} import { askThroughApproval } from '@struktoai/mirage-dsh' const ctx = new Context() const ws = new Workspace(mounts, { profiles, profile: 'agent', onAsk: askThroughApproval(ctx) }) await ctx.plugin(MirageService, { workspace: ws }).await() ``` Building the handler before the plugins load is fine: it reads `ctx.approval` at ask time, not at construction, so an approval plugin composed later is still found. A **deny** refuses the line at 126 in bash's voice, and the reason rides on the result as its `decision` record, which is also what dsh reads to tell a policy refusal from a command that failed on its own. Command rules match token prefixes: `rm` covers every `rm` line, while `rm -rf` does not match `rm -r -f` or `rm --recursive --force`. Those forms still match the broader `rm` ask rule. ``` $ rm -rf /data/build rm: Permission denied ``` ```ts theme={null} result.decision // { kind: 'deny', reason: 'rm -rf is blocked', policy: 'PermissionsPolicy', askId: null } ``` An **ask** is put to the human through dsh's own approval channel, `ctx.approval` — the same prompt dsh already shows for its escalations, so nothing new appears in the UI. The bridge maps dsh's answer onto Mirage's ledger: | dsh answers | the line | | - | - | | `allowed-once` | runs, and only this line — the next `rm` asks again | | `rejected` | is refused | | `cancelled` (the prompt was dismissed) | is refused | | `unavailable` (nobody could answer) | is refused | The prompt is the rule's reason and the line it is about, quoted word by word as a shell would read it back: the human is authorizing this run, so a name carrying a space or a newline cannot pass itself off as two operands or as two lines. Ordinary names stay bare. Only `allowed-once` is a yes, and it grants exactly the line that asked; a single nod is never widened into a standing grant. The three refusals match what dsh does with the same vocabulary for its own escalations, where a rejection, a dismissal and an unanswerable ask all fail closed. A refused retry of the same line is answered from the record rather than prompting again, so a human who said no is not asked twice about it. A question never outlives the run that raised it. The run's abort signal goes to the channel with the request, so a prompt can take itself down, and the ledger stops waiting on the same signal — a line whose approval is still unanswered when its timeout expires (or when the caller kills it) comes back as the kill it was given, not as a refusal: ```ts theme={null} const killed = await run({ command: 'rm /data/notes.txt', timeoutMs: 5000 }) // killed.timedOut true // killed.exitCode null ``` Whatever the human says afterwards is dropped rather than recorded. Banking a late yes would leave a spend-once grant in the ledger for the next identical line to take, with nobody asked; the question stays open instead. A rule can also be scoped to one mount, so it applies only to a line working inside it. That is how a role asks about deletes in scratch space while leaving its own housekeeping elsewhere alone: ```yaml theme={null} mounts: /tmp: commands: ask: - { commands: [rm], reason: deletes are reviewed } ``` With **no approval plugin composed** — a headless run, a cron job, CI — an ask has nowhere to go, so it becomes a pending record instead of a refusal: ``` $ rm /data/notes.txt rm: Permission denied ``` ```ts theme={null} result.decision // { kind: 'pending', reason: 'deletes are reviewed', policy: '', askId: '0efc4a8f6280' } ``` This is deliberate: the document says `ask`, and silently rewriting that as `deny` would change what the operator wrote. The question is real and answerable, through `ctx.mirage.decisions`: ```ts theme={null} import { Outcome, Scope } from '@struktoai/mirage-core' const [waiting] = ctx.mirage.decisions.pending('agent') await ctx.mirage.decisions.answer(waiting.id, Outcome.ALLOW, Scope.SESSION) ``` `ONCE` passes the retry of that one line; `SESSION` passes every line the same rule covers for the rest of the session. Nothing reaches further — an answer is never inherited by another session, and never re-opens a deny rule, which is consulted first. A refused line is reported as refused, whatever refused it: `result.sandbox.denied` is set for a policy deny and for an unanswered ask, not only for the read-only narrowing, and under `workspace-write` as readily as under `read-only`. A mode describes what the mounts allow and says nothing about whether a rule forbids the line. It holds for a line that redirects its diagnostics too (`rm secrets 2>&1` leaves stderr empty and the refusal on stdout), where the exit code has to agree before words on stdout are read as a ruling, so a command printing the phrase as data is not mistaken for one. One gap is worth naming: a rule scoped to a path refuses one operand in GNU's own voice (`cat: /data/notes/a.txt: no notes`, exit 1), which carries no fixed marker, so that shape is not flagged — Mirage has no out-of-band denial channel on `ExecuteResult`, and inventing a marker would report ordinary command failures as policy refusals. Through `ctx.fs`, a rule refusal arrives as `FS_SANDBOX_DENIED` rather than `FS_PERMISSION_DENIED`, which is what makes dsh's tool layer attach its escalation hint. A plain mount-mode refusal keeps `FS_PERMISSION_DENIED`: a mode is the shape of this world, while a rule is a confinement the call may be entitled to escalate past. ### Asking what a line would do `explain` runs a line through the same gate the dispatcher uses, without running it: ```ts theme={null} const what = await ctx.mirage.explain('rm /data/notes.txt') // what.outcome 'ask' // what.reason 'deletes are reviewed' // what.source where the rule that spoke is written // what.exitCode / what.stderr exactly what the agent would get // what.node the parsed line, each command with its own verdict ``` It spends no approval, records no question and never reaches the human, so it is safe to call about a line nobody typed — a pre-execute check, or an operator asking why a command was refused. Because it is the same gate, an explanation of a refused line is byte-identical to the refusal. ## Custom backends A mount is not limited to the builtin VFS (`ram`, `s3`, `slack`, `redis`, ...). Register your own VFS factory host-side and its name becomes usable in a `mounts` block exactly like a builtin: ```ts theme={null} import { registerVfs } from '@struktoai/mirage-node' registerVfs('acme', (config) => Promise.resolve(new AcmeVFS(config))) ``` ```yaml theme={null} - id: mirage config: mounts: /acme: { vfs: acme, mode: read, config: { token: !!js process.env.ACME_TOKEN } } ``` The registration must run before the workspace builds, since a `mounts` block only names a VFS, it does not construct one. In a dsh bundle that means a small plugin the profile loads alongside `@struktoai/mirage-dsh` (or a plain import in code, before `MirageService` starts), not the declarative patch. A builtin name cannot be shadowed, so a custom backend needs its own name. Nothing else changes: the shell, the commands, and the sandbox claim treat a custom mount like any other. ## Background commands A backgrounded command streams its output through a workspace console rather than arriving whole: each statement of a compound line lands as it finishes, and stdout and stderr keep their own channels. The unread backlog is bounded to the stdout budget, so a reader that never drains cannot grow it without limit; output past the budget is flagged lossy, with the freshest kept. Set `spillDir` on `MirageShellExecutor` to a workspace path (for example `/tmp` on a ram mount) and an overrunning command's full stdout and stderr are written there, so the agent can read the complete output back through the same VFS; unset, nothing spills. A concrete scenario: serving agents from a TypeScript server (an Express endpoint, say), where every request is assigned its own context and workspace, created on entry and gone with the response. What one 2 vCPU / 8 GB box holds then depends on the harness: | Harness | Startup | Est. concurrent sessions (2 vCPU / 8 GB) | | - | - | - | | dsh | \~0.5 ms | \~200 | | [Codex](/home/agents/codex) | \~20 ms (+ \~150 ms sandbox startup) | \~30 | | [Claude Agent SDK](/typescript/agents/claude-agent-sdk) | \~40 ms (+ \~150 ms sandbox startup) | \~15 | Concurrency is estimated as about 6 GB of free memory divided by a session's measured resident footprint (a dsh session with a live Python engine is about 27 MB, idle workspaces 240 KB, a Codex session about 200 MB, a Claude Code CLI session about 430 MB); startup is the measured time to bring one session up, process boot for the CLIs and workspace construction for dsh. The dsh numbers already include isolation, since monty is the sandbox and each engine runs on its own crash-isolated worker process; the CLI sessions run on the host, so isolating them means provisioning a container or remote sandbox per session, measured at about 150 ms even for a warm local container and more for a cold or remote one. ## Subprocess provider The bundle also replaces `dsh-subprocess-local` with `MirageSubprocess`. Executable lookup and argv execution stay in the same workspace as `ctx.fs` and `ctx.shell`. It supplies raw pipes or bounded, independently readable output tails. `terminate()` requests cancellation of its managed execution group; `waitForExit(signal)` waits for that group's tracked runners, or returns false if the wait is aborted. Disposal terminates and awaits the provider's groups. This provider currently requires workspace-only runtimes. It refuses native or remote reach, terminal allocation, subprocess spill requests, and environment tombstones instead of falling back to host processes. `graceMs` is validated but cancellation is immediate, with no simulated TERM/KILL escalation. Use `ctx.spill` for separate tool-result artifacts. Native process trees and PTYs need a provider that can actually observe and control them. Set the subprocess provider's `sessionId` to bind it to an existing workspace session and its profile. Omit it to use the default session. Configure the same session on the shell provider when both should share that authority. # Overview Source: https://docs.mirage.strukto.ai/typescript/agents/index Connect a coding agent or an agent framework to a Mirage workspace. ## Coding Agents Claude Code, Codex and Grok Build run as they are, on a workspace the `mirage` CLI creates, whatever language you build in. Their guides are under [Agents](/home/agents#coding-agents). To replace an agent's own file and shell tools instead, load Mirage into it as a plugin: | Agent | Plugin | | - | - | | [Pi Coding Agent](/typescript/agents/pi) | `mirageExtension(ws)` | | [OpenCode](/typescript/agents/opencode) | `@struktoai/mirage-opencode` in `opencode.json` | | [DeepSeek Harness](/typescript/agents/dsh) | `@struktoai/mirage-dsh` | ## Agent SDKs Your program holds the workspace and hands it to the framework. | Framework | Hand it | The agent gets | | - | - | - | | [Vercel AI SDK](/typescript/agents/vercel) | `mirageTools(ws)` | Mirage's seven tools | | [Mastra](/typescript/agents/mastra) | `mirageTools(ws)` | Mirage's seven tools | | [Claude Agent SDK](/typescript/agents/claude-agent-sdk) | `MirageServer(ws)` | Mirage's seven tools | | [OpenAI Agents](/typescript/agents/openai) | `mirageTools(ws)`, or `MirageShellExecutor`, `MirageEditor` and `MirageSandboxClient` | Mirage's seven tools, or its shell, patch and sandbox tools run in Mirage | | [LangChain Deep Agents](/typescript/agents/langchain) | `new LangchainWorkspace(ws)` | its file and shell tools, run in Mirage | Mirage's seven tools are the session's [`session.tools`](/typescript/access/in-app#session-tools): `shell`, `read`, `write`, `edit`, `ls`, `grep` and `glob`. A session gets the ones its [profile](/home/policy/explain#which-tools-the-agent-gets) leaves it (`session.tools.names()`), so an agent is never offered a tool every call of which would be refused. Each framework is its own package: `@struktoai/mirage-vercel`, `@struktoai/mirage-mastra`, `@struktoai/mirage-claude-agent-sdk`, `@struktoai/mirage-openai-agents` or `@struktoai/mirage-langchain`. ```bash theme={null} pnpm add @struktoai/mirage-vercel @struktoai/mirage-node ``` When the framework supports browsers, use `@struktoai/mirage-browser` in place of `@struktoai/mirage-node`. ## API & Environment The provider runs the agent, and the workspace is its environment: its own shell and file tools run in Mirage. | API | Hand it | The agent gets | | - | - | - | | [OpenAI Agents API](/typescript/agents/openai-agents-api) | a `self_hosted` environment, through [exec-server forward](/home/agents/codex#exec-server-forward) | its shell, file and patch tools, run in Mirage | | [Claude Managed Agents](/typescript/agents/claude-managed-agents) | `mirageTools(ws)`, in an `EnvironmentWorker` | its `bash`, `read`, `write`, `edit`, `glob` and `grep`, run in Mirage | # LangChain (Deep Agents) Source: https://docs.mirage.strukto.ai/typescript/agents/langchain Back Deep Agents with a Mirage workspace via LangchainWorkspace. [Deep Agents](https://github.com/langchain-ai/deepagents) is LangChain's framework for long-horizon coding agents. It accepts a pluggable `backend` for filesystem and shell operations, and Mirage ships one. > [!NOTE] > > Node only. `LangchainWorkspace` uses `@struktoai/mirage-node`, and Deep Agents depends on Node APIs. ## Install ```bash theme={null} pnpm add @struktoai/mirage-langchain @struktoai/mirage-node deepagents @langchain/anthropic ``` ## Usage ```ts theme={null} import { MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node' import { ChatAnthropic } from '@langchain/anthropic' import { createDeepAgent } from 'deepagents' import { LangchainWorkspace, buildSystemPrompt, extractText, } from '@struktoai/mirage-langchain' const ws = new Workspace({ '/': new RAMVFS() }, { mode: MountMode.WRITE }) const agent = createDeepAgent({ model: new ChatAnthropic({ model: 'claude-sonnet-4-6' }), systemPrompt: await buildSystemPrompt({ mountInfo: { '/': 'In-memory filesystem (read/write)' }, }), backend: new LangchainWorkspace(ws), }) const result = await agent.invoke({ messages: [{ role: 'user', content: 'Create /report.md and summarize.' }], }) for (const text of extractText(result.messages.slice(-1))) { console.log(text) } ``` ## Multimodal files `read_file` can pass images, PDFs, audio, video, PPT, and PPTX files from a Mirage mount to a model as multimodal content. The selected model and provider must support the corresponding input type. Text files continue to use line-based pagination. ## Exports | Symbol | Purpose | | - | - | | `LangchainWorkspace` | A `SandboxBackendProtocolV2` implementation for Deep Agents that runs reads, writes, edits, search and shell commands in a Mirage workspace. | | `LangchainWorkspaceOptions` | Options for `LangchainWorkspace`: `sandboxId` sets the backend's `id` (default `mirage`), and `sessionId` names the Mirage session it acts as. | | `extractText` | Returns the non-empty text blocks of an array of LangChain messages, in order, as `string[]`. | | `MIRAGE_SYSTEM_PROMPT` | The default system prompt: how the Mirage filesystem differs from a plain one. | | `buildSystemPrompt` | Returns `MIRAGE_SYSTEM_PROMPT` followed by a description of the mounted paths and any extra instructions, ready to use as an agent's system prompt. | | `BuildSystemPromptOptions` | Options for `buildSystemPrompt`: which mounts to describe and what to append. | ## Examples * [`examples/typescript/agents/langchain/ram_deepagent.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/agents/langchain/ram_deepagent.ts), RAM-only sandbox. * [`examples/typescript/agents/langchain/ram_pdf_deepagent.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/agents/langchain/ram_pdf_deepagent.ts), RAM-backed PDF reading with no external storage credentials. * [`examples/typescript/agents/langchain/s3_deepagent.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/agents/langchain/s3_deepagent.ts), read-only S3 exploration. # Mastra Source: https://docs.mirage.strukto.ai/typescript/agents/mastra Wire mirage tools into a Mastra Agent via @struktoai/mirage-mastra. [Mastra](https://mastra.ai) is an opinionated TypeScript framework for AI agents and workflows. Mirage ships a tool factory that gives a Mastra `Agent` a session's seven tools. > [!NOTE] > > Node only. The Mirage adapter is runtime-agnostic, but most Mastra setups (memory, evals, workflows) depend on Node APIs. ## Install ```bash theme={null} pnpm add @struktoai/mirage-mastra @struktoai/mirage-node @mastra/core ``` ## Usage ```ts theme={null} import { MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node' import { Agent } from '@mastra/core/agent' import { buildSystemPrompt, mirageTools } from '@struktoai/mirage-mastra' const ws = new Workspace({ '/': new RAMVFS() }, { mode: MountMode.WRITE }) const agent = new Agent({ id: 'mirage-ram-agent', name: 'Mirage RAM Agent', instructions: await buildSystemPrompt({ mountInfo: { '/': 'In-memory filesystem (read/write)' }, }), model: 'openai/gpt-5.4-mini', tools: mirageTools(ws), }) const result = await agent.generate( "Create /hello.txt with 'hi from mirage' and list every file under /.", { maxSteps: 20 }, ) console.log(result.text) ``` ## Exports | Symbol | Purpose | | - | - | | `MIRAGE_SYSTEM_PROMPT` | The default system prompt: how the Mirage filesystem differs from a plain one. | | `buildSystemPrompt` | Returns `MIRAGE_SYSTEM_PROMPT` followed by a description of the mounted paths and any extra instructions, ready to use as an agent's system prompt. | | `BuildSystemPromptOptions` | Options for `buildSystemPrompt`: which mounts to describe and what to append. | | `mirageTools` | Returns Mirage's tools (`shell`, `read`, `write`, `edit`, `ls`, `grep`, `glob`) as Mastra tools, limited to what the session's profile allows. | ## Examples * [`examples/typescript/agents/mastra/ram_mastra.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/agents/mastra/ram_mastra.ts), RAM-only sandbox driven by `gpt-5.4-mini`. # OpenAI Agents SDK Source: https://docs.mirage.strukto.ai/typescript/agents/openai Run @openai/agents against a Mirage workspace with shell, editor, file-reading tools, and a SandboxAgent client. The OpenAI Agents SDK ([@openai/agents](https://github.com/openai/openai-agents-js)) ships `shellTool` and `applyPatchTool` primitives that take pluggable `Shell` and `Editor` backends. Mirage provides `MirageShellExecutor` and `MirageEditor` implementations that route every command and patch through your `Workspace` instead of the host shell. `mirageReadFileTool` adds agent-initiated file reads with structured model input for text, images, and PDFs. ## Install `@struktoai/mirage-openai-agents` is runtime-agnostic. Pair it with `@struktoai/mirage-node` for Node or `@struktoai/mirage-browser` for the browser. ```bash Node theme={null} pnpm add @struktoai/mirage-openai-agents @struktoai/mirage-node @openai/agents ``` ```bash Browser theme={null} pnpm add @struktoai/mirage-openai-agents @struktoai/mirage-browser @openai/agents ``` ## Usage ```ts theme={null} import { MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node' import { Agent, applyPatchTool, run, shellTool } from '@openai/agents' import { MirageEditor, MirageShellExecutor, buildSystemPrompt, mirageReadFileTool, } from '@struktoai/mirage-openai-agents' const ws = new Workspace({ '/': new RAMVFS() }, { mode: MountMode.WRITE }) const agent = new Agent({ name: 'Mirage RAM Agent', model: 'gpt-5.5-mini', instructions: await buildSystemPrompt({ mountInfo: { '/': 'In-memory filesystem (read/write)' }, }), tools: [ mirageReadFileTool(ws), shellTool({ shell: new MirageShellExecutor(ws) }), applyPatchTool({ editor: new MirageEditor(ws) }), ], }) await run(agent, "Create /hello.txt with 'hi from mirage' and cat it.") ``` For an OpenAI-compatible provider without the Responses API, give the agent `mirageTools(ws)`, Mirage's seven function tools, instead of the hosted shell and editor tools. ## Sandbox Agent `SandboxAgent` runs the SDK's own `exec_command`, `apply_patch` and `view_image` tools against a sandbox session. `MirageSandboxClient` makes that session a Mirage workspace, and `MirageCapability` adds the workspace's mounts (backend, mode, commands) to the agent's instructions. The client also needs `@openai/agents-core`, at the same version as `@openai/agents`. ```ts theme={null} import { run } from '@openai/agents' import { Capabilities, SandboxAgent } from '@openai/agents/sandbox' import { MirageCapability, MirageSandboxClient } from '@struktoai/mirage-openai-agents' const agent = new SandboxAgent({ name: 'Mirage Sandbox Agent', model: 'gpt-5.5', capabilities: [...Capabilities.default(), new MirageCapability()], }) const result = await run(agent, 'Summarize /data/report.csv into /notes.md.', { sandbox: { client: new MirageSandboxClient(ws) }, }) ``` How the session behaves: * Every command starts at the manifest root, `/` unless you configure a `Manifest`, or at the model's `workdir`, and a `cd` or `export` ends with its command, as in the SDK's other sandboxes. Commands see the manifest's environment. Each sandbox session has its own Mirage session. Its commands run in it side by side, so one left running in the background does not hold up the next. * A command still running after `exec_command`'s yield time keeps running. The model polls it with `write_stdin` and stops it with Ctrl-C (`\u0003`). * Relative paths resolve against the manifest root. Manifest `file` and `dir` entries are written into the workspace; other entry types raise `SandboxUnsupportedFeatureError`. * A run paused for tool approval resumes on the same workspace and keeps the files the agent wrote. ## Exports | Symbol | Purpose | | - | - | | `MirageCapability` | Tell a SandboxAgent's model which Mirage mounts it is working in. | | `MirageEditor` | An `Editor` that applies patches through the workspace's file operations; pass it to `applyPatchTool({ editor })`. | | `mirageTools` | Returns Mirage's tools (`shell`, `read`, `write`, `edit`, `ls`, `grep`, `glob`) as OpenAI Agents function tools, limited to what the session's profile allows. | | `mirageReadFileTool` | Returns a `read_file` function tool: text comes back as text, images as image input and PDFs as file input the model can see. | | `MirageReadFileOutput` | What the `read_file` tool returns: text, an image, or a file such as a PDF, as the model receives it. | | `MirageSandboxClient` | The OpenAI Agents SDK sandbox client over an in-process Mirage workspace. | | `MirageSandboxSession` | One SDK sandbox session, backed by its own Mirage shell session. | | `MirageSandboxSessionState` | The serializable state of a `MirageSandboxSession`: the SDK's sandbox state plus `mirageSessionId`, the Mirage session it runs in. | | `MirageShellExecutor` | A `Shell` that runs each command in the workspace's shell; pass it to `shellTool({ shell })`. | | `MIRAGE_SYSTEM_PROMPT` | The default system prompt: how the Mirage filesystem differs from a plain one. | | `buildSystemPrompt` | Returns `MIRAGE_SYSTEM_PROMPT` followed by a description of the mounted paths and any extra instructions, ready to use as an agent's system prompt. | | `BuildSystemPromptOptions` | Options for `buildSystemPrompt`: which mounts to describe and what to append. | Unsupported binary formats return a metadata description instead of being decoded as corrupt text. The tool reads raw workspace bytes, so files mounted from RAM, S3, and other Mirage mounts use the same model-input path. ## Examples * [`examples/typescript/agents/openai_agents/ram_agent.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/agents/openai_agents/ram_agent.ts), RAM-only sandbox. * [`examples/typescript/agents/openai_agents/multi_vfs_agent.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/agents/openai_agents/multi_vfs_agent.ts), RAM + S3 mounts. * [`examples/typescript/agents/openai_agents/sandbox_agent.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/agents/openai_agents/sandbox_agent.ts), `SandboxAgent` over a RAM workspace with a read-only data mount. * [`examples/typescript/agents/openai_agents/snapshot.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/agents/openai_agents/snapshot.ts), branch & roll back agent state. # OpenAI Agents API Source: https://docs.mirage.strukto.ai/typescript/agents/openai-agents-api Make a Mirage workspace the self-hosted environment of an agent on OpenAI's Agents API. OpenAI's [Agents API](https://developers.openai.com/api/docs/guides/agents-api/overview) runs the agent on OpenAI's servers. With a `self_hosted` environment, its shell commands, file reads and patches run in a Mirage workspace, under the workspace's profile and mount modes. No sandbox holds the files. The workspace connects through Codex's exec-server relay, set up on the [Codex page](/home/agents/codex#exec-server-forward). The Agents API is in beta. ## Install ```bash theme={null} npm install -g @struktoai/mirage-cli npm install openai ``` ## Workspace `/workspace`, where OpenAI's examples work, is scratch space in memory. `/redis` keeps what the agent saves there after the workspace closes, which needs a Redis server and the `redis` package next to the CLI: ```yaml workspace.yaml theme={null} mode: write mounts: /workspace: vfs: ram /redis: vfs: redis config: url: redis://localhost:6379/0 ``` ```bash theme={null} docker run -d -p 6379:6379 redis npm install -g redis mirage workspace create workspace.yaml --id demo printf 'customer,item,amount\nacme,widget,120\nglobex,gadget,75\nacme,gizmo,30\ninitech,widget,60\nglobex,widget,45\n' \ | mirage shell -w demo -c 'cat > /workspace/orders.csv' ``` ## Create a session ```ts theme={null} import OpenAI from 'openai' const client = new OpenAI() const session = await client.beta.agents.sessions.create({ agent: { model: 'gpt-6-luna' }, environment: { type: 'self_hosted', workspace_directory: '/workspace' }, }) console.log(session.environment.id, session.environment.remote_url) ``` ## Connect the workspace Hand the session's `environment.id` and `environment.remote_url`, with an [environment key](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#authentication), to [`codex exec-server forward`](/home/agents/codex#exec-server-forward) pointed at workspace `demo`. The agent's commands then run in the workspace, and what it writes lands in its mounts. ## Run a task Open the session's event stream, then send the task. The agent's reply streams back while its commands run in the workspace: ```ts theme={null} import { randomUUID } from 'node:crypto' const stream = await client.beta.agents.sessions.events.stream(session.id) await client.beta.agents.sessions.events.create(session.id, { events: [ { type: 'agent.session.input.message', input: [ { role: 'user', content: [{ type: 'input_text', text: 'Total the amount per customer in /workspace/orders.csv and save the totals as a markdown table to /redis/report.md.' }], }, ], }, ], 'Idempotency-Key': randomUUID(), }) for await (const event of stream) { if (event.type === 'agent.session.turn.output_text.delta') process.stdout.write(event.delta) else if (event.type === 'agent.session.turn.completed' || event.type === 'agent.session.turn.failed') break } ``` The report stays in Redis after the session ends: ```bash theme={null} mirage shell -w demo -c 'cat /redis/report.md' ``` ## Example [`examples/typescript/agents/openai_agents_api/redis_report.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/agents/openai_agents_api/redis_report.ts) runs the whole flow: it seeds `/workspace/orders.csv`, starts `mirage codex-exec` and `codex exec-server forward`, sends the task and prints the report. # OpenCode Source: https://docs.mirage.strukto.ai/typescript/agents/opencode Install native Mirage filesystem tools in OpenCode, with stale-write protection and no MCP server. [OpenCode](https://opencode.ai) can use Mirage through a native plugin, without MCP. The plugin replaces its filesystem and shell tools with Mirage-backed versions. ## Install Create a `mirage.yaml` that mounts your project at `/` inside Mirage using [Disk](/typescript/setup/disk): ```yaml mirage.yaml theme={null} mounts: /: vfs: disk config: root: /absolute/path/to/project ``` Add the plugin to `opencode.json`: ```json opencode.json theme={null} { "$schema": "https://opencode.ai/config.json", "plugin": ["@struktoai/mirage-opencode"] } ``` Run `opencode` normally. Mirage searches the project and parent directories for `mirage.yaml`, `workspace.yaml`, `.mirage/workspace.yaml`, and their `.yml` variants. To select another config or disable stale-write protection, pass plugin options: ```json opencode.json theme={null} { "plugin": [ [ "@struktoai/mirage-opencode", { "config": "config/agent-workspace.yaml", "staleWriteProtection": true } ] ] } ``` You can also set `MIRAGE_OPENCODE_CONFIG` or `MIRAGE_CONFIG` to the workspace config path. ## Stale writes Stale-write protection is enabled by default and isolated per OpenCode session. `read` records a content fingerprint; `write` and `edit` verify it immediately before changing the file. If the file changed, OpenCode must reread it before retrying. `bash` commands are not tracked because they can read or mutate arbitrary paths. Use the structured `read`, `write`, and `edit` tools when stale-write protection is required. ## Custom plugin Use `@struktoai/mirage-opencode/plugin` directly when the workspace is constructed in code rather than YAML: ```bash theme={null} bun add @struktoai/mirage-opencode @struktoai/mirage-node @opencode-ai/plugin ``` Create `.opencode/plugins/mirage.ts`: ```ts .opencode/plugins/mirage.ts theme={null} import { MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node' import { miragePlugin } from '@struktoai/mirage-opencode/plugin' const ws = new Workspace({ '/': new RAMVFS() }, { mode: MountMode.WRITE }) export default miragePlugin(ws) ``` Add the dependencies to `.opencode/package.json`: ```json .opencode/package.json theme={null} { "dependencies": { "@struktoai/mirage-node": "*", "@struktoai/mirage-opencode": "*", "@opencode-ai/plugin": "*" } } ``` ## Exports | Symbol | Purpose | | - | - | | `WsResolver` | A function that picks the workspace for a tool call from its OpenCode `ToolContext`. | | `WsLike` | A workspace, or a `WsResolver` that picks one per tool call. | | `MirageOpenCodeOptions` | Options for `mirageTools` and `miragePlugin`: `staleWriteProtection` (default `true`) and `sessionId`, the Mirage session every tool acts as. | | `mirageTools` | Returns OpenCode tool definitions for `read`, `write`, `edit`, `ls`, `bash`, `glob` and `grep`, backed by `ws`. | | `miragePlugin` | Returns a native OpenCode plugin whose tools are `mirageTools(ws, options)`. | ### Tool reference Tools return text except PDF and image reads, which return OpenCode attachments. | Tool | Input | Output | | - | - | - | | `read` | `{ filePath }` | UTF-8 text; a PDF/image attachment; or metadata for other binaries | | `write` | `{ filePath, content }` | Confirmation; creates parent directories | | `edit` | `{ filePath, oldString, newString, replaceAll? }` | Confirmation with replacement count | | `ls` | `{ path }` | Entries, with `/` after directories | | `bash` | `{ command }` | Merged stdout and stderr | | `glob` | `{ pattern, path? }` | `find -name` results | | `grep` | `{ pattern, path? }` | `grep -rn` results | `bash`, `glob`, and `grep` run through the Mirage shell across all mounts. ## Examples * [`examples/typescript/agents/opencode/ram_opencode.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/agents/opencode/ram_opencode.ts), an end-to-end runner that spawns OpenCode via `@opencode-ai/sdk`, loads a RAM-backed plugin that pre-writes `/hello.txt`, and asks `gpt-5.4-mini` to `cat` it. # Pi Coding Agent Source: https://docs.mirage.strukto.ai/typescript/agents/pi Run @earendil-works/pi-coding-agent with all 7 built-in tools wired to a Mirage workspace. [Pi Coding Agent](https://github.com/earendil-works/pi) is a TypeScript coding agent with seven built-in tools (`read`, `write`, `edit`, `bash`, `grep`, `find`, and `ls`). Mirage provides a native Pi inline extension that replaces their host-filesystem operations with a `Workspace`. > [!NOTE] > > This integration requires a [supported Node release](/typescript/install#quick-install). > Pi uses `process.cwd()`, agent directories, and other Node-only APIs. ## Install ```bash theme={null} pnpm add @struktoai/mirage-pi @struktoai/mirage-node @earendil-works/pi-coding-agent ``` ## Native Pi UI Pass the Mirage extension to Pi's regular entry point. Pi continues to own its CLI/TUI, model selection, sessions, themes, commands, and authentication. ```ts theme={null} import { MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node' import { main } from '@earendil-works/pi-coding-agent' import { mirageExtension } from '@struktoai/mirage-pi' const ws = new Workspace({ '/': new RAMVFS() }, { mode: MountMode.WRITE }) await main(process.argv.slice(2), { extensionFactories: [mirageExtension(ws)], }) ``` Running this script in a terminal opens Pi's existing UI. The extension also routes interactive `!` and `!!` shell commands through Mirage at the virtual working directory. For an isolated Mirage session, prevent Pi from loading `AGENTS.md` and `CLAUDE.md` files from the host project: ```bash theme={null} pnpm exec tsx agents/pi/ui_pi.ts --no-context-files ``` After asking Pi to create a file, you can verify that the native UI is using Mirage: ```text theme={null} !ls / !cat /hello.txt ``` Omit `--no-context-files` when you intentionally want Pi to combine host-project instructions with the mounted Mirage workspace. ## Stale-write protection Pi serializes its own mutations and its `edit` tool checks that the requested old text still exists in the current file. It does not, however, retain a file revision from an earlier agent read. The Mirage extension records a content fingerprint whenever Pi reads or greps a file. A later `edit` or full-file `write` fails with a `STALE_WRITE` [error](/home/access/errors#file-calls) if that content changed in the meantime. Reading the file again refreshes the fingerprint, so the agent can reconsider the new content and retry. The `edit` adapter also checks again immediately before writing. This protection is enabled by default. It observes the content returned by the mounted VFS, so a remote backend's cache and invalidation policy still determines when an external change becomes visible to Mirage. ## Exports | Symbol | Purpose | | - | - | | `mirageExtension` | Returns a Pi `InlineExtension` named `mirage` that registers all seven tools against `ws` and appends a mount-aware system prompt. | | `MirageExtensionOptions` | Options for `mirageExtension`: `cwd` (default `/`), `systemPrompt` (a string to append, or `false` for none), plus `staleWriteProtection` and `sessionId` from `MirageOperationsOptions`. | | `mirageOperations` | Returns the lower-level `{ read, write, edit, bash, grep, find, ls }` operation bundle backed by `ws`, for wiring Pi tools by hand. | | `MirageOperationsBundle` | The operations `mirageOperations` returns, one per Pi tool: `read`, `write`, `edit`, `bash`, `grep`, `find` and `ls`. | | `MirageOperationsOptions` | Options for `mirageOperations`: `staleWriteProtection` (default `true`) and `sessionId`, the Mirage session the operations act as. | | `MIRAGE_SYSTEM_PROMPT` | The default system prompt: how the Mirage filesystem differs from a plain one. | | `buildSystemPrompt` | Returns `MIRAGE_SYSTEM_PROMPT` followed by a description of the mounted paths and any extra instructions, ready to use as an agent's system prompt. | | `BuildSystemPromptOptions` | Options for `buildSystemPrompt`: which mounts to describe and what to append. | `mirageExtension` accepts: | Option | Default | Purpose | | - | - | - | | `cwd` | `'/'` | Working directory inside the mounted workspace. | | `staleWriteProtection` | `true` | Reject mutations when the file changed after Pi read it. | | `sessionId` | default session | The Mirage session every operation acts as, under that session's profile. | | `systemPrompt` | Mirage mount prompt | Extra instructions appended to Pi's prompt. Pass a string to replace the Mirage text, or `false` to disable it. | ## Examples * [`examples/typescript/agents/pi/ui_pi.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/agents/pi/ui_pi.ts), Mirage inside Pi's native CLI/TUI. * [`examples/typescript/agents/pi/ram_pi.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/agents/pi/ram_pi.ts), RAM-only sandbox. * [`examples/typescript/agents/pi/s3_pi.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/agents/pi/s3_pi.ts), Pi exploring an S3 bucket through Mirage. # Vercel AI SDK Source: https://docs.mirage.strukto.ai/typescript/agents/vercel Wire mirage tools into the Vercel AI SDK via @struktoai/mirage-vercel. The [Vercel AI SDK](https://sdk.vercel.ai) (`ai`) drives tool-calling agents around any provider in its registry. Mirage ships an AI SDK 7 tool factory that gives `generateText`, `streamText` and agent loops a session's seven tools. ## Install `@struktoai/mirage-vercel` is runtime-agnostic. Pair it with `@struktoai/mirage-node` for Node or `@struktoai/mirage-browser` for the browser. ```bash Node theme={null} pnpm add @struktoai/mirage-vercel @struktoai/mirage-node ai @ai-sdk/openai ``` ```bash Browser theme={null} pnpm add @struktoai/mirage-vercel @struktoai/mirage-browser ai @ai-sdk/openai ``` ## Usage ```ts theme={null} import { MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node' import { generateText, stepCountIs } from 'ai' import { openai } from '@ai-sdk/openai' import { buildSystemPrompt, mirageTools } from '@struktoai/mirage-vercel' const ws = new Workspace({ '/': new RAMVFS() }, { mode: MountMode.WRITE }) const { text } = await generateText({ model: openai('gpt-5.4-mini'), system: await buildSystemPrompt({ mountInfo: { '/': 'In-memory filesystem (read/write)' }, }), prompt: "Create /hello.txt with 'hi from mirage' and /data/numbers.csv with 3 sample rows. " + 'Then list and read every file back.', tools: mirageTools(ws), stopWhen: stepCountIs(20), }) console.log(text) ``` ## Exports | Symbol | Purpose | | - | - | | `MIRAGE_SYSTEM_PROMPT` | The default system prompt: how the Mirage filesystem differs from a plain one. | | `buildSystemPrompt` | Returns `MIRAGE_SYSTEM_PROMPT` followed by a description of the mounted paths and any extra instructions, ready to use as an agent's system prompt. | | `BuildSystemPromptOptions` | Options for `buildSystemPrompt`: which mounts to describe and what to append. | | `mirageTools` | Returns Mirage's tools (`shell`, `read`, `write`, `edit`, `ls`, `grep`, `glob`) as AI SDK tools to spread into `tools`, limited to what the session's profile allows. | `read` uses AI SDK 7's `toModelOutput`: text files come back as numbered lines, PDFs and supported images become file content parts, and other binary formats return a metadata note. ## Examples * [`examples/typescript/agents/vercel/ram_vercel.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/agents/vercel/ram_vercel.ts), RAM-only sandbox driven by `gpt-5.4-mini`. # Browser Quickstart Source: https://docs.mirage.strukto.ai/typescript/browser-quickstart Run a Mirage RAM workspace in a browser with Vite and @struktoai/mirage-browser. This runs Mirage in the browser with an in-memory filesystem and no credentials. ## Create the app This Vite starter needs Node 20.19+ on Node 20, or Node 22.12+: ```bash theme={null} npm create vite@7 mirage-browser -- --template vanilla-ts cd mirage-browser npm install @struktoai/mirage-browser ``` With pnpm, also add `@struktoai/mirage-core`: Vite's dev server finds Mirage's WebAssembly files through it. Replace `src/main.ts` with: ```ts src/main.ts theme={null} import { MountMode, RAMVFS, Workspace } from '@struktoai/mirage-browser' async function main(): Promise<void> { const ws = new Workspace({ '/data': new RAMVFS() }, { mode: MountMode.WRITE }) await ws.shell('echo "hello mirage" > /data/hello.txt') const result = await ws.shell('cat /data/hello.txt') document.querySelector<HTMLDivElement>('#app')!.textContent = result.stdoutText await ws.close() } void main() ``` Start the development server: ```bash theme={null} npm run dev ``` Open the URL Vite prints. The page displays `hello mirage`. Before choosing a production mount, review the [browser limitations](/typescript/limitations#browser) and browser support in the [VFS table](/home/setup/vfs). # airtable Source: https://docs.mirage.strukto.ai/typescript/cli/airtable Supported Airtable commands for querying and changing records and comments. Query Airtable bases, tables, records and comments, and create, update or delete records. Mirage defines this command tree over the [Airtable Web API](https://airtable.com/developers/web/api/introduction). ## Setup Create a token with the scopes in [Airtable setup](/home/setup/airtable). Reads need record and schema read scopes; writes and comments need their corresponding write scopes. ```typescript theme={null} import { AIRTABLE, Workspace } from '@struktoai/mirage-node' const config = { token: 'pat_...' } const ws = new Workspace({}) ws.registerCli('airtable', AIRTABLE, config) ``` No service mount is required. For YAML and multiple accounts, see the [CLI overview](/typescript/cli/index#register-a-cli). ## Supported commands Run `airtable <command> --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `airtable base list` | List the bases the token reaches as JSON | | `airtable base get` | Get one base and its tables (base.json) | | `airtable table get` | Get one table's fields and views (table.json) | | `airtable record list` | List records as JSONL (records.jsonl) | | `airtable record get` | Get one record as a JSONL line | | `airtable record create` | Create records from --fields or stdin | | `airtable record update` | Update records' cells (PATCH) from RECORD --fields or stdin | | `airtable record delete` | Delete records by RECORD or from stdin | | `airtable comment list` | List a record's comments, newest first | | `airtable comment add` | Comment on a record | ## Read and filter records ```bash theme={null} airtable base list airtable table get --base appRoadmapBase001 Features airtable record list --base appRoadmapBase001 --table tblFeatures000001 --formula "{Status} = 'Done'" airtable record get --base appRoadmapBase001 --table tblFeatures000001 recFeat0000000003 airtable comment list --base appRoadmapBase001 --table tblFeatures000001 recFeat0000000003 ``` `--base` takes a base ID. `--table` takes a table ID or name. Find these in API output or in the VFS's `name__id` directory names; record lines carry `record_id` explicitly. `--formula` and `--view` filter on the server. `base list` and `comment list` return JSON arrays. `base get` and `table get` return the same schema objects as the mount. Record commands return JSONL. ## Write records ```bash theme={null} airtable record create --base appRoadmapBase001 --table tblFeatures000001 --fields '{"Name":"Search"}' airtable record update --base appRoadmapBase001 --table tblFeatures000001 recFeat0000000003 --fields '{"Status":"Done"}' airtable record delete --base appRoadmapBase001 --table tblFeatures000001 recFeat0000000003 echo 'Ready to ship' | airtable comment add --base appRoadmapBase001 --table tblFeatures000001 recFeat0000000003 ``` For bulk writes, pipe record JSONL into `record create`, `record update` or `record delete` without the single-record arguments: ```bash theme={null} jq -c 'select(.fields.Status == "Todo") | .fields.Status = "Done"' /work/records.jsonl \ | airtable record update --base appRoadmapBase001 --table tblFeatures000001 ``` | Operation | Required fields in each stdin line | | - | - | | `record create` | `fields`; existing `record_id` and `created_time` are ignored | | `record update` | `record_id` and `fields`; omitted fields remain unchanged | | `record delete` | `record_id` | Each line may contain only `record_id`, `created_time` and `fields`. Mirage validates every line before the first request, drops computed fields from stdin writes, and sends batches of at most ten records. Inline `--fields` is sent as given. Use `--typecast` to allow Airtable's type conversion. ## VFS and limits The optional [Airtable VFS](/typescript/setup/airtable) exposes bases and tables as files. Record output uses the same JSONL shape, so mounted records can feed the CLI through stdin. The CLI uses its own account config and needs no Airtable mount. * `base_ids` restricts accessible bases, including writes; an excluded base is refused before a request. * Without `--max-records`, a list exceeding `max_read_records` fails with exit 1. An explicit `--max-records N` sets the requested cap. * Bad flags, malformed JSON and invalid stdin lines exit 2. API failures exit 1. A partial write prints the completed records and exits 1; it does not roll them back. * Requests use the config's per-base rate limit. Reads retry `429`, `502` and `503`; writes retry only `429`, to avoid repeating a write that may already have succeeded. The service is reached by IDs and the CLI's config. Input files such as `/work/records.jsonl` enter through shell stdin; they can live on any readable workspace mount. This is Mirage's Apache-2.0 command implementation for the Web API. No compatibility with a separate Airtable CLI is claimed; the API link documents the service rather than an upstream CLI implementation. See [compatibility and licenses](/home/setup/clis#compatibility-and-licenses). # Customize CLI Source: https://docs.mirage.strukto.ai/typescript/cli/custom Define a typed or script CLI with shared parsing, account config and VFS access. Define a custom CLI when an agent needs service operations with a stable command grammar. Use a typed `CLI` for parsed commands and generated help, or a script CLI when the program should parse its own arguments. Shell builtins and CLIs keep separate catalogs and dispatch. Both use `CommandSpec` for argument parsing. ## Define a typed command Each handler receives `(accessor, paths, texts, ctx)`, the shape a shell command takes: the installation's accessor, the operands, and the same `Context`. The install builds the accessor once from its validated config (`CLI.accessor`, default a `NOOPAccessor` holding the config at `accessor.config`) and the workspace closes it when the install goes. The example below shows the registration and parsing contract; the runnable [pager example](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/cli/pager.ts) adds a mutable incident service and shared cross-language coverage. The `@struktoai/mirage-core/...` type imports need `pnpm add @struktoai/mirage-core`. ```typescript theme={null} import { Argument, CLI, CLIHandler, CommandSpec, type Context, FlagView, IOResult, type PathSpec, Workspace, z, type CommandFnResult, } from '@struktoai/mirage-node' import type { NOOPAccessor } from '@struktoai/mirage-core/accessor/base' const PagerConfigSchema = z.strictObject({ account: z.enum(['engineering', 'support']) }) type PagerConfig = z.infer<typeof PagerConfigSchema> function acknowledge( accessor: NOOPAccessor, _paths: PathSpec[], texts: string[], ctx: Context, ): CommandFnResult { const { account } = accessor.config as PagerConfig const incidentId = texts[0] const by = new FlagView(ctx.flags, ctx.spec).asStr('by') return [ new TextEncoder().encode(`[${account}] acknowledged ${incidentId} by ${by}\n`), new IOResult(), ] } const PAGER = new CLI({ spec: new CommandSpec({ name: 'pager', subcommands: [new CommandSpec({ name: 'ack', arguments: [ new Argument('INCIDENT_ID'), new Argument('--by', { required: true }), ], })], }), handlers: { ack: new CLIHandler({ fn: acknowledge, write: true }) }, configModel: PagerConfigSchema, }) const ws = new Workspace({}) ws.registerCli('pager-eng', PAGER, { account: 'engineering' }) ws.registerCli('pager-support', PAGER, { account: 'support' }) ``` The same CLI can be installed for multiple accounts. Service IDs use textual operands; file operands use `type: 'path'`. Read flags through `new FlagView(ctx.flags, ctx.spec)` so a read of an undeclared option fails rather than looking like an omitted flag. ## Choose the command shape | Node | Declares | Handler input | | - | - | - | | Leaf | `CommandSpec.arguments`, a `CLIHandler` binding | Paths and text as arguments, parsed flags on `ctx` | | Group | `subcommands`, optional inherited options | Dispatches to a leaf | | Script CLI | `CLI.script`, optional runtime | Raw argv, stdin and environment | A typed node is a leaf or a group. Names and aliases are single words; child names and aliases share one namespace. Options cannot collide across ancestors and descendants. Construction validates the tree and compiles the grammar; do not repeat parser validation in every handler. `CommandSpec.arguments` holds options and positional arguments: a dashed name such as `--by` declares an option; a bare name declares a positional. `CLI.handlers` maps canonical paths below the root to `CLIHandler` bindings, such as `"ack"`, `"incident ack"`, or `""` for a single-command program. Declare `configModel` on the account `CLI`. Registration validates each installation, and the default `NOOPAccessor` holds that account's settings at `accessor.config`. Without a config model, a typed CLI accepts no config and `accessor.config` is `null`. Mark mutating `CLIHandler` bindings `write: true`. This classifies the command for policy and cache invalidation; it does not grant permission or perform the mutation. Policy reads it as `CommandContext.write`, so one `preCommand` method can refuse every writing verb. Descriptions, options and operands supply `--help` and `man` at every level. ## Register the program Installing a CLI directly is the shortest path: ```typescript theme={null} ws.registerCli('pager-eng', PAGER, { account: 'engineering' }) ``` The installed name is the dispatch key and does not have to equal the spec's root name. This is what makes one tree usable for several accounts. To resolve a bare name from workspace YAML, register the CLI before loading the workspace: ```typescript theme={null} import { registerCliSpec } from '@struktoai/mirage-node' registerCliSpec(PAGER) ``` ```yaml theme={null} clis: pager-eng: cli: pager config: account: engineering ``` The Node config loader also accepts `./file.mjs:ATTR` and package references such as `my-clis/specs:PAGER`. Relative files resolve next to the YAML file. A `.js` file follows its nearest `package.json` `type`; `.mjs` is unambiguous. A `.ts` file uses Node's type stripping, not compilation, so syntax requiring transformation must be built first. Registered names and builtins win over direct references. A name collision fails rather than silently replacing another program. TypeScript has no Python entry-point discovery equivalent; use a package reference or call `registerCliSpec` from the host. Registration and installation are host-side lifecycle operations. There is no shell `install` or `uninstall` command, so an agent can use a CLI it was given but cannot remove it. A deployment that must pin the head word should enforce that with policy; shell functions can otherwise shadow it like they do in bash. ## Serve a CLI on a mount Registered on a mount, a typed CLI serves its verbs there as a command tree. Its leaves get the mount's accessor, so the tree declares no `configModel`, `accessor`, `script` or `runtime`: ```typescript theme={null} import { MountMode, RAMVFS } from '@struktoai/mirage-node' import type { RAMAccessor } from '@struktoai/mirage-core/accessor/ram' function tag(accessor: RAMAccessor, paths: PathSpec[], texts: string[]): CommandFnResult { const [note] = paths if (note === undefined) return [null, new IOResult({ exitCode: 1 })] accessor.store.files.set(`/${note.vfsPath}`, new TextEncoder().encode(texts.join(' '))) return [null, new IOResult()] } const NOTES = new CLI({ spec: new CommandSpec({ name: 'notes', subcommands: [new CommandSpec({ name: 'tag', arguments: [new Argument('note', { type: 'path' }), new Argument('tags', { nargs: '+' })], })], }), handlers: { tag: new CLIHandler({ fn: tag, write: true }) }, }) const ws = new Workspace({ '/notes/': new RAMVFS() }, { mode: MountMode.WRITE }) ws.mount('/notes/').registerCommands([NOTES]) ``` `notes tag /notes/a.md draft` walks, helps and refuses like an installed CLI's line, and runs on the working directory's mount when it serves `notes`. Otherwise a writing leaf selects the only writable matching mount; several writable matches produce an ambiguity error. Use `cd` to select the target. Read-only leaves keep the first matching mount, with a debug log when several match. Help remains available without selecting a write destination. A VFS hands the same tree to every mount of it through its `commands` option. Its leaves reach the backend past the dispatcher. Mutating leaves must declare `write: true`, run only when the mount is writable, and clear cached mount listings on return. ## Use workspace files Build the service client in the CLI's accessor (`CLI.accessor`), from the install's config, so one install keeps one client for every call; the workspace closes it when the install goes. A CLI should not find a matching VFS to obtain credentials or a backend accessor. Reuse core service functions and accessor classes between CLI and VFS implementations where their behavior is the same. For file arguments such as uploads or attachments, use `ctx`: | Field | Purpose | | - | - | | `vfs` | The session's files, the same API as `session.vfs`: `read`, `write`, `stat`, `readdir`, `symlink`, `readlink` and the rest, with workspace policy and mount modes applied | | `session` | Live, gated session reads and writes; `ctx.env` is the frozen invocation snapshot | `vfs.stat(path, undefined, { nofollow: true })` reports a link itself. `vfs.mountOf(path)` names the mount serving a path, `vfs.isMount(path)` says whether a path is a mount root, and `vfs.submounts(path)` lists the mounts below a folder. A mount the session hides is listed as the nearest folder above it that the session sees, so a CLI that removes a folder can refuse without learning the hidden name. A CLI that prints paths from its own data, as git prints its index, hands its output over as rows instead of bytes: each row names the path it shows, and the command prints none of it itself. The workspace drops the rows the session hides, then calls the renderer with the rest, so no line, count, total or column width stands for a hidden path: ```ts theme={null} import { IOResult, PathSpec, type CommandFnResult, type Context, } from '@struktoai/mirage-node' import type { NOOPAccessor } from '@struktoai/mirage-core/accessor/base' import type { Rows } from '@struktoai/mirage-core/io/types' interface Entry { readonly path: PathSpec readonly size: number } function tracked( _accessor: NOOPAccessor, _paths: PathSpec[], _texts: string[], _ctx: Context, ): CommandFnResult { // The CLI's own record of the files it tracks. const kept: [string, number][] = [['/data/a.txt', 1], ['/data/b.txt', 3]] const rows: Rows<Entry> = { items: kept.map(([path, size]) => ({ path: PathSpec.fromStrPath(path), size })), render: (shown) => { const lines = shown.map((entry) => `${entry.path.virtual} ${String(entry.size)}\n`) lines.push(`${String(shown.length)} files\n`) return Promise.resolve(new TextEncoder().encode(lines.join(''))) }, } return [null, new IOResult({ rows })] } ``` The renderer runs inside the command's timeout. A handler hands over rows or stdout, never both. Declare file options and operands with `type: 'path'`; preserve the resulting `PathSpec` values when calling `ctx.vfs`. Use `PathSpec.fromStrPath(value, undefined, ctx.cwd)` for a path string from config, and derive paths with `join` and `parent`. Do not convert them to plain strings before filesystem access. Direct handler callers may leave `ctx.vfs` unset; a handler requiring files must refuse when it is absent. Account CLI writes, including failed writes that may have reached the service, expire mounted caches. Config-free filesystem CLIs rely on the dispatcher's per-path invalidation. A script marked as a write also expires caches because its config and service access are opaque. An install's accessor decides which mounts that is: implement `reaches(peer)` to answer false for a mount's accessor its writes cannot change. An accessor without it reaches every mount. ## Snapshots and credentials A named typed CLI is saved by spec name. A Zod object `configModel` doubles as the redaction schema; mark string credentials with `secretStr()`. Loading a snapshot with redacted fields must provide fresh install config through `clis`; Mirage refuses to restore redacted credentials as if they were usable values. ```typescript theme={null} import { secretStr, z } from '@struktoai/mirage-node' const ConfigSchema = z.object({ token: secretStr(), account: z.string() }) ``` A normalizer function is also accepted as `configModel`, but its result is opaque to snapshot redaction and is serialized as-is. Prefer a Zod object for credential-bearing config. The loading process must also make the spec name resolvable, or pass `[cli, config]` as that install's `clis` override. `Workspace.copy()` carries the live CLI and config together, including a tree installed directly in code. A script CLI is different: the script source is embedded in the snapshot and its opaque config is serialized verbatim because there is no config model to identify secrets. Keep credentials in the environment, or provide fresh script config through `clis` when loading. ## Script CLIs Use `script:` when the program should own its grammar or should have no Mirage imports: ```yaml theme={null} clis: pager: script: ./cli/pager.py runtime: pyodide config: width: 80 ``` The file is embedded at load. Words after the head arrive as argv, piped input arrives on stdin, and config arrives as JSON in `MIRAGE_CLI_CONFIG`. The program's stdout, stderr, and exit status become the shell result. A script CLI cannot declare `configModel`, subcommands, or function handlers; it parses and documents its own options, including `--help`. Slot 0 is the installed name on pyodide, monty, and quickjs, so two installs can identify themselves and user-facing errors can name the invoked program. The Node-only local runtime runs CPython with `-c`, which owns `sys.argv[0]`; arguments still begin at index 1. A YAML script declares no Mirage grammar, so every option reaches the program unchanged. A script CLI constructed in code may supply a `CommandSpec` to opt into Mirage parsing and generated help. Runtime argument spellings differ: | Runtime | Arguments | Standard input | | - | - | - | | pyodide | `sys.argv` | `sys.stdin` | | monty | `argv` global | `stdin` global | | quickjs | `scriptArgs` | `std.in` | The sandboxed runtimes provide files plus compute, not arbitrary networking or Node builtins. The Node-only `local` runtime selects the host interpreter when that broader authority is intentional. ## Authoring reference The public constructors document exact types and defaults: [`CLI` and `CLIHandler`](https://github.com/strukto-ai/mirage/blob/main/typescript/packages/core/src/commands/cli/types.ts), and [`CommandSpec` and `Argument`](https://github.com/strukto-ai/mirage/blob/main/typescript/packages/core/src/commands/spec/types.ts). ### `CLI` and `CLIHandler` | Field | Authoring meaning | | - | - | | `CLI.spec` | Root `CommandSpec` describing the program's grammar. | | `CLI.handlers` | Canonical leaf paths mapped to `CLIHandler` bindings. | | `CLI.configModel` | Zod schema or normalizer for per-install account validation. | | `CLI.accessor` | Builds the install's accessor from its validated config, once per install; closed when the install goes. Default `NOOPAccessor`. | | `CLI.script`, `CLI.runtime` | Embedded script and optional runtime; used instead of typed handlers. | | `CLIHandler.fn` | Leaf handler, called as `fn(accessor, paths, texts, ctx)`. | | `CLIHandler.write`, `CLIHandler.limit` | Mutation classification and optional execution-limit category. | ### `CommandSpec` | Field | Authoring meaning | | - | - | | `name`, `aliases` | Command word and alternate subcommand words. | | `subcommands` | Child nodes for a group. | | `arguments` | Options and positional arguments; group options are inherited by leaves. | | `description`, `epilog` | Help text and trailing help text. | | `usageStyle` | Root help and refusal dialect: argparse, Git, clap or Cobra. Cobra keeps standard help and option errors; handlers own missing positional refusals. | | `allowAbbrev` | Whether unique long-option prefixes are accepted. | ### `Argument` | Field | Authoring meaning | | - | - | | Names | One positional name, or one or more dashed option spellings. | | `type` | `str` (default), `int`, `float`, or virtual `path`. | | `action` | `store` (default), `store_true`, `count`, `append`, or `extend`. | | `nargs` | One value by default; `?` for optional or an integer for fixed arity. Positionals also accept `*`, `+`, or `REMAINDER`. | | `choices` | Allowed values, validated by the parser. | | `required` | Require an option; positional arity comes from `nargs`. | | `default`, `env` | Option fallbacks; an environment value counts as supplied. | | `help`, `metavar` | Help description and displayed value name. | This follows argparse's naming conventions and supports a subset of its features. Positional defaults and variadic options are unsupported; `append` collects single option values, while `extend` flattens fixed groups. ### Handler arguments and `Context` | Argument or field | Handler view | | - | - | | `accessor` | The install's accessor. The default `NOOPAccessor` holds the validated config at `accessor.config` (`null` without a config model). | | `paths` | Cwd-resolved path operands. | | `texts` | Textual and numeric operands in declaration order. | | `ctx.argv` | Verbatim words after the installed head word, including subcommands. | | `ctx.flags` | Group and leaf flags keyed by normalized property name. | | `ctx.spec` | The resolved leaf grammar. | | `ctx.stdin` | Piped bytes or an async byte source, or `null`. | | `ctx.cwd` | The session's working directory. | | `ctx.env` | Frozen environment snapshot for this invocation. | | `ctx.vfs`, `ctx.session` | The session's files and live session, for verbs that need them; absent outside a workspace. | ## Verify a custom CLI Check help, successful execution, a refusal and isolation between two account installations. Exercise VFS access with path and mount policy, and verify snapshot restoration with credentials supplied again. Keep service request construction and internal edge cases in unit tests; put observable shell results in shared integration cases when both hosts implement the program. The shared grammar also serves shell commands. Prefer its existing argparse and POSIX concepts; keep a program-specific rule in its handler, or use a script when the whole program needs to own parsing. # discord Source: https://docs.mirage.strukto.ai/typescript/cli/discord Supported Discord commands for messages, threads, polls and guild information. Read and send Discord messages, edit or delete messages, add reactions, create threads and polls, and inspect guilds. The action names follow [OpenClaw](https://github.com/openclaw/openclaw); `members` and `server-info` are Mirage extensions. ## Setup Configure a bot token and its permissions with [Discord setup](/home/setup/discord). ```typescript theme={null} import { DISCORD, Workspace } from '@struktoai/mirage-node' const config = { token: 'bot-token' } const ws = new Workspace({}) ws.registerCli('discord', DISCORD, config) ``` No service mount is required. For YAML and multiple accounts, see the [CLI overview](/typescript/cli/index#register-a-cli). ## Supported commands Run `discord <command> --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `discord send` | Send a message to a channel | | `discord read` | Read the most recent messages of a channel | | `discord edit` | Edit a message the bot authored | | `discord delete` | Delete a message | | `discord react` | Add an emoji reaction to a message | | `discord reactions` | List the reactions on a message | | `discord pin-message` | Pin a message to its channel | | `discord unpin-message` | Remove a pin from a message | | `discord list-pins` | List a channel's pinned messages | | `discord search` | Search a guild's messages by content | | `discord thread-create` | Create a thread, standalone or from a message | | `discord poll` | Post a poll message to a channel | | `discord members` | List a guild's members, optionally filtered | | `discord server-info` | Fetch a guild's metadata | ## Messages ```bash theme={null} discord read --channel 1256522563555819574 --limit 20 discord send --channel 1256522563555819574 --text "Release is ready" discord send --channel 1256522563555819574 --text "A reply" --reply-to 1489887688978075769 discord send --channel 1256522563555819574 --text "Spoken reply" --file /data/reply.wav discord edit --channel 1256522563555819574 --message 1489887688978075769 --text "Updated" discord delete --channel 1256522563555819574 --message 1489887688978075769 ``` `edit` works only on messages authored by the bot. Channel, guild and message arguments are Discord snowflake IDs; `send --file` reads a workspace path and attaches it. ## Threads, polls and search ```bash theme={null} discord react --channel 1256522563555819574 --message 1489887688978075769 --emoji "👍" discord reactions --channel 1256522563555819574 --message 1293847561029384756 discord pin-message --channel 1256522563555819574 --message 1293847561029384756 discord list-pins --channel 1256522563555819574 discord unpin-message --channel 1256522563555819574 --message 1293847561029384756 discord thread-create --channel 1256522563555819574 --message 1489887688978075769 --name "Release review" discord poll --channel 1256522563555819574 --question "Ship today?" --answer Yes --answer Tomorrow --duration 24 discord server-info --guild 1256522563555819574 discord members --guild 1256522563555819574 --query alice discord search --guild 1256522563555819574 --query deploy --channel 1256522563555819574 ``` Omit `--message` on `thread-create` to create a standalone thread. Repeat `--answer` for each poll option; `--multiselect` allows multiple choices. Responses are JSON. ## VFS and limits The optional [Discord VFS](/typescript/setup/discord) exposes the guild's channels and messages as files. Use the IDs in its `name__id` path segments with the CLI. Registration remains independent of the mount, and command policy controls service writes. Only the listed actions are implemented. OpenClaw's source uses the [MIT license](https://github.com/openclaw/openclaw/blob/main/LICENSE). Mirage's command implementation is Apache-2.0; see [compatibility and licenses](/home/setup/clis#compatibility-and-licenses). # gh Source: https://docs.mirage.strukto.ai/typescript/cli/gh Supported GitHub commands for repositories, issues, pull requests, Actions and API calls. Work with GitHub repositories, issues, pull requests, releases and Actions, or call REST and GraphQL directly. Mirage implements the supported subset below of the [GitHub CLI (`gh`)](https://github.com/cli/cli), with workspace files and configured account credentials. ## Setup Use [GitHub setup](/home/setup/github) for token permissions. No GitHub mount or local checkout is required. ```typescript theme={null} import { GH, Workspace } from '@struktoai/mirage-node' const ws = new Workspace({}) ws.registerCli('gh', GH, { token: 'ghp_...', repo: 'acme/tools' }) ``` `repo` is the default repository and `branch` the current branch, as a checkout would give them to a host `gh`: `branch` fills the API's `{branch}` placeholder, names the pull request a `pr` command acts on when given none, and is the head `pr create` opens from. `base_url` (`baseUrl` in TypeScript) selects an API host. An Enterprise REST base ending in `/api/v3` uses `/api/graphql` for GraphQL; other bases use `/graphql` beneath that base. For YAML and multiple accounts, see [registration](/typescript/cli/index#register-a-cli). ## Supported commands Run `gh <command> --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `gh auth status` | Check the configured token | | `gh auth token` | Token display is unavailable in Mirage | | `gh help` | Help about any command | | `gh version` | Show the Mirage GitHub CLI implementation version. Aliases: `--version`. | | `gh api` | Make an authenticated GitHub API request | | `gh issue list` | List issues. Aliases: `ls`. | | `gh issue view` | View an issue | | `gh issue create` | Create an issue. Aliases: `new`. | | `gh issue edit` | Edit an issue | | `gh issue close` | Close an issue | | `gh issue reopen` | Reopen an issue | | `gh issue comment` | Add a comment to an issue | | `gh issue delete` | Delete issue | | `gh issue lock` | Lock issue conversation | | `gh issue pin` | Pin an issue to a repository | | `gh issue status` | Show status of relevant issues | | `gh issue transfer` | Transfer issue to another repository | | `gh issue unlock` | Unlock issue conversation | | `gh issue unpin` | Unpin an issue from a repository | | `gh pr list` | List pull requests. Aliases: `ls`. | | `gh pr view` | View a pull request | | `gh pr create` | Create a pull request. Aliases: `new`. | | `gh pr edit` | Edit a pull request | | `gh pr merge` | Merge a pull request | | `gh pr close` | Close a pull request | | `gh pr reopen` | Reopen a pull request | | `gh pr comment` | Add a comment to a pull request | | `gh pr diff` | View changes in a pull request | | `gh pr checks` | Show CI checks for a pull request | | `gh pr lock` | Lock pull request conversation | | `gh pr ready` | Mark a pull request as ready for review | | `gh pr revert` | Revert a pull request | | `gh pr review` | Add a review to a pull request | | `gh pr status` | Show status of relevant pull requests | | `gh pr unlock` | Unlock pull request conversation | | `gh pr update-branch` | Update a pull request branch with latest changes of the base branch | | `gh repo list` | List repositories. Aliases: `ls`. | | `gh repo clone` | Clone a repository locally | | `gh repo view` | View a repository | | `gh repo create` | Create a repository | | `gh repo fork` | Create a fork of a repository | | `gh repo rename` | Rename a repository | | `gh repo edit` | Edit repository settings | | `gh repo delete` | Delete a repository | | `gh repo archive` | Archive a GitHub repository | | `gh repo sync` | Sync destination repository from source repository | | `gh repo unarchive` | Unarchive a GitHub repository | | `gh repo autolink create` | Create a new autolink reference for a repository. Aliases: `new`. | | `gh repo autolink delete` | Delete an autolink reference for a repository | | `gh repo autolink list` | Gets all autolink references that are configured for a repository. Aliases: `ls`. | | `gh repo autolink view` | View an autolink reference for a repository | | `gh repo deploy-key add` | Add a deploy key to a GitHub repository | | `gh repo deploy-key delete` | Delete a deploy key from a GitHub repository | | `gh repo deploy-key list` | List deploy keys in a GitHub repository. Aliases: `ls`. | | `gh repo gitignore list` | List available repository gitignore templates. Aliases: `ls`. | | `gh repo gitignore view` | View an available repository `.gitignore` template | | `gh repo license list` | List common repository licenses. Aliases: `ls`. | | `gh repo license view` | View a specific repository license by license key or SPDX ID | | `gh release list` | List releases. Aliases: `ls`. | | `gh release view` | View a release | | `gh release create` | Create a release | | `gh release delete` | Delete a release | | `gh release delete-asset` | Delete an asset from a release | | `gh release edit` | Edit a release | | `gh run list` | List workflow runs. Aliases: `ls`. | | `gh run view` | View a workflow run | | `gh run rerun` | Rerun a workflow run | | `gh run cancel` | Cancel a workflow run | | `gh run delete` | Delete a workflow run | | `gh workflow list` | List workflows. Aliases: `ls`. | | `gh workflow view` | View a workflow | | `gh workflow run` | Run a workflow | | `gh workflow disable` | Disable a workflow, preventing it from running or showing up when listing workflows | | `gh workflow enable` | Enable a workflow, allowing it to be run and show up when listing workflows | | `gh search issues` | Search for issues | | `gh search prs` | Search for prs | | `gh search repos` | Search for repos | | `gh search code` | Search for code | | `gh search commits` | Search for commits | | `gh cache delete` | Delete GitHub Actions caches | | `gh cache list` | List GitHub Actions caches. Aliases: `ls`. | | `gh gist create` | Create a new GitHub gist with given contents. Aliases: `new`. | | `gh gist delete` | Delete a GitHub gist | | `gh gist edit` | Edit one of your gists | | `gh gist list` | List gists from your user account. Aliases: `ls`. | | `gh gist rename` | Rename a file in the given gist ID / URL | | `gh gist view` | View the given gist or select from recent gists | | `gh gist clone` | Clone a GitHub gist locally | | `gh label clone` | Clones labels from a source repository to a destination repository on GitHub | | `gh label create` | Create a new label on GitHub, or update an existing one with `--force` | | `gh label delete` | Delete a label from a repository | | `gh label edit` | Update a label on GitHub | | `gh label list` | Display labels in a GitHub repository. Aliases: `ls`. | | `gh org list` | List organizations for the authenticated user. Aliases: `ls`. | | `gh ruleset check` | View information about GitHub rules that apply to a given branch | | `gh ruleset list` | List GitHub rulesets for a repository or organization. Aliases: `ls`. | | `gh ruleset view` | View information about a GitHub ruleset | | `gh secret delete` | Delete a secret on one of the following levels:. Aliases: `remove`. | | `gh secret list` | List secrets on one of the following levels:. Aliases: `ls`. | | `gh variable delete` | Delete a variable on one of the following levels:. Aliases: `remove`. | | `gh variable get` | Get a variable on one of the following levels: | | `gh variable list` | List variables on one of the following levels:. Aliases: `ls`. | | `gh variable set` | Set a value for a variable on one of the following levels: | ## Issues, pull requests and Actions ```bash theme={null} gh auth status gh issue list --state open --label bug --limit 20 gh issue view 42 --json number,title,labels,url --jq '.url' gh pr view 17 --json files,commits,reviews --jq '.files[].path' gh pr checks 17 --json name,bucket,state gh run list --workflow ci.yml --json databaseId,status,conclusion gh run view 123456 --log-failed gh workflow view ci.yml --yaml --ref release ``` Use `-R/--repo [HOST/]OWNER/REPO` where supported to override the configured repository. Typed `--jq` requires `--json`. List commands paginate up to `-L/--limit`. Typed `--json` fields follow upstream's for each command, except `jobs` on `run view`; use `gh api` for additional data. ```bash theme={null} gh issue create --title 'Broken build' --body-file /work/issue.md --label bug gh issue comment 42 --body-file - < /work/comment.md gh issue edit 42 --add-label confirmed --remove-assignee octocat gh pr create --title 'Fix build' --head fix-build --base main --body-file /work/pr.md gh pr merge 17 --squash --subject 'Fix build' gh release create v1.2.0 --title '1.2.0' --notes-file /work/notes.md gh workflow run ci.yml --ref main -f mode=full gh run rerun 123456 --failed ``` Commands are noninteractive: supply titles, bodies, branches and confirmation flags explicitly. Body/notes files and `--input` files use the workspace VFS; `-` selects stdin. Workflow YAML is read at the selected ref. Run logs are available only after completion; `--log-failed` selects failed steps. ## Repositories ```bash theme={null} gh repo view --json nameWithOwner,defaultBranchRef,url gh repo list acme --limit 50 gh repo clone acme/tools /work/tools -- --branch dev gh repo create acme/tools-next --private --add-readme gh repo fork acme/tools --fork-name tools-patched gh repo rename tools-v2 -R acme/tools gh repo edit acme/tools --enable-wiki=false --add-topic cli,agents gh repo edit acme/tools --visibility private --accept-visibility-change-consequences gh repo delete acme/tools-old --yes ``` `repo clone` uses Mirage's Git implementation and needs a writable destination mount. The token travels in the HTTP authorization header, not in the command line, output or `.git/config`, and only to the configured GitHub origin: `https://github.com` for GitHub's own API (`base_url` unset or `https://api.github.com`), else the scheme, host and port `base_url` names. Git clones any other URL on the line without it. Fork clones do not add an `upstream` remote. `repo rename` takes the **new name** as its operand; `-R` selects the repository to rename. `repo edit` changes only the named settings, and bare boolean settings can be disabled with `=false`. Deletion needs both a repository name and `--yes`. Repository URLs and `[HOST/]OWNER/REPO` are accepted, but the host must match the configured API host; use a separate install for another host. ## REST and GraphQL API ```bash theme={null} gh api /user gh api 'repos/{owner}/{repo}/issues' -f title='Bug' -f body='Steps to reproduce' gh api repos/acme/tools/issues -F 'labels[]=bug' -F 'metadata[agent]=worker' gh api repos/acme/tools/issues --input /work/issue.json --silent gh api 'repos/acme/tools/issues?per_page=50' --paginate --slurp gh api repos/acme/tools/pulls/17 -H 'Accept: application/vnd.github.v3.diff' gh api graphql -f query='{viewer{login}}' ``` | Option or input | Behavior | | - | - | | No fields | GET by default; no request body | | `-f` / `--raw-field` | String field; supplying fields selects POST unless `-X` overrides it | | `-F` / `--field` | Typed booleans, null and integers; `@FILE` reads a workspace file and `@-` reads stdin | | `-X` / `--method` | Explicit method; GET fields become query parameters, other methods use JSON | | `key[nested]`, `key[]` | Nested objects and arrays | | `--input FILE` | Request body from a file or `-`, sent as raw bytes; additional fields move to the query string | | `-H` / `--header` | Add or replace a header | | `--paginate` | Follow REST Link headers, joining array pages, or a GraphQL query's `endCursor` | | `--slurp` | Wrap pages in an array; cannot be combined with `--jq` | | `-i` / `--include` | Print status and headers for each response, including failures | | `--silent` | Suppress the response body; `--include` still prints headers | | `-q` / `--jq` | Filter API output in process; unlike typed commands, needs no `--json` | Quote endpoints containing `{owner}`, `{repo}` or `{branch}`. These expand from config in endpoints and `-F` values, but not `-f` values. Other brace pairs remain unchanged. A leading endpoint slash is optional. Unfiltered output preserves the server's response bytes. Typed `--json` output is compact JSON followed by a newline. `--jq` prints strings raw, null as an empty line, and objects/arrays as compact JSON. A jq error exits 1 and can leave earlier output on stdout. Connection failures and HTTP 500 responses are not retried. ## VFS and limits A [GitHub VFS](/typescript/setup/github) can expose the same remote repository as files, independently of the CLI. The configured `repo` and `branch` supply context that a host `gh` would infer from a checkout. CLI service writes invalidate mounted caches; read API methods leave them intact. | Boundary | Mirage behavior | | - | - | | Authentication | `auth status` checks the token; `auth token` refuses to print it. No login/logout flow. | | Interactive tools | No editor, browser, extension manager, codespace or host-checkout workflow. | | Pull-request creation | Requires a title and a body or body file. `--head` defaults to `branch` and `--base` to the repository's default branch. | | Forks | `--clone` is refused; `--remote` without a repository is refused. | | Repository operations | No `repo set-default`. `repo sync` acts on a repository on GitHub, never a local checkout. | | Release assets and live runs | `release upload`, `release download`, `run watch` and `run download` are absent. | | Raw API | REST pagination only; no verbose, cache, hostname, preview or template flags. | | Help topics | `environment` and `exit-codes` are supported, alongside command help. | | HTTP display | `--include` prints HTTP/1.1 rather than upstream's HTTP/2.0 display. | | jq compatibility | Uses jq rather than gojq: builtin error wording and floating-point edge cases can differ. Numbers above 2^53 can lose precision; NaN, infinities and negative zero follow jq's values. | The original GitHub CLI uses the [MIT license](https://github.com/cli/cli/blob/trunk/LICENSE). Mirage's command implementation is Apache-2.0; the listed subset and differences define its compatibility scope. See [compatibility and licenses](/home/setup/clis#compatibility-and-licenses). # git Source: https://docs.mirage.strukto.ai/typescript/cli/git Supported Git commands for repositories and working trees on Mirage mounts. Inspect and modify repositories using a subset of the [Git command line](https://git-scm.com/docs/git). Mirage routes repository files through the workspace dispatcher, so the same commands can operate on RAM, disk or another backend with the required filesystem operations. The Python implementation uses [Dulwich](https://github.com/jelmer/dulwich); the TypeScript implementation uses [isomorphic-git](https://github.com/isomorphic-git/isomorphic-git). Mirage supplies the command grammar, output and VFS integration on both hosts. The compatibility target is native Git's supported behavior, with the [differences below](#limits-and-intentional-differences). These libraries are implementation dependencies; their own command interfaces do not define Mirage's supported commands. ## Setup `git` has no account config. It needs an existing repository to inspect, or a writable mount on which to initialize or clone one. ```typescript theme={null} import { GIT, MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node' const ws = new Workspace({ '/repo': new RAMVFS() }, { mode: MountMode.WRITE }) ws.registerCli('git', GIT) await ws.shell('git -C /repo init -b main') ``` For YAML registration, see the [CLI overview](/typescript/cli/index#register-a-cli). ## Supported commands Run `git <command> --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `git reflog` | Show reference history | | `git for-each-ref` | List references with a format | | `git cat-file` | Provide contents or details of repository objects | | `git hash-object` | Compute object ID and optionally create an object from a file | | `git grep` | Search tracked files in the working tree, index or named trees | | `git ls-tree` | List the contents of a tree object | | `git ls-files` | Show files in the index | | `git fetch` | Download objects and refs from another repository | | `git clone` | Clone a repository into a new directory | | `git help` | Show command help | | `git init` | Create an empty Git repository or reinitialize an existing one | | `git fsck` | Verify object hashes and connectivity | | `git stash list` | List stashed changes | | `git stash show` | Show stashed changes | | `git version` | Show the Mirage Git implementation version. Aliases: `--version`, `-v`. | | `git remote` | List remotes and inspect their URLs | | `git config` | Read repository configuration | | `git merge-base` | Find best common ancestors of commits | | `git show-ref` | List references | | `git symbolic-ref` | Read, change or delete a symbolic ref | | `git shortlog` | Summarize commit history | | `git rev-parse` | Resolve revisions | | `git rev-list` | List reachable commits | | `git diff-tree` | Compare a commit with its parent, or two trees | | `git diff-files` | Compare the index with the working tree | | `git diff-index` | Compare a tree with the working tree or index | | `git check-ref-format` | Check that a ref name is well formed | | `git ls-remote` | List the refs another repository publishes | | `git check-ignore` | Show which paths the ignore rules cover | | `git describe` | Name a commit after the nearest tag | | `git status` | Show the working tree status | | `git log` | Show commit logs | | `git show` | Show a commit and its diff | | `git diff` | Show changes between commits | | `git branch` | List, create or delete branches | | `git add` | Stage working tree content | | `git reset` | Unstage, putting the index back to HEAD | | `git commit` | Record the index as a new commit | | `git checkout` | Switch branches | | `git switch` | Switch branches | | `git restore` | Restore working tree files | | `git rm` | Remove files from the working tree and the index | | `git mv` | Move or rename a file, a directory, or a symlink | | `git tag` | Create, list or delete a tag | ## Create and inspect a repository ```bash theme={null} git -C /repo init -b main echo hello > /repo/hello.txt git -C /repo add hello.txt git -C /repo commit -m 'Initial commit' git -C /repo status --short git -C /repo log --oneline -5 git -C /repo show HEAD git -C /repo diff git -C /repo diff --cached git -C /repo grep -n hello git -C /repo ls-files --stage git -C /repo fsck ``` `-C` selects a workspace directory and defaults to the session's working directory. Repository discovery walks upward, so commands also work from subdirectories. Loose objects, packs, refs, the index and working files all use the same VFS operations as the shell. `init` supports `-b`, `--bare` and reinitialization. The default branch is `master` unless `-b` chooses another. `commit` requires `-m` and records `mirage <mirage@localhost>` unless `--author 'Name <email>'` overrides it. `fsck` checks the object database without modifying it. ## Stage and change files Continue from the initial commit above. Record a second version before using `HEAD~1` to restore the original: ```bash theme={null} echo updated > /repo/hello.txt git -C /repo commit -am 'Update greeting' git -C /repo add -A git -C /repo reset -- hello.txt git -C /repo restore -- hello.txt git -C /repo restore --staged -- hello.txt git -C /repo restore --source HEAD~1 -- hello.txt git -C /repo commit -am 'Restore original greeting' git -C /repo mv hello.txt greeting.txt git -C /repo commit -m 'Rename greeting' git -C /repo rm greeting.txt git -C /repo commit -am 'Remove greeting' ``` | Command | Behavior | | - | - | | `add` | `-A` stages all changes, `-u` tracked changes, `-f` allows ignored paths | | `reset` | Mixed reset from HEAD, optionally limited by paths; no revision operand or hard reset | | `restore` | Worktree by default, `--staged` for the index, `-SW` for both; `--source` accepts a tree-ish | | `rm` | Refuses uncommitted changes unless `-f`; `--cached` keeps working files; `-r` allows directories | | `mv` | Files or directories; supports force, dry-run, verbose and skip-failure modes; cannot cross mounts | | `commit` | Commits the whole index; `-a` restages tracked files, `--allow-empty` permits an empty change | `restore` can discard changes in the selected destination. Use `--` before a path beginning with `-`. Permission and read-only refusals go through the workspace dispatcher and are reported in Git's command-specific wording. ## Branches, tags and history ```bash theme={null} git -C /repo branch topic git -C /repo switch topic git -C /repo switch -c experiment git -C /repo checkout --detach HEAD~1 git -C /repo branch --contains HEAD git -C /repo tag v1.0 git -C /repo tag -a v1.1 -m 'Release' git -C /repo for-each-ref --format='%(refname:short)' refs/heads git -C /repo reflog git -C /repo stash list ``` Annotated tags need `-m`; lightweight tags can point to any object. Revision expressions include parent/ancestor operators (`^`, `~`), typed peels such as `HEAD^{tree}`, and paths such as `HEAD:hello.txt`. Operators apply left to right. Invalid suffixes are refused as part of the whole revision. `log`, `show`, `rev-list`, `diff-tree`, `shortlog`, `cat-file`, `hash-object` and `ls-tree` provide inspection without a host Git process. Run each command's `--help` for supported formatting, filtering, path and diff options. ## Clone, fetch and repository configuration ```bash theme={null} git clone /repo /work/copy git clone https://github.com/acme/tools.git /work/tools git -C /work/tools fetch origin git -C /work/tools remote -v git -C /work/tools config --get remote.origin.url git --git-dir=/repo/.git --work-tree=/repo status --short ``` Clone and fetch can read another workspace repository or a smart-HTTP remote. Destinations must be writable mounts. There is no push or pull command. A path git refuses to check out is refused by `checkout`, `switch`, `restore` and `reset` as git refuses it; `git clone` then exits 128 and keeps the repository with an empty work tree. Reading the entries of a tree that holds an entry with an empty name exits 128 with git's `empty filename in tree entry`. For authenticated GitHub clones, `gh repo clone` supplies its configured token, and only to its configured GitHub origin. `--git-dir` and `--work-tree` override `GIT_DIR` and `GIT_WORK_TREE` and resolve against `-C`. Repository `core.worktree` and `core.bare` affect discovery; linked worktrees use their recorded layout. Working-tree commands refuse bare repositories. No repository operation opens a host path behind the VFS. ## Limits and intentional differences * Only the listed command subset is implemented. Merge, rebase, push, pull, `reset --hard` and `switch -` are absent; stash supports inspection only. * Commits accept no path operands and do not create merge commits. An unmerged index blocks commits and branch moves. `checkout` is stricter than Git about staged changes; `switch` can carry compatible staged changes but refuses file/directory collisions that would discard them. * Host templates, hooks, editors and Git's initial-branch advisory are absent. Per-worktree `config.worktree` is not read. With conflicting `core.bare` and `core.worktree`, Mirage keeps the repository bare without Git's warning. * Working-tree replacements preserve executable modes and symlink semantics. They do not follow a symlink out of a directory being replaced. Nested mounts block removals or replacements that would consume their contents; destinations are checked before writes begin. Renames preserve namespace metadata and cannot cross mount boundaries at either end. * Gitlinks create or retain directory placeholders. Mirage does not check out submodule content or compare a submodule's HEAD; files inside a submodule directory can still appear as untracked. Removing a nonempty gitlink directory warns and leaves it in place. * Diff hunk bodies and diffstat counts can differ from native Git because the line-diff algorithm differs from xdiff. Headers, ordering and supported formatting match Git. Pretty formats `email`, `mboxrd` and `reference` are refused. * History searches use ASCII case folding. `--since` and `--until` accept ISO-8601 or epoch seconds; relative date phrases are refused. * `tag -l`/`-d` conflict wording uses a fixed option order. Tag deletion uses a ref transaction: duplicate updates are refused atomically, while missing names are reported and skipped. These boundaries are exercised by the shared Git integration corpus on RAM and disk mounts. The VFS determines which filesystem operations are available; registering `git` does not make a read-only mount writable. ## Upstream and dependency licenses | Project | Role in Mirage | License | | - | - | - | | [Git](https://github.com/git/git) | Command behavior and repository-format reference; Mirage's CLI does not launch the native Git executable | [GPL-2.0, with the qualifications in Git's COPYING file](https://github.com/git/git/blob/master/COPYING) | | [Dulwich](https://github.com/jelmer/dulwich) | Python Git implementation dependency | [Apache-2.0 OR GPL-2.0-or-later](https://github.com/jelmer/dulwich/blob/main/COPYING) | | [isomorphic-git](https://github.com/isomorphic-git/isomorphic-git) | TypeScript Git implementation dependency | [MIT](https://github.com/isomorphic-git/isomorphic-git/blob/main/LICENSE.md) | | [Mirage](https://github.com/strukto-ai/mirage) | Command layer and VFS adapters | [Apache-2.0](https://github.com/strukto-ai/mirage/blob/main/LICENSE) | Dulwich offers an Apache-2.0 option; using it does not require choosing its GPL alternative. Matching Git behavior does not relicense Git, Dulwich or isomorphic-git. Copied or ported source and redistributed dependencies still carry their applicable terms and notices; see [compatibility and licenses](/home/setup/clis#compatibility-and-licenses). # GWS Source: https://docs.mirage.strukto.ai/typescript/cli/gws Supported Google Workspace API methods and helpers for seven services. Use Google Drive, Sheets, Docs, Slides, Calendar, Forms and Gmail through one command tree. Mirage implements a subset of the [Google Workspace CLI (`gws`)](https://github.com/googleworkspace/cli), with selected API methods and helpers for mail, spreadsheet ranges and document text. ## Setup Use [Google Workspace setup](/home/setup/google) to obtain OAuth credentials and the scopes needed by each service. ```typescript theme={null} import { GWS, Workspace } from '@struktoai/mirage-node' const config = { clientId: '...', clientSecret: '...', refreshToken: '...' } const ws = new Workspace({}) ws.registerCli('gws', GWS, config) ``` No service mount is required. For YAML and multiple accounts, see the [CLI overview](/typescript/cli/index#register-a-cli). ## Supported commands Run `gws <command> --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `gws drive files list` | GET /files (Google drive API passthrough) | | `gws drive files get` | GET /files/\{fileId} (Google drive API passthrough) | | `gws drive files create` | POST /files (Google drive API passthrough) | | `gws drive files update` | PATCH /files/\{fileId} (Google drive API passthrough) | | `gws drive files copy` | POST /files/\{fileId}/copy (Google drive API passthrough) | | `gws drive files delete` | DELETE /files/\{fileId} (Google drive API passthrough) | | `gws drive files export` | GET /files/\{fileId}/export (Google drive API passthrough) | | `gws drive permissions create` | POST /files/\{fileId}/permissions (Google drive API passthrough) | | `gws drive permissions list` | GET /files/\{fileId}/permissions (Google drive API passthrough) | | `gws drive permissions delete` | DELETE /files/\{fileId}/permissions/\{permissionId} (Google drive API passthrough) | | `gws sheets spreadsheets get` | GET /spreadsheets/\{spreadsheetId} (Google sheets API passthrough) | | `gws sheets spreadsheets create` | POST /spreadsheets (Google sheets API passthrough) | | `gws sheets spreadsheets batchUpdate` | POST /spreadsheets/\{spreadsheetId}:batchUpdate (Google sheets API passthrough) | | `gws sheets read` | Read a cell range. Aliases: `+read`. | | `gws sheets write` | Overwrite a range with 2D values | | `gws sheets append` | Append rows after a range. Aliases: `+append`. | | `gws docs documents get` | GET /documents/\{documentId} (Google docs API passthrough) | | `gws docs documents create` | POST /documents (Google docs API passthrough) | | `gws docs documents batchUpdate` | POST /documents/\{documentId}:batchUpdate (Google docs API passthrough) | | `gws docs write` | Append text to a document. Aliases: `+write`. | | `gws slides presentations get` | GET /presentations/\{presentationId} (Google slides API passthrough) | | `gws slides presentations create` | POST /presentations (Google slides API passthrough) | | `gws slides presentations batchUpdate` | POST /presentations/\{presentationId}:batchUpdate (Google slides API passthrough) | | `gws calendar calendarList list` | GET /users/me/calendarList (Google calendar API passthrough) | | `gws calendar calendars get` | GET /calendars/\{calendarId} (Google calendar API passthrough) | | `gws calendar events list` | GET /calendars/\{calendarId}/events (Google calendar API passthrough) | | `gws calendar events get` | GET /calendars/\{calendarId}/events/\{eventId} (Google calendar API passthrough) | | `gws calendar events insert` | POST /calendars/\{calendarId}/events (Google calendar API passthrough) | | `gws calendar events patch` | PATCH /calendars/\{calendarId}/events/\{eventId} (Google calendar API passthrough) | | `gws calendar events delete` | DELETE /calendars/\{calendarId}/events/\{eventId} (Google calendar API passthrough) | | `gws calendar freebusy query` | POST /freeBusy (Google calendar API passthrough) | | `gws forms forms create` | POST /forms (Google forms API passthrough) | | `gws forms forms get` | GET /forms/\{formId} (Google forms API passthrough) | | `gws forms forms batchUpdate` | POST /forms/\{formId}:batchUpdate (Google forms API passthrough) | | `gws forms forms responses list` | GET /forms/\{formId}/responses (Google forms API passthrough) | | `gws forms forms responses get` | GET /forms/\{formId}/responses/\{responseId} (Google forms API passthrough) | | `gws gmail users drafts create` | POST /users/\{userId}/drafts (Google gmail API passthrough) | | `gws gmail users drafts delete` | DELETE /users/\{userId}/drafts/\{id} (Google gmail API passthrough) | | `gws gmail users drafts get` | GET /users/\{userId}/drafts/\{id} (Google gmail API passthrough) | | `gws gmail users drafts list` | GET /users/\{userId}/drafts (Google gmail API passthrough) | | `gws gmail users drafts send` | POST /users/\{userId}/drafts/send (Google gmail API passthrough) | | `gws gmail users drafts update` | PUT /users/\{userId}/drafts/\{id} (Google gmail API passthrough) | | `gws gmail users labels list` | GET /users/\{userId}/labels (Google gmail API passthrough) | | `gws gmail users messages list` | GET /users/\{userId}/messages (Google gmail API passthrough) | | `gws gmail users messages get` | GET /users/\{userId}/messages/\{id} (Google gmail API passthrough) | | `gws gmail users messages send` | POST /users/\{userId}/messages/send (Google gmail API passthrough) | | `gws gmail users messages trash` | POST /users/\{userId}/messages/\{id}/trash (Google gmail API passthrough) | | `gws gmail users messages attachments get` | GET /users/\{userId}/messages/\{messageId}/attachments/\{id} (Google gmail API passthrough) | | `gws gmail send` | Send a new email via Gmail. Aliases: `+send`. | | `gws gmail read` | Fetch one Gmail message as processed JSON (same shape as cat \<path>.gmail.json). Aliases: `+read`. | | `gws gmail reply` | Reply to the sender of a Gmail message (excludes CC). Aliases: `+reply`. | | `gws gmail reply-all` | Reply to a Gmail message including all recipients (To+CC). Aliases: `+reply-all`. | | `gws gmail forward` | Forward a Gmail message to a new recipient. Aliases: `+forward`. | | `gws gmail triage` | List message summaries (id, from, subject, date, snippet) for a Gmail search query. Aliases: `+triage`. | ## Call an API method ```bash theme={null} gws drive files list --params '{"pageSize":10}' gws gmail users messages get --params '{"userId":"me","id":"MESSAGE_ID"}' gws drive permissions create --params '{"fileId":"FILE_ID"}' --json '{"role":"reader","type":"anyone"}' gws sheets spreadsheets create --json '{"properties":{"title":"Q3 planning"}}' ``` The form is `gws SERVICE RESOURCE METHOD`. `--params` supplies URL path and query parameters; `--json` supplies the body. Methods return the API response as compact JSON. Lists follow `nextPageToken` by default and print multiple pages as NDJSON. Use `--page-limit N` to stop early. Export methods can return raw bytes instead of JSON. The supported methods are the registered subset above, not every method in Google's Discovery documents. ## Use helpers ```bash theme={null} gws gmail triage --query 'is:unread' --max 10 gws gmail +triage --query 'is:unread' --max 10 gws gmail read --id MESSAGE_ID gws gmail send --to user@example.com --subject Hello --body 'Hi there' gws gmail reply --message-id MESSAGE_ID --body 'Thanks' gws sheets read --spreadsheet SHEET_ID --range 'Sheet1!A1:C10' gws sheets append --spreadsheet SHEET_ID --values 'alice,42' gws docs write --document DOC_ID --text 'New paragraph' gws docs write --document DOC_ID --tab TAB_ID --text 'Into this tab' ``` Helpers omit the upstream CLI's `+` prefix: use `gws docs write`, not `gws docs +write`. `--tab` is Mirage's addition for document tabs. ## Choose a document tab `gws docs documents get --params '{"documentId":"DOC_ID"}'` returns the legacy body of the first tab. Add `"includeTabsContent":true` to receive `tabs[].documentTab`, including nested `childTabs`, instead of that flat body. Mounted `.gdoc.json` files always use the tab-aware shape. `docs write` appends to the first tab unless `--tab` selects another one. A raw `batchUpdate` follows the API's defaults: `replaceAllText` without a tab restriction can affect every tab. ## VFS, folder placement and limits The CLI can share `GoogleConfig` with Google's VFS adapters. Each registration owns its config and requires no mount. Setting `folder_id` (`folderId` in TypeScript) changes **creation placement**, not which files the CLI may read: * Drive `files create` and `copy` default `parents` to that folder. * An explicit `parents` array wins, including an empty array. * Docs, Sheets and Slides creation is followed by a Drive move into the folder. These are separate requests, so a failed move can leave the new file created. * Injected placement requests include Shared Drive support. Reads still reach the whole account allowed by the credential. Use command policy to restrict operations; a mounted folder is not a CLI access boundary. Mirage registers a fixed command subset; upstream builds commands from Google Discovery at runtime. Folder placement and helper spelling also differ, and the host config supplies credentials instead of an interactive login. Mirage paginates list methods by default; upstream requires `--page-all`. Parser refusals use Mirage's declared command style, so upstream exit codes and diagnostics are not a blanket compatibility promise. The original `gws` is [Apache-2.0 licensed](https://github.com/googleworkspace/cli/blob/main/LICENSE). Mirage's command implementation is also Apache-2.0; see [compatibility and licenses](/home/setup/clis#compatibility-and-licenses). # hf Source: https://docs.mirage.strukto.ai/typescript/cli/hf Supported Hugging Face Hub commands for downloads, commits, repositories and tags. Download Hugging Face Hub files into the workspace and upload files or directories as a single commit. Mirage also supports repository creation, tags and file deletion using the [official `hf` vocabulary](https://github.com/huggingface/huggingface_hub). ## Setup Create a token using [Hugging Face setup](/home/setup/hf_models). TypeScript imports `HF` from the Node package. The Hub API needs no Python extra; `hf-buckets` is a separate storage backend. ```typescript theme={null} import { HF, MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node' const config = { token: 'hf_...' } const ws = new Workspace({ '/work': new RAMVFS() }, { mode: MountMode.WRITE }) ws.registerCli('hf', HF, config) ``` No service mount is required. For YAML and multiple accounts, see the [CLI overview](/typescript/cli/index#register-a-cli). ## Supported commands Run `hf <command> --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `hf auth whoami` | Find out which huggingface.co account you are logged in as | | `hf auth list` | List all stored access tokens | | `hf repo create` | Create a new repo on huggingface.co | | `hf repo tag create` | Create a tag for a repo | | `hf repo tag list` | List tags for a repo | | `hf repo tag delete` | Delete a tag from a repo | | `hf repo-files delete` | Delete files from a repo on the Hub | | `hf download` | Download files from the Hub | | `hf upload` | Upload a file or a folder to the Hub. Recommended for single-commit uploads | | `hf env` | Print information about the environment | | `hf version` | Print information about the hf version | ## Download, edit and upload ```bash theme={null} hf auth whoami hf download acme/model config.json --local-dir /work sed -i 's/1024/2048/' /work/config.json hf upload acme/model /work/config.json config.json --commit-message 'Widen the model' ``` `/work` must be a writable workspace mount. Each upload is one commit, including all files selected from a directory. `--repo-type` selects models, datasets or spaces; `--revision` selects a branch, tag or commit. Local paths resolve against the shell's working directory. With no source, `hf upload acme/model` reads `./model`. Downloads, uploads and cache files use workspace operations rather than the host filesystem. ## Repositories and tags ```bash theme={null} hf repo create acme/new-model --private hf repo tag create acme/model v1.0 hf repo tag list acme/model hf repo tag delete acme/model v1.0 hf repo-files delete acme/model '*.tmp' ``` For spaces, use `--repo-type space` and `--space_sdk`. `--exist-ok` accepts an existing repository. Deleting matching files creates one commit. ## Select files and cache downloads `--include`, `--exclude`, `--delete` and `repo-files delete` use Hub glob semantics: `*` crosses `/`, `[!a]` negates a character class, and a trailing `/` names a folder. Directory uploads exclude `.git` and `.cache/huggingface`. Single-file uploads ignore the include/exclude/delete filters with warnings. Deletion globs match the remote listing; `--delete` is relative to the upload destination and spares files re-added by the same commit. `.gitattributes` is never deleted. An empty change is skipped with a warning. Without `--local-dir`, downloads use the cache layout under `--cache-dir`: ```text theme={null} models--acme--model/ blobs/<etag> refs/main snapshots/<sha>/config.json -> ../../blobs/<etag> ``` A branch or tag download writes its ref; a commit-pinned download does not. `--force-download` refetches a blob. Relative cache paths, including `HF_HUB_CACHE` and `HF_HOME`, resolve against the session's working directory. ## VFS and limits The [model](/typescript/setup/hf_models), [dataset](/typescript/setup/hf_datasets) and [space](/typescript/setup/hf_spaces) VFS adapters expose remote repository files without creating a local checkout. They are read-only. Use a writable mount for editing and `hf upload` to choose the commit boundary. There is no interactive `auth login` or `auth logout`; the registered config supplies the token. Only the listed commands are implemented. Upstream `huggingface_hub` uses [Apache-2.0](https://github.com/huggingface/huggingface_hub/blob/main/LICENSE), as does Mirage's command implementation. See [compatibility and licenses](/home/setup/clis#compatibility-and-licenses). # Himalaya Source: https://docs.mirage.strukto.ai/typescript/cli/himalaya Supported IMAP and SMTP commands for reading, composing and sending mail. List and search IMAP mail, read messages, and compose, reply, forward or send through SMTP. Mirage uses the [Himalaya](https://github.com/pimalaya/himalaya) command vocabulary with JSON output and workspace file attachments. ## Setup Configure the account using [Email setup](/home/setup/email). Python needs the `email` extra; TypeScript imports `HIMALAYA` from the Node package. ```typescript theme={null} import { HIMALAYA, Workspace } from '@struktoai/mirage-node' const config = { imapHost: 'imap.example.com', smtpHost: 'smtp.example.com', username: 'agent@example.com', password: 'app-password' } const ws = new Workspace({}) ws.registerCli('himalaya', HIMALAYA, config) ``` No service mount is required. For YAML and multiple accounts, see the [CLI overview](/typescript/cli/index#register-a-cli). ## Supported commands Run `himalaya <command> --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `himalaya mailbox list` | List the mailboxes of the account. Aliases: `ls`. | | `himalaya flag add` | Add flags to messages | | `himalaya flag set` | Replace the flags of messages | | `himalaya flag remove` | Remove flags from messages. Aliases: `rm`. | | `himalaya attachment list` | List the attachments of one message. Aliases: `ls`. | | `himalaya attachment download` | Save a message's attachments to the workspace. Aliases: `dl`. | | `himalaya envelope list` | List the envelopes of a mailbox, most recent first. Aliases: `ls`. | | `himalaya envelope search` | Search envelopes with the query DSL. Aliases: `sr`. | | `himalaya message copy` | Copy messages to another mailbox. Aliases: `cp`. | | `himalaya message move` | Move messages to another mailbox. Aliases: `mv`. | | `himalaya message delete` | Move messages to the trash, or remove them once they are there. Aliases: `rm`. | | `himalaya message read` | Read a message | | `himalaya message compose` | Compose a new message from flags. Aliases: `write`, `new`. | | `himalaya message send` | Send a message through the account | | `himalaya message add` | Add a raw RFC 5322 message to a mailbox. Aliases: `save`. | | `himalaya message reply` | Reply to a message | | `himalaya message forward` | Forward a message. Aliases: `fwd`. | ## Triage and read ```bash theme={null} himalaya envelope list -m INBOX --page 1 --page-size 10 himalaya envelope search -m INBOX not flag seen and from alice@example.com himalaya envelope search after 2026-01-01 order by subject asc himalaya envelope search subject '"quarterly review"' himalaya --json envelope list -m INBOX | jq -r '.envelopes[].subject' himalaya message read -m INBOX 12345 himalaya message read -m INBOX 12345 --raw himalaya mailbox list --counts himalaya flag add 12345 -f seen -f flagged himalaya message move 12345 --to Archive himalaya message copy 12345 --from Archive --to Projects himalaya message delete 12345 himalaya attachment list 12345 himalaya attachment download 12345 -d /data/attachments ``` Output matches upstream Himalaya. Listings print tables and confirmations print a sentence; add the global `--json` for JSON, in any position. `message read` shows the headers and walks the MIME parts, `--raw` returns RFC 5322 bytes, and `--seen` marks the message as seen, which reading alone does not. Messages take positional IDs. `-m/--mailbox` defaults to `INBOX`. An attachment's ID is its position among the message's MIME parts. Listings are newest first, with pages starting at 1 and a default page size of 25. The account's `max_messages` (default 200) bounds the search and paging window. Sorted search considers that whole window. Search conditions are `date`, `after`, `from`, `to`, `subject`, `body` and `flag`. Combine them with `and`, `or`, `not` and parentheses; sort with `order by date|from|to|subject [asc|desc]`. Date conditions use the message's `Date:` header, and `after` is exclusive. A pattern containing spaces needs literal double quotes inside the shell quotes, as above. A malformed query exits 1 before contacting the server, and the report points at where it stopped. ## Compose, reply and send ```bash theme={null} himalaya message compose --to you@example.org --subject Report --body 'See attached' --attach /work/report.pdf himalaya message compose --to you@example.org --subject Hello --body Hi --send echo 'The body' | himalaya message compose --to you@example.org --subject Hello | himalaya message send himalaya message reply -m INBOX 12345 --body 'Thanks' --send himalaya message forward -m INBOX 12345 --to colleague@example.com --send ``` **Without `--send`, compose/reply/forward print MIME bytes and send nothing.** With `--json` they print the decoded fields instead. Bodies come from `--body`, `--body-file` or stdin. `message send` accepts raw MIME on stdin, or after `--` as text or a file path. `--attach` is repeatable and reads workspace files through the VFS; `--from`, `--to`, `--cc`, `--bcc`, `--subject`, `--signature` and `--signature-file` control the composed message. `message add -m MAILBOX` appends raw MIME to a mailbox and reports the new id. Reply uses `Reply-To` or `From`, adds reply headers and quotes the source. Forward prefixes the subject with `Fwd:` and keeps `References`. Both accept `--posting-style top|bottom|none` and `--quote-headline`. There is no reply-all switch; supply the extra recipients through `--cc`. ## Save drafts and sent copies ```bash theme={null} himalaya message compose --to you@example.org --body Draft --save Drafts himalaya message send --save Sent < /work/message.eml ``` Sending normally saves a seen copy by IMAP after SMTP succeeds. Mirage uses the server's `\Sent` folder, or the config's `sent_folder` (`sentFolder`) when set. `save_copy=False` (`saveCopy: false`) disables the default copy. `--save MAILBOX` overrides both settings for one command; without `--send` on a composer, it saves a draft and sends nothing. `--no-save` skips the configured copy. A copy that fails after delivery exits 1 and says the message was already sent, so do not retry it. Saving a draft without sending fails normally if IMAP refuses it. ## VFS and limits The optional [Email VFS](/typescript/setup/email) exposes the mailbox as files. Reading a message does not mark it seen. The CLI uses its own account config; attachments can come from any readable workspace mount. Server matching rules determine how search patterns match addresses and text. `trashFolder` picks the mailbox `message delete` moves to, as upstream's `mailbox.alias.trash`; unset, the server's `\\Trash` tag decides. Only the mailbox, envelope, flag, message and attachment commands are present, and `-c`, `-a` and `-b` are not accepted since an install is one account. Upstream Himalaya offers a choice of [MIT](https://github.com/pimalaya/himalaya/blob/master/LICENSE-MIT) or [Apache-2.0](https://github.com/pimalaya/himalaya/blob/master/LICENSE-APACHE). Mirage's command implementation is Apache-2.0; see [compatibility and licenses](/home/setup/clis#compatibility-and-licenses). # Overview Source: https://docs.mirage.strukto.ai/typescript/cli/index Register and discover Mirage’s supported CLIs, and use them with workspace files. Mirage includes twelve command-line programs for working with services, Git repositories and search mounts inside a workspace. Each program's `--help` describes the commands and flags implemented by Mirage. The [host `mirage` CLI](/home/access/cli) connects to and manages workspaces. The programs on this page run in those workspaces through `ws.shell(...)`, `mirage shell`, or another [access method](/home/access/overview). ## Supported CLIs | Program | Supported operations | Commands | | - | - | - | | [airtable](/typescript/cli/airtable) | Query bases and tables; read, create, update and delete records; add comments | 10 | | [discord](/typescript/cli/discord) | Read and send messages; edit, react, create threads and polls; inspect guilds | 14 | | [gh](/typescript/cli/gh) | Manage repositories, issues, pull requests, releases and Actions; call GitHub APIs | 103 | | [git](/typescript/cli/git) | Inspect history, stage and commit files, manage branches and tags, clone and fetch | 44 | | [gws](/typescript/cli/gws) | Call Drive, Sheets, Docs, Slides, Calendar, Forms and Gmail APIs | 54 | | [hf](/typescript/cli/hf) | Download and upload Hub files; create repositories; manage tags and delete files | 11 | | [himalaya](/typescript/cli/himalaya) | List and search mail; read, compose, reply, forward and send messages | 17 | | [linear](/typescript/cli/linear) | Query teams, issues, projects and documents; update issues and comments | 30 | | [ntn](/typescript/cli/ntn) | Read and edit Markdown pages, query data sources and call Notion APIs | 12 | | [search](/typescript/cli/search) | Rank the records of Dify, Chroma, mem0, Qdrant and LanceDB mounts for a query | 1 | | [slack](/typescript/cli/slack) | Read and send messages; manage reactions and pins; find members and search | 14 | | [trello](/typescript/cli/trello) | Read boards, lists, labels and cards; create, update, move, assign, label and comment on cards | 16 | All twelve are available in Python and TypeScript on Node. The TypeScript Node package provides `hf` and `himalaya`; the other ten live in core. These are Mirage implementations of the listed command trees, not installed copies of the upstream binaries. Each reference links its upstream project or service API and documents its supported subset, limits and relevant licenses. See [compatibility and licenses](/home/setup/clis#compatibility-and-licenses) for the distinction between matching behavior and reusing code. ## Register a CLI Account CLIs need credentials but do not need a service mount: ```typescript theme={null} import { SLACK, Workspace } from '@struktoai/mirage-node' const ws = new Workspace({}) ws.registerCli('slack', SLACK, { token: 'xoxb-...' }) await ws.shell('slack --help') ``` `registerCli(name, spec, config)` validates the config object with the spec's schema. `git` and `search` have no account config; register their `GIT` and `SEARCH` specs without the third argument. Two installations of the same spec under different names can use different accounts. Registration is a host operation, not an agent shell command. The equivalent YAML entry is: ```yaml theme={null} clis: slack: cli: slack config: token: ${SLACK_TOKEN} ``` YAML config fields use snake\_case in both languages. [Setup pages](/home/setup/clis) cover credentials and imports for every program. ## Discover functionality ```bash theme={null} man slack --help slack send-message --help man slack send-message type -t slack which slack ``` `man` and `--help` render the registered spec. Unknown commands and flags are refused; wording and exit codes follow the program's declared style. Use each reference for command-specific errors rather than assuming one exit code for all CLIs. Visible installed programs have read-only stubs under `/usr/bin`, so `which slack` returns `/usr/bin/slack`. The stub describes the command without exposing its config or credentials. Executing that path uses the same command and policy checks. Changing `PATH` does not change Mirage's virtual command lookup; host and remote runtimes use their own executable paths. ## Use CLIs with the VFS | Operation | Where it goes | | - | - | | `cat`, `find`, `grep`, `jq` on mounted files | The selected VFS through workspace operations | | Account commands such as `slack send-message` | The service configured for that CLI installation | | File arguments such as `gh --body-file`, `ntn --filter-file`, `himalaya --attach` and `hf upload` paths | Workspace files through `ctx.vfs` | | `git -C /repo ...` | The repository and working tree on workspace mounts | Credentials may be shared between a CLI and a VFS, but neither registers or locates the other. A CLI write uses service IDs, while file arguments resolve against the session's working directory and retain `PathSpec` semantics. After an account CLI write, Mirage expires the caches of every mount the CLI's client may reach, including answers a mount's client keeps itself (a vector store's search results), so later reads can observe the change. A client that names what it reaches narrows this: `gh` reaches only GitHub mounts on its API base. Mount modes and path policy govern workspace file operations. A read-only Slack mount does **not** disable `slack send-message`; use command policy to restrict service actions. The service's own credentials and permissions still apply to its API calls. ## Add a custom CLI Use [the authoring guide](/typescript/cli/custom) to define a typed command tree, register multiple accounts, work with VFS paths, or run a script CLI. It also covers config validation, snapshots and the shared command grammar. # linear Source: https://docs.mirage.strukto.ai/typescript/cli/linear Supported Linear commands for issues, comments, teams, projects and search. Query Linear teams, issues, projects, cycles, comments, users and documents. Mirage's noun/verb interface draws partly on [schpet/linear-cli](https://github.com/schpet/linear-cli), with its own supported command tree and normalized JSON output for `jq`. ## Setup Create an API key using [Linear setup](/home/setup/linear). ```typescript theme={null} import { LINEAR, Workspace } from '@struktoai/mirage-node' const config = { apiKey: 'lin_api_...' } const ws = new Workspace({}) ws.registerCli('linear', LINEAR, config) ``` No service mount is required. For YAML and multiple accounts, see the [CLI overview](/typescript/cli/index#register-a-cli). ## Supported commands Run `linear <command> --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `linear team list` | List teams as JSON | | `linear team get` | Get one team by key, name, or ID | | `linear team members` | List a team's members | | `linear issue list` | List a team's issues | | `linear issue get` | Get one issue by key or ID | | `linear issue create` | Create an issue | | `linear issue update` | Update an issue's title or description | | `linear issue assign` | Assign an issue to a user | | `linear issue transition` | Move an issue to a workflow state | | `linear issue set-priority` | Set an issue's priority | | `linear issue set-project` | Attach an issue to a project | | `linear issue relation add` | Create an issue relation | | `linear issue relation list` | List incoming and outgoing relations | | `linear issue relation delete` | Delete an issue relation | | `linear issue add-label` | Add a label to an issue | | `linear issue remove-label` | Remove a label from an issue | | `linear project list` | List a team's projects | | `linear project get` | Get one project by ID | | `linear cycle list` | List a team's cycles | | `linear cycle current` | Get a team's current cycle | | `linear cycle get` | Get one cycle by ID | | `linear label list` | List a team's labels | | `linear comment list` | List an issue's comments | | `linear comment add` | Comment on an issue | | `linear comment update` | Edit a comment | | `linear user list` | List workspace users | | `linear user get` | Get one user by email | | `linear document list` | List a team's documents | | `linear document get` | Get one document by ID | | `linear search` | Search issues by text | ## Find work ```bash theme={null} linear team list linear team members ENG linear issue list --team ENG linear issue get ENG-42 linear project list --team ENG linear cycle current --team ENG linear comment list ENG-42 linear user get sam@example.com linear document list --team ENG linear search "login bug" ``` Issues take a positional key such as `ENG-42` or a raw ID. `--team` accepts a team key, name or ID. Use the list commands to discover project, cycle, label and document IDs. ## Update work ```bash theme={null} linear issue create --team ENG --title "Fix login" --description "Reproduction steps" linear issue update ENG-42 --title "Fix expired-session login" linear issue assign ENG-42 --assignee-email user@example.com linear issue transition ENG-42 --state-name "In Review" linear issue set-priority ENG-42 --priority 2 linear issue set-project ENG-42 --project-name "Search" linear issue add-label ENG-42 --label-name bug linear issue remove-label ENG-42 --label-name bug echo 'Ready for review' | linear comment add ENG-42 linear comment update --comment COMMENT_ID --body "Reviewed" ``` | Value | Accepted forms | | - | - | | Assignee | `--assignee-email` or `--assignee-id` | | Workflow state | `--state-name` or `--state-id` | | Project | `--project-name` or `--project` with an ID | | Label | `--label-name` or `--label` with an ID; preserves existing labels | | Priority | `0` none, `1` urgent, `2` high, `3` normal, `4` low | Descriptions and comment bodies can come from stdin. Issue creation requires `--team` and `--title`; updates use the values explicitly supplied. ## Issue relations ```bash theme={null} linear issue relation add ENG-42 blocks ENG-43 linear issue relation add ENG-42 blocked-by ENG-43 linear issue relation add ENG-42 related ENG-43 linear issue relation add ENG-42 duplicate ENG-43 linear issue relation list ENG-42 linear issue relation delete ENG-42 duplicate ENG-43 --yes ``` The positional order is `ISSUE RELATION RELATED`, matching [linear-cli v3.1.0](https://github.com/schpet/linear-cli/tree/02571d34be662e5487204841fb80bf23ed79b4f0). Relation names are case insensitive. `blocked-by` stores the inverse of `blocks`. Deletion matches the exact stored direction, including `related`. Both issue references are validated before contacting the service. Relation commands accept full keys such as `eng-42`, Linear issue URLs, UUIDs and opaque IDs of the form `prefix_value`. UUID and opaque ID operands extend the upstream interface. An explicit issue is required for listing; branch inference and bare issue numbers are unavailable in this virtual CLI. Adding `ENG-42 duplicate ENG-43` marks ENG-42 as the duplicate and ENG-43 as its original. Linear applies the reserved Duplicate status through the relation mutation. Mirage does not submit a separate state update. Removing that relation lets Linear restore the previous status. See [Linear issue properties](https://linear.app/docs/issue-property) and the [June 18, 2026 changelog](https://linear.app/changelog/2026-06-18-agent-assisted-project-updates). Add and delete return one normalized JSON relation. List returns an array, outgoing relations first, followed by incoming relations, with all pages read. Each row contains `relation_id`, `type`, `direction`, `issue_id`, `issue_key`, `related_issue_id`, `related_issue_key` and `related_issue_title`. `issue_id` always identifies the queried or first operand issue. Incoming `blocks` rows have type `blocked-by`. Incoming `duplicate` rows keep type `duplicate` and `direction: "incoming"`; the other issue is the duplicate in that case. This JSON contract deliberately differs from upstream's text output. Deletion requires `--yes`, also spelled `-y`, `-f`, `--force` or `--confirm`. The virtual CLI cannot prompt. The relation is looked up before confirmation, so a missing relation still reports that failure first. Service errors and false mutation success flags fail the command. Mutations are not retried automatically, including when a response cannot confirm the outcome. Failure output follows the virtual CLI's conventions. Missing required operands and unknown options exit 2. Extra operands, relation validation, missing issues or relations, missing confirmation and service failures exit 1. Upstream instead classifies invalid relation names and missing confirmation as usage errors with exit 2, and missing entities with exit 3. Its authentication and availability failures use exits 4 and 5. Error wording also follows the virtual CLI rather than upstream text. ## VFS and limits The [Linear VFS](/typescript/setup/linear) lets agents browse the same service as files. The CLI takes service IDs and its own config; piping a mounted file into a body does not make that mount the CLI's account. Only the commands above are implemented. Commands, flags and JSON output follow this reference; Mirage does not promise full compatibility with `schpet/linear-cli`. That project uses the [ISC license](https://github.com/schpet/linear-cli/blob/main/LICENSE). Mirage's command implementation is Apache-2.0, with ISC-licensed relation adaptations recorded in `licenses/third_party/schpet-linear-cli.txt`; see [compatibility and licenses](/home/setup/clis#compatibility-and-licenses). # From MCP Source: https://docs.mirage.strukto.ai/typescript/cli/mcp Install a streamable-HTTP MCP server's tools as one CLI. An MCP server's tools become one CLI: each tool is a subcommand that takes the tool's arguments as one JSON object. Profiles, network rules and snapshots apply to it as to any CLI. ## Register a server `mcpCli` reads the server's tool list and returns a `CLI`; install it with `registerCli`, passing the same config: ```ts theme={null} import { Workspace, mcpCli } from '@struktoai/mirage-node' const config = { url: 'https://mcp.example.com/mcp', auth: { type: 'bearer', token: process.env.ISSUES_TOKEN! }, } const ws = new Workspace({}) ws.registerCli('issues', await mcpCli(config), config) ``` ```bash theme={null} issues --help issues search-issues --help issues search-issues '{"query": "login bug"}' ``` A tool named `search_issues` becomes the subcommand `search-issues`; its `--help` prints the tool's description and the JSON schema of its arguments. `mcpCli` rejects with `MCPToolsError` when the server cannot be listed within 5 minutes in all, it lists more than 1024 tools or more than 16 MiB of them, or its tools cannot all become distinct subcommands. The tool list is read once, at registration. To pick up tools the server added later, list them again, then remove the CLI and register the new one: ```ts theme={null} const cli = await mcpCli(config) await ws.unregisterCli('issues') ws.registerCli('issues', cli, config) ``` ## Authentication `auth` sets the one header every request carries. Leave it out for a server that needs none. | `auth` | Header sent | | - | - | | `{ type: 'bearer', token: T }` | `Authorization: Bearer T` | | `{ type: 'header', name: N, token: T }` | `N: T` | The token is redacted in snapshots. The URL is saved as written, so keep credentials in `auth`, not in the URL. A token must be printable ASCII with no leading or trailing space; any other is refused at registration. ## Register from YAML An MCP server is a `clis:` entry with `cli: mcp`. The token can come from `${VAR}` or a [credential pointer](/home/authentication): ```yaml workspace.yaml theme={null} mounts: /: vfs: ram clis: issues: cli: mcp config: url: https://mcp.example.com/mcp auth: type: bearer token: from: env key: ISSUES_TOKEN ``` `mirage workspace create workspace.yaml` builds it on the server, and `configToWorkspaceArgs` lists each server as it loads the file. ## Call a tool | Call | Result | | - | - | | `issues search-issues '{"query": "x"}'` | the tool's answer on stdout, exit 0 | | `issues list-labels` | the tool called with `{}` | | the tool reports an error | its text on stderr, exit 1 | | the server cannot be reached | `search-issues: MCP server failed: <reason>`, exit 1 | | the server gives no answer within 5 minutes | `search-issues: MCP server timed out`, exit 1 | | the answer is larger than 16 MiB | `search-issues: MCP server reply exceeds 16777216 bytes`, exit 1 | | the operand is not one JSON object | `search-issues: invalid JSON`, `JSON must be an object` or `takes one JSON object`, exit 2, nothing sent | Text content prints as text; any other content prints as one line of JSON. A failed call is not retried. Cancelling the line cancels the call. A `preNetwork` policy or a `network` setting that excludes the server's host refuses the call before anything is sent; a config's `network` also refuses listing its servers when it loads. ## Profiles A profile names a tool the way it names any CLI subcommand: ```yaml theme={null} profiles: triage: commands: deny: - commands: ["issues delete-issue"] reason: triage never deletes ``` A tool the server marks `readOnlyHint` runs as a read; every other tool counts as a write. ## On a server The [server](/typescript/access/server) takes `cli: mcp` entries in a workspace's create body. `${VAR}` is expanded only in files; over HTTP, send the token or a pointer. [`mirage cli`](/home/access/cli#saved-connections) saves a server's URL and token under a name, as a CLI of type `mcp`: ```bash theme={null} mirage cli create issues --type mcp --set url=https://mcp.example.com/mcp --set auth.type=bearer --secret auth.token ``` A create body or a template points at the saved fields: ```yaml theme={null} clis: issues: cli: mcp config: url: {from: strukto, ref: issues, key: url} auth: type: {from: strukto, ref: issues, key: auth.type} token: {from: strukto, ref: issues, key: auth.token} ``` ## Snapshots A snapshot keeps the tool list, so loading one rebuilds the CLI without contacting the server. The token is redacted, so pass the config again as the fourth argument: ```ts theme={null} const ws = await Workspace.load('snap.tar', {}, {}, { issues: config }) ``` # ntn Source: https://docs.mirage.strukto.ai/typescript/cli/ntn Supported Notion commands for Markdown pages, data sources and API calls. Read and edit Notion page bodies as Markdown, query data sources, or call the Notion API directly. Mirage implements the command subset below using the [official `ntn` grammar](https://www.npmjs.com/package/ntn). ## Setup Create an integration and grant it access to the relevant pages using [Notion setup](/home/setup/notion). ```typescript theme={null} import { NTN, Workspace } from '@struktoai/mirage-node' const config = { apiKey: 'secret_...' } const ws = new Workspace({}) ws.registerCli('ntn', NTN, config) ``` No service mount is required. For YAML and multiple accounts, see the [CLI overview](/typescript/cli/index#register-a-cli). ## Supported commands Run `ntn <command> --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `ntn api` | Call the public Notion API (beta) | | `ntn auth token` | Print the current authentication token | | `ntn datasources query` | Query pages in a data source | | `ntn datasources resolve` | Resolve a Notion database ID to its data source IDs | | `ntn files create` | Create a file upload from stdin or an external URL | | `ntn files get` | Retrieve a file upload by id | | `ntn files list` | List file uploads. Aliases: `ls`. | | `ntn pages get` | Retrieve a page as Markdown | | `ntn pages create` | Create a page from Markdown content | | `ntn pages edit` | Edit a page's content from Markdown | | `ntn pages trash` | Trash a page | | `ntn whoami` | Show the authenticated Notion user | ## Read and edit pages ```bash theme={null} ntn whoami ntn pages get PAGE_ID ntn pages get PAGE_ID --json ntn pages create --parent page:PARENT_ID --content '# Release notes' echo '# Release notes' | ntn pages create --parent data-source:SOURCE_ID ntn pages edit PAGE_ID --content '# Updated body' ntn pages trash PAGE_ID --yes cat /data/photo.png | ntn files create --filename photo.png ntn files create --external-url https://example.com/photo.png ntn files get UPLOAD_ID ntn files list --json ``` Page IDs are positional. Bodies are Markdown; the first heading becomes the title when creating a page. `--parent` accepts `page:`, `database:` or `data-source:` followed by an ID. **`pages edit` replaces the entire body.** Trashing requires confirmation; pass `--yes` for noninteractive use. To update database-row properties, use the API rather than page-body editing: ```bash theme={null} ntn api v1/pages/PAGE_ID -X PATCH -d '{"properties":{"Stage":{"select":{"name":"Draft"}}}}' ``` ## Query data sources ```bash theme={null} ntn datasources resolve DATABASE_ID ntn datasources query SOURCE_ID --limit 10 -s 'Priority desc' ntn datasources query SOURCE_ID --filter '{"property":"Stage","select":{"equals":"Done"}}' ntn datasources query SOURCE_ID --filter-file /work/filter.json --json ``` `resolve` returns a database's data source IDs. `query` accepts a data source or database ID/URL. Its default output is tab-separated: page ID followed by property values, with columns sorted by name from the returned rows. `--json` returns the API response. `--filter-file` reads through the workspace VFS, relative to the session's working directory. ## Call the API ```bash theme={null} ntn api v1/users/me ntn api v1/search -d '{"query":"Roadmap"}' ntn api v1/blocks/PAGE_ID/children page_size==10 ntn api v1/blocks/BLOCK_ID -X DELETE printf '{"query":"Roadmap"}' | ntn api v1/search ``` | Input | Meaning | | - | - | | `-d` / `--data`, stdin, or inline fields | Request body; choose one source | | `name=value` | String body field | | `name:=json` | Typed JSON body field | | `name==value` | Query parameter, regardless of method | | `Header:Value` | Request header | | `-X` / `--method` | `GET`, `POST`, `PATCH`, `PUT` or `DELETE` | A body selects POST unless a method is explicit. Blocks, comments and search use API paths; they are not separate command groups. ## VFS and limits The optional [Notion VFS](/typescript/setup/notion) provides page and database files. Reuse its IDs, or obtain them through the API; no mount is required. Interactive login/logout, update, workers, deployment and file-management commands are absent. The config supplies the credential. Command-line parsing follows CLAP style. Exit codes distinguish these failures: | Failure | Exit code | | - | - | | Unknown options or missing required arguments, such as `ntn --bogus` or `ntn pages get` | 2 | | Invalid JSON in a nonempty `ntn api --data` body or stdin | 1 | | Empty `--data`, invalid inline request input, or conflicting body sources | 5 | | Notion API authentication failure (HTTP 401) | 4 | | Other Notion API failures | 5 | The shared conformance suite checks the implemented surface against `ntn`. The suite pins `ntn` 0.21.9, whose [package metadata](https://registry.npmjs.org/ntn/0.21.9) declares MIT. Mirage's command implementation is Apache-2.0; see [compatibility and licenses](/home/setup/clis#compatibility-and-licenses). # search Source: https://docs.mirage.strukto.ai/typescript/cli/search Rank the records of Dify, Chroma, mem0, Qdrant and LanceDB mounts for a query. `search` asks a mount's own search to rank its records for a query: Dify's retrieval API, Chroma's and Qdrant's vector queries, mem0's memory search and LanceDB's vector search. Use it when meaning matters; `grep` and `rg` still match exact text. ## Setup `search` has no account config. It searches the mounts it is pointed at, so register it on a workspace that mounts a store: ```typescript theme={null} import { ChromaVFS, MountMode, SEARCH, Workspace } from '@struktoai/mirage-node' const knowledge = new ChromaVFS({ config: { collectionName: 'docs' } }) const ws = new Workspace({ '/knowledge/': knowledge }, { mode: MountMode.READ }) ws.registerCli('search', SEARCH) await ws.shell('search "how do I get started" /knowledge/') ``` Mounting a store does not register `search`. For YAML registration, see the [CLI overview](/typescript/cli/index#register-a-cli): ```yaml theme={null} clis: search: cli: search ``` ## Supported commands Run `search --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `search` | Rank the records of a search mount for a query | ## Usage ```bash theme={null} search "how do I reset my password" /knowledge/ search --top-k 5 "billing policy" /knowledge/policies/ /knowledge/guides/ search --threshold 0.4 "quickstart" /knowledge/guides/*.md ``` | Argument | Meaning | | - | - | | `QUERY` | The text to rank records by. | | `PATH ...` | Folders, files or globs to search; the working directory when none is given. Several are ranked as one query when one mount serves them all. | | `--top-k N` | The most hits to print, 1 or more. Absent, the mount's default: 10, or the config's `searchLimit` on Qdrant and LanceDB and `defaultSearchLimit` on mem0. | | `--threshold F` | The score a hit must reach, or on LanceDB the largest distance it may have; `0` keeps every hit. | | `--method M` | `semantic`, the default. Dify also takes `fulltext`, `hybrid` and `keyword`. | Each hit prints its path, then its score where the store ranks, then the record's text: ```text theme={null} /knowledge/policies/refunds:0.82 Refunds are allowed within 30 days. ``` A file the session cannot see is never printed. ## Mounts | Mount | Searches with | `--threshold` | | - | - | - | | [Dify](/python/vfs/dify#search) | The dataset retrieval API | Dify's score, from 0 to 1 | | [Chroma](/typescript/setup/chroma) | Chroma's vector query | 1 minus Chroma's distance | | [mem0](/typescript/setup/mem0) | mem0's memory search | mem0's score, from 0 to 1 | | [Qdrant](/typescript/setup/qdrant) | Qdrant's vector query | Qdrant's score | | [LanceDB](/typescript/setup/lancedb) | LanceDB's vector search | The largest distance kept | ## Answer from a custom VFS A [custom VFS](/typescript/vfs/new) joins the list by overriding `search`. It gets the path the line names and a `SearchQuery`: the text in `query`, and in `options` the `top_k`, `threshold` and `method` the line gives. It returns one `[path, record]` pair per hit, the hit's workspace path and the text `search` prints; `[]` means no match and `null` declines. A VFS that ranks several paths together overrides `searchMany(paths, query)` as well. Pass the path on to the service, so a search under one folder ranks only that folder's notes and no other folder's hits use up `top_k`. ```ts theme={null} import { BaseVFS, type PathSpec, type SearchQuery } from '@struktoai/mirage-node' import { mountedPath } from '@struktoai/mirage-core/utils/key_prefix' class NotesVFS extends BaseVFS<NotesAccessor> { override async search(path: PathSpec, query: SearchQuery): Promise<[string, string][] | null> { const hits = await this.accessor.client.search(query.query, { folder: path.vfsPath, limit: Number(query.options?.top_k ?? 10), }) return hits.map((hit) => [mountedPath(path, `/${hit.key}`).virtual, hit.text]) } } ``` A search never passes the file cache. To keep results, the accessor holds a `ResponseCache` and returns it from `caches()`; the mount then expires it with its read policy and drops it after a write from outside Mirage. ```ts theme={null} import { Accessor, ResponseCache } from '@struktoai/mirage-node' class NotesAccessor extends Accessor { readonly searches = new ResponseCache<string, [string, string][]>() override caches(): readonly ResponseCache<unknown, unknown>[] { return [this.searches] } } ``` `await this.searches.get(key, fetch)` answers from the cache or calls `fetch`. ## Errors | Line | Exit | Prints | | - | - | - | | No query, an empty one, `--top-k` below 1, an unknown option, or a value that is not a number | 2 | `search: query is required`, `search: top-k must be positive`, or the option error and `Try 'search --help' for more information.` | | A value the mount does not take, such as `--method keyword` on Chroma or `--threshold 1.5` on Dify | 1 | The mount's reason, such as `search: only the 'semantic' method is supported` | | A path that does not exist | 1 | `search: /knowledge/nope: No such file or directory` | | A path on a mount without search | 1 | `search: /data: Operation not supported` | # slack Source: https://docs.mirage.strukto.ai/typescript/cli/slack Supported Slack commands for messages, reactions, pins, members and search. Read and send Slack messages, share files, manage reactions and pins, and look up members or search messages. The action names follow [OpenClaw](https://github.com/openclaw/openclaw); `search` and `list-members` are Mirage extensions. ## Setup Use the bot and user token scopes in [Slack setup](/home/setup/slack). The bot token handles ordinary actions; `search` needs `search_token` (`searchToken` in TypeScript). ```typescript theme={null} import { SLACK, Workspace } from '@struktoai/mirage-node' const config = { token: 'xoxb-...', searchToken: 'xoxp-...' } const ws = new Workspace({}) ws.registerCli('slack', SLACK, config) ``` No service mount is required. For YAML and multiple accounts, see the [CLI overview](/typescript/cli/index#register-a-cli). ## Supported commands Run `slack <command> --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `slack send-message` | Post a message to a channel or thread | | `slack edit-message` | Replace the text of a message | | `slack delete-message` | Delete a message | | `slack upload-file` | Share a workspace file in a channel or thread | | `slack read-messages` | Read the most recent messages of a channel | | `slack react` | Add an emoji reaction to a message | | `slack reactions` | List the reactions on a message | | `slack pin-message` | Pin a message to its channel | | `slack unpin-message` | Remove a pin from a message | | `slack list-pins` | List the pinned items of a channel | | `slack member-info` | Fetch one user's profile | | `slack list-members` | List workspace members, optionally filtered | | `slack emoji-list` | List the workspace's custom emoji | | `slack search` | Search messages with Slack query operators | ## Messages, reactions and pins ```bash theme={null} slack read-messages --channel C04KEPWF6V7 --limit 20 slack send-message --channel C04KEPWF6V7 --text "Release is ready" slack send-message --channel C04KEPWF6V7 --thread-ts 1712345678.123456 --text "Thread reply" slack edit-message --channel C04KEPWF6V7 --ts 1712345678.123456 --text "Release shipped" slack delete-message --channel C04KEPWF6V7 --ts 1712345678.123456 slack upload-file --channel C04KEPWF6V7 --file /data/reply.wav --initial-comment "Spoken reply" slack react --channel C04KEPWF6V7 --ts 1712345678.123456 --emoji thumbsup slack reactions --channel C04KEPWF6V7 --ts 1712345678.123456 slack pin-message --channel C04KEPWF6V7 --ts 1712345678.123456 slack list-pins --channel C04KEPWF6V7 slack unpin-message --channel C04KEPWF6V7 --ts 1712345678.123456 ``` Channels and users are Slack IDs. A message is identified by its channel and timestamp (`--ts`); replies use the parent's timestamp in `--thread-ts`. `upload-file` reads `--file` from the workspace, so any mount can be the source. ## Find people and messages ```bash theme={null} slack member-info --user U04K21SEVR9 slack list-members --query alice slack emoji-list slack search --query 'from:@priya in:#general launch' --count 20 --page 1 ``` Search accepts Slack operators such as `from:`, `in:` and `after:`. Results are JSON and can be piped to `jq`. ## VFS and limits The optional [Slack VFS](/typescript/setup/slack) exposes channels and messages as files. Its IDs can be passed to this CLI, but the CLI gets credentials from its own registration and does not need the mount. Only the listed actions are implemented; this is not Slack's app-development CLI. Mount read-only mode does not prevent service writes—use command policy to restrict sending messages, reactions or pin changes. OpenClaw's source uses the [MIT license](https://github.com/openclaw/openclaw/blob/main/LICENSE). Mirage's command implementation is Apache-2.0; see [compatibility and licenses](/home/setup/clis#compatibility-and-licenses). # trello Source: https://docs.mirage.strukto.ai/typescript/cli/trello Supported Trello commands for boards, lists, labels, cards and comments. Read Trello boards, lists, labels, cards and comments, and create, update, move, assign, label and comment on cards. Mirage defines this command tree over the [Trello REST API](https://developer.atlassian.com/cloud/trello/rest/); every command prints normalized JSON for `jq`. ## Setup Create an API key and token using [Trello setup](/home/setup/trello). ```typescript theme={null} import { TRELLO, Workspace } from '@struktoai/mirage-node' const config = { apiKey: '...', apiToken: '...' } const ws = new Workspace({}) ws.registerCli('trello', TRELLO, config) ``` No service mount is required. For YAML and multiple accounts, see the [CLI overview](/typescript/cli/index#register-a-cli). ## Supported commands Run `trello <command> --help` for the supported flags and operands. This list is generated from Mirage's registered command tree. | Command | Description | | - | - | | `trello board list` | List the boards in scope as JSON | | `trello board show` | Get one board by ID | | `trello board members` | List a board's members | | `trello list list` | List a board's lists | | `trello label list` | List a board's labels | | `trello card list` | List the cards in a list | | `trello card show` | Get one card by ID | | `trello card comments` | List a card's comments | | `trello card create` | Create a new card | | `trello card update` | Update an existing card | | `trello card move` | Move a card to a different list | | `trello card assign` | Assign a member to a card | | `trello card label` | Add a label to a card | | `trello card unlabel` | Remove a label from a card | | `trello card comment` | Add a comment to a card | | `trello card comment-update` | Update an existing comment | ## Find work ```bash theme={null} trello board list trello board show brd_001 trello board members brd_001 trello list list brd_001 trello label list brd_001 trello card list lst_001 trello card show crd_001 trello card comments crd_001 ``` Reads take a board, list or card ID as a positional operand. The [Trello VFS](/typescript/setup/trello) embeds each ID after the last `__` of a directory or file name. ## Update cards ```bash theme={null} trello card create --list_id lst_001 --name "Fix login" --desc "Details here" cat brief.md | trello card create --list_id lst_001 --name "Agent bug" trello card update --card_id crd_001 --name "Updated title" --due 2026-11-01 trello card update --card_id crd_001 --closed true trello card move --card_id crd_001 --list_id lst_002 trello card assign --card_id crd_001 --member_id mem_001 trello card label --card_id crd_001 --label_id lbl_001 trello card unlabel --card_id crd_001 --label_id lbl_001 trello card comment --card_id crd_001 --text "Looks good" trello card comment-update --card_id crd_001 --comment_id cmt_001 --text "Updated text" ``` Writes take every ID as a flag. A description or comment comes from `--desc` or `--text`, from the file `--desc_file` or `--text_file` names, or from stdin; `--desc ''` clears a description. `--closed true`, `1` or `yes` archives a card and any other value restores it. Each write prints the card or comment it changed. ## Scope, VFS and limits The CLI uses its own account config and needs no Trello mount. * `workspaceId` and `boardIds` narrow the CLI as they narrow the mount: `trello board list` shows only the boards in scope, and a board, list or card ID on a board outside them is refused before any read or write (`trello card show: card crd_009 is outside the configured scope`, exit 1). * `--desc_file` and `--text_file` read a workspace file through the session, from any mount the session can read. * A read-only Trello mount does not make the CLI read-only: the CLI consults no mount. Use command policy, such as a profile rule denying `trello card create`, to restrict writes. * API failures exit 1 with Trello's error. This is Mirage's Apache-2.0 command implementation for the REST API. No compatibility with a separate Trello CLI is claimed; the API link documents the service rather than an upstream CLI implementation. See [compatibility and licenses](/home/setup/clis#compatibility-and-licenses). # Cloudflare Quickstart Source: https://docs.mirage.strukto.ai/typescript/cloudflare-quickstart Run Mirage workspaces and the Mirage server API on Cloudflare Workers with @struktoai/mirage-cloudflare. `@struktoai/mirage-cloudflare` runs Mirage on Cloudflare Workers. A workspace runs in the Worker's own isolate: the shell, the commands built on Rust and, when a workspace names it, `python3` on [Monty](/typescript/runtime/python), all in one thread. The Worker needs `nodejs_compat` for Node's `buffer`, `crypto`, `path`, `process` and `util` modules. Wrangler loads Mirage's Rust module and Monty as compiled `WebAssembly.Module` imports. ## Install ```bash theme={null} npm install @struktoai/mirage-cloudflare npm install -D wrangler ``` ```toml wrangler.toml theme={null} name = "mirage" main = "src/worker.ts" compatibility_date = "2026-10-01" compatibility_flags = ["nodejs_compat", "no_handle_cross_request_promise_resolution"] [alias] "cpu-features" = "@struktoai/mirage-cloudflare/cpu_features" ``` The package serves a workspace's files into a [machine](/home/setup/machine/e2b) with `ssh2`, which tries the native `cpu-features` addon inside a `try`. A Worker cannot load a native addon, so the alias hands it the package's stub, which throws in its place. ## Run a workspace ```ts src/worker.ts theme={null} import { MountMode, RAMVFS, Workspace } from '@struktoai/mirage-cloudflare' export default { async fetch(request: Request): Promise<Response> { const { command } = (await request.json()) as { command: string } const ws = new Workspace( { '/data': new RAMVFS() }, { mode: MountMode.EXEC, runtimes: ['workspace', 'monty'], maxMemory: '32MB' }, ) try { const result = await ws.shell(command) return Response.json({ exit: result.exitCode, stdout: result.stdoutText }) } finally { await ws.close() } }, } ``` ```bash theme={null} npx wrangler dev curl -s localhost:8787 -d '{"command": "seq 1 100 | sort -rn | head -3"}' ``` `python3` runs on Monty in the isolate's own thread, where no timer can interrupt it, so Monty's own clock stops a run: at the line's time limit, which ends the line with exit 124, or after 30 seconds with `TimeoutError` if that comes first. A loop that never ends leaves the isolate free for the next line. `node` and `js` do not run on Cloudflare Workers. [QuickJS](/home/setup/runtime/quickjs) would run on the isolate's one thread, where a script that never calls the host, such as `for (;;) {}`, runs until Cloudflare's CPU limit ends the request while every workspace in the isolate waits, a Durable Object sharing it included. A config whose `runtimes` names `quickjs` is refused. For anything else from core, import its subpaths (`@struktoai/mirage-core/vfs/registry`), not its package root: the root also imports optional packages, such as Pyodide, that a Worker bundle cannot resolve. ## Serve the server API `createApp` answers the [HTTP](/home/access/http) routes, [MCP](/home/access/mcp) and [RPC](/home/access/rpc) as the [server](/typescript/access/server) does, over the workspaces the isolate holds: ```ts src/worker.ts theme={null} import { createApp } from '@struktoai/mirage-cloudflare' export default createApp({ maxWorkspaces: 8 }) ``` A workspace outlives the request that created it, so a later request finishes work an earlier one started; `no_handle_cross_request_promise_resolution` above lets it. It checks each request the way the server does, from the same `MIRAGE_AUTH_MODE`, `MIRAGE_AUTH_TOKEN` and `MIRAGE_JWT_*` [variables](/home/access/http#configure-authentication). Without a token or a JWT issuer it serves nothing, since a Worker's URL is public. ```toml wrangler.toml theme={null} [vars] MIRAGE_AUTH_MODE = "token" ``` ```bash theme={null} npx wrangler secret put MIRAGE_AUTH_TOKEN curl -s localhost:8787/v1/workspaces -H "Authorization: Bearer $MIRAGE_AUTH_TOKEN" \ -H 'content-type: application/json' \ -d '{"id": "demo", "config": {"mounts": {"/": {"vfs": "ram"}}, "runtimes": ["workspace", "monty"]}}' curl -s localhost:8787/v1/workspaces/demo/shell -H "Authorization: Bearer $MIRAGE_AUTH_TOKEN" \ -H 'content-type: application/json' -d '{"command": "python3 -c \"print(6 * 7)\""}' ``` | Option | Meaning | | - | - | | `auth` | An `AuthConfig` in place of the env variables: `{ mode: 'token', bearerToken }`, or `{ mode: 'jwt', jwt }`. | | `maxWorkspaces` | The most workspaces the isolate holds at once. A create past it answers 503. | | `maxSessions` | The most sessions each workspace holds, `4` unless set, since every workspace shares the isolate's memory. A new session past it answers 429. | | `maxMemory` | The most any workspace's `max_memory` reaches, as a [size](/home/configuration#sizes). | | `maxProcesses` | The most any session's `processes.max` reaches. | | `maxLineSeconds` | The most seconds any line runs, whatever `@line` a config or profile sets. | | `maxEnv` | The most any workspace's `max_env` reaches, as a [size](/home/configuration#sizes). | | `policies` | The server's own [policies](/home/access/http#server-policies). | | `snapshotStore` | An `S3Config`: the store a snapshot request may name a key in. | `/v1/workspaces/:id/codex-exec` serves Codex's exec-server over a WebSocket, as the server does, so `codex exec-server forward` runs its tools in a workspace on the Worker. ## Keep a workspace's files A Worker's memory goes with its isolate. To keep a workspace's files and sessions, put them in SQL: [`SqlVFS`](/typescript/setup/sql) over a Durable Object's own storage or a D1 database, and `SqlWorkspaceStateStore` over the same driver for each session's working directory, variables and functions, its jobs, and the lines and processes it ran. Pass the Durable Object's own id as `daemonId`, so a Durable Object woken again takes its workspace back at once. One database holds one filesystem, so a Durable Object per workspace gives each workspace its own. It does not give each its own memory: Cloudflare may run several Durable Objects of one class in one isolate, where they share its 128 MB and run one at a time. ```ts theme={null} import { DurableObjectSqlDriver, SqlVFS, SqlWorkspaceStateStore, Workspace } from '@struktoai/mirage-cloudflare' const driver = new DurableObjectSqlDriver(this.ctx.storage) const ws = new Workspace( { '/work': new SqlVFS(driver) }, { workspaceId: 'w1', store: new SqlWorkspaceStateStore(driver), ownsStore: true, daemonId: this.ctx.id.toString(), }, ) ``` ## Mounts and CLIs Mounts: * `ram`, `github`, `gdrive`, `gdocs`, `gsheets`, `gslides`, `gcal`, `gmail`, `onedrive`, `sharepoint`, `box`, `airtable`, `linear`, `trello`, `langfuse`, `wandb`, `mem0`, `dify`, `slack`, `discord`, `notion`, `dropbox`, `jaeger`, `databricks_volume`, `tidb_filesystem`, `hf_models`, `hf_datasets`, `hf_spaces` * `s3`, `r2`, `gcs`, `minio`, `ceph`, `seaweedfs`, `wasabi`, `backblaze`, `digitalocean`, `tencent`, `aliyun`, `scaleway`, `qingstor`, `oci`, `supabase`, without `proxy` * `qdrant`: install `@qdrant/js-client-rest` * `postgres`: install `pg` * `redis`: any Redis over TCP, Upstash included, at a `redis://` or `rediss://` url, through Cloudflare's `connect()` * `email`: install `imapflow`, `mailparser` and `nodemailer` `chroma` does not run on Cloudflare. CLIs: `airtable`, `discord`, `gh`, `git`, `gws`, `hf`, `himalaya`, `linear`, `mcp`, `ntn`, `search`, `slack`, `trello`. ## Limits * A Worker's isolate has 128 MB of memory and no disk, shared by every workspace it runs, whether the server API holds them or each has its own Durable Object. Set `max_memory` on each workspace so a large write fails with `Disk quota exceeded`, and a command's output held for its redirect with `line: memory exhausted`, before the isolate runs out. * The server API's workspaces live in the isolate's memory. A request routed to another isolate does not see them, a write to a running line's stdin included, and they are gone when the isolate is evicted. `store.type` must be `ram`. A workspace built in code keeps its files and sessions in SQL, as [above](#keep-a-workspaces-files). * Network rules judge each request by host name: the isolate never sees the address a name reaches, so a `denied_domains` entry naming an address or a range is refused, and jwt mode's block on cloud metadata addresses covers only a request made to the address itself. * SSH, FUSE, policy and script files read by path, and runtimes or CLIs loaded by a `source:Class` reference are the Node server's alone. Codex's exec-server runs here over its WebSocket. # Installation Source: https://docs.mirage.strukto.ai/typescript/install Install the Mirage TypeScript SDK and add the optional native peers only if you need them. ## Quick Install For Node applications, use Node 22.20+ on Node 22, 24.12+ on Node 24, or 25+. Install the Node package: ```bash theme={null} pnpm add @struktoai/mirage-node ``` This ships the base runtime (Workspace, RAM VFS, Disk VFS, the shell executor) and is enough to follow the [TypeScript Quickstart](/typescript/quickstart). The packages use ECMAScript modules (ESM). In your application directory, set `"type": "module"` in `package.json` before importing them: ```bash theme={null} npm pkg set type=module ``` `npm install` and `yarn add` work identically; examples below use pnpm because the FUSE binding's install script needs pnpm's `onlyBuiltDependencies` allow-list. ## Optional Peer Dependencies Mirage keeps native and network-heavy dependencies as **optional peers** so consumers who don't use those features don't pay the download or build cost. Mirage imports each library lazily, so unused peers cost nothing at runtime either. Install a peer with `pnpm add <package>` when you use the feature that needs it: | Feature | Packages | Needed for | | - | - | - | | FUSE | `@zkochan/fuse-native@^0.1.0` | Mounting a workspace as an OS filesystem; see the [FUSE setup](/typescript/setup/fuse). | | Redis | `redis@^5.0.0` | `RedisVFS`, the Redis file and index cache stores, and the Redis session store. | | Postgres | `pg@^8.13.0` | `PostgresVFS`. | | MongoDB | `mongodb@^6.10.0` | `MongoDBVFS` and `GridFSVFS`. | | LanceDB | `@lancedb/lancedb@^0.30.0` | `LanceDBVFS`. | | Qdrant | `@qdrant/js-client-rest@^1.18.0` | `QdrantVFS`. | | Chroma | `chromadb@^3.4.3` | `ChromaVFS`. | | SSH | `ssh2@^1.16.0` | `SSHVFS`, the `ssh` machine, `mountType` `ssh` and `both`, and the SFTP mount. | | Email | `imapflow@^2.10.0`, `mailparser@^3.12.4`, `nodemailer@^10.1.4` | `EmailVFS` (IMAP read, MIME parsing) and sending mail with `himalaya` (SMTP). | | OpenDAL | `opendal@^0.49.4` | `HfBucketsVFS` and `NextcloudVFS`. | | Python runtimes | `pyodide@^0.29.0 \|\| ^314.0.0`, `@pydantic/monty@^1.4.0` | The Pyodide and Monty runtimes behind `python3`. | | Cloud machines | `e2b@^2.62.0`, `@daytonaio/sdk@^0.227.0` | The `e2b` and `daytona` machines. | | 1Password | `@1password/sdk@^0.5.0` | The `1password` secret source. | The FUSE binding also needs pnpm's `onlyBuiltDependencies` allow-list and, on macOS, the macFUSE 4+ symlink workaround described in the [TypeScript FUSE setup](/typescript/setup/fuse). For a browser application, install `@struktoai/mirage-browser` instead and follow the [browser quickstart](/typescript/browser-quickstart). ## Install From Source Contributing to Mirage or exploring the examples directly: ```bash theme={null} git clone https://github.com/strukto-ai/mirage.git cd mirage/typescript pnpm install pnpm -r build ``` The examples in `examples/typescript/` link to the workspace packages via pnpm's workspace protocol, so changes in `packages/core` or `packages/node` are picked up on the next `pnpm build`. # Limitations Source: https://docs.mirage.strukto.ai/typescript/limitations Runtime-specific constraints in the TypeScript SDK (Node and Browser) and how to work around them. Most of Mirage's behavior is identical across Python and TypeScript. The two TS runtimes (Node and Browser) each impose a handful of constraints, most of which don't exist in Python (the one shared design property, size-unknown stat, is included because it is the most common surprise). All are documented here so you can plan around them before they surprise you in production. > [!NOTE] > > `python3` has its own set of WASM-runtime-level divergences. See the > [TypeScript runtime reference](/typescript/runtime/python#pyodide) for the > worker, filesystem, socket, and containment details. ## Node versions The Node SDK and packages that use it require Node `^22.20 || ^24.12 || >=25`, matching the [XZ streaming codec](https://www.npmjs.com/package/@napi-rs/lzma) shipped with the SDK. Node 20, 23, and early Node 22/24 releases are outside that range. The runtime-agnostic core and browser packages do not acquire this Node requirement. ## Shell traps (Python, Node and Browser) `trap 'commands' EXIT` (or `0`) registers cleanup for the shell that ends. It runs at `exit`, in the frame that called it, so a function's locals and `$1` are still in scope. It also runs when a child shell ends (`bash -c`, a script, `( ... )`, a pipeline stage, `$( )`, a background job) or when `set -e` or a fatal expansion error ends the shell. `$?` starts at the ending status. The status stays that unless the cleanup calls `exit N` or fails under `set -e`. `trap -p` lists the registration, `trap - EXIT` removes it and `trap '' EXIT` turns cleanup off. A subshell lists its parent's registration but runs only one it registers itself. `bash` and `sh` start with none. `trap 'commands' ERR` runs after a command fails where `set -e` would end the shell: not in an `if`/`while`/`until` test, on the left of `&&`/`||` or after `!`, and not again for the group, loop or `case` whose command already ran it. `$?` is the failed status while it runs and after it. `trap 'commands' RETURN` runs as a function or a sourced file returns. A function neither runs nor lists its caller's `ERR` and `RETURN` actions unless `set -E` / `set -T`, and gives them back when it returns unless it set its own; a child shell keeps listing them but runs neither. `exec CMD` replaces the shell, so its actions go with it. A workspace session persists across `shell()` calls, so a call that returns does not fire `EXIT`. Register the cleanup inside `bash -c` when it has to finish before the call returns. Registrations are live shell state: session stores do not keep them. `trap` cannot catch a signal. Cancellation, `kill`, timeouts, and stopping or closing a workspace or a session end the work without running cleanup, and they interrupt cleanup that is already running (bash runs `EXIT` on a `SIGTERM`). `trap` refuses every other event (`INT`, `TERM`, `DEBUG`, ...) as `bash: line 1: trap: TERM: not supported`, and `trap -l` the same way. ## Background job output (Python, Node and Browser) A background job writes where the shell that started it writes, as it writes, so its lines and the foreground's come out in the order they were written, as in bash. `wait` prints none of a job's output, and `fg` prints only the job's command line. A `shell()` call returns whatever reached the session's virtual terminal while the line ran. A job that writes after the call has returned has no line to show it, so that output waits and comes first in the next call on the session; bash prints it right away. With `sink`, the output goes to the console while a line runs, and between lines it waits the same way. `$( )` and every pipeline stage but the last wait for the jobs they start, as bash reads a pipe until every writer has closed it. Inside `$( )`, `jobs` still lists the caller's jobs, but `wait` and `kill` reach only its own. `bash -c` sees only its own jobs. ## Node ### 1. `patchNodeFs` only patches CJS `require('fs')`, not ESM named imports **The problem.** `patchNodeFs()` routes `fs` calls on mounted paths through the workspace so that third-party libraries "just work" against them. It swaps the functions on the CommonJS `fs` object and on `fs.promises`. ESM is different: * `import { readFile } from 'node:fs/promises'` binds the function when the module links. * There is no public hook to replace that binding after the fact. * Loader hooks (`--loader=…`) could intercept the resolution, but they're a build-time decision, not a runtime monkey-patch. **What this means in practice.** ```ts theme={null} // ✅ Works, this is CJS and goes through require('fs') const fs = require('fs') patchNodeFs(ws) await fs.promises.readFile('/data/x.txt') // routes through the RAM VFS // ❌ Does not work, an ESM named import bypasses the patch import { readFile } from 'node:fs/promises' patchNodeFs(ws) await readFile('/data/x.txt') // hits the real filesystem, throws ENOENT ``` A sync form (`fs.readFileSync`, `fs.statSync`) refuses a mounted path, since the workspace answers asynchronously. Paths outside every mount keep Node's own behavior in every form. **Why Python doesn't hit this.** Python has no equivalent concept of "ESM vs CJS". `with Workspace() as ws:` swaps `builtins.open`, the `os` module's functions and `shutil.rmtree` in place: one set of mutable globals, one patch point, works for every caller. **Workarounds.** > [tab] Use FUSE instead > > If you want ESM-imported `node:fs` to see your mounted data, expose the workspace as a real filesystem. Mount FUSE, then every `fs` call, ESM or CJS, goes through the kernel. > > ```ts theme={null} > import { readFile } from 'node:fs/promises' > const ws = new Workspace({ '/data': new Mount(new RAMVFS(), { backend: MountBackend.FUSE }) }) > await ws.fuseReady() > // The `/data` subtree is exposed at the mountpoint root, so paths are relative to it. > const bytes = await readFile(`${ws.fuseMountpoint}/x.txt`) > ``` > [tab] Use Mirage's VFS API directly > > The most reliable approach: call `ws.shell()` or the VFS methods. No magic, no monkey-patching, works from ESM or CJS. > > ```ts theme={null} > const res = await ws.shell('cat /data/x.txt') > const bytes = res.stdout > ``` > [tab] Restrict your code to CJS > > If you really need `fs` patching to work, keep the consuming code in CJS. Note that most modern Node projects default to ESM, so this is a narrow escape hatch. > > ```js theme={null} > // package.json: no "type": "module" > const { readFileSync } = require('fs') > ``` **Possible future fix.** A published Node loader hook that resolves `node:fs` through the workspace would remove the ESM limitation, at the cost of forcing consumers to opt into the loader (`node --loader @struktoai/mirage-node/loader main.mjs`). Not planned currently. *** ### 2. The FUSE mount is served by your process's event loop **The problem.** `@zkochan/fuse-native` dispatches every FUSE request (`getattr`, `read`, …) as a callback on the mounting process's Node event loop. Any *synchronous* access to your own mountpoint from that same process (`readFileSync`, `statSync`, `execFileSync('cat', …)`) blocks the loop that must answer the request: the call deadlocks, the kernel eventually times the filesystem out, and later operations fail with `Device not configured` / `ENOTCONN`. ```ts theme={null} const ws = new Workspace({ '/data': new Mount(new RAMVFS(), { backend: MountBackend.FUSE }) }) await ws.fuseReady() const mp = ws.fuseMountpoint // ✅ async APIs interleave with the FUSE callbacks await readFile(`${mp}/x.txt`) await promisify(execFile)('cat', [`${mp}/x.txt`]) // ❌ sync APIs deadlock the mount this process is serving readFileSync(`${mp}/x.txt`) execFileSync('cat', [`${mp}/x.txt`]) ``` **Why Python doesn't hit this.** Python's FUSE loop runs on a dedicated thread, so the main thread can block on the mount freely. **Workarounds.** Use async `fs` APIs and async subprocess spawns from the mounting process, or dedicate a child process to owning the mount (see `examples/typescript/fuse/helper.ts` for the pattern). External processes (a program on a machine, another terminal, your shell) are unaffected — the constraint only binds the process that created the mount. *** ### 3. Size-unknown API files stat as 0 bytes until first open **The behavior.** API-backed mounts (Trello, Linear, Slack, MongoDB, …) return `stat.size = null` because the byte size isn't known until the API has been called. Over the FUSE mount these files behave like Linux `/proc` files: they stat as **0 bytes until first open**, and become fully readable the moment anything opens them. Mirage mounts with `direct_io` (the kernel reads to EOF regardless of the reported size; `@zkochan/fuse-native` doesn't expose the option, so Mirage appends it to the mount option string itself) and `attr_timeout=0` (post-open `fstat` returns the real size of the now-fetched content, kept warm in a 30-second cache). What that means per tool: | Tools | Behavior | | - | - | | `cat`, `grep`, `head`, `cp`, `md5sum`, `sed`, `sort` | correct content, always | | `wc -c`, `tail -c` | correct (they fstat after open, which serves the real size) | | `ls -l`, `du`, `find -size`, `test -s` | report 0 until the file has been opened recently | | `tar`, `rsync`, `scp` | see 0 at stat time and copy empty content, exactly like `tar` over `/proc`; read the file first or use `cat`/`cp` based flows | Mirage never reports a fake size and never fetches content during `stat`: returning real sizes eagerly would fire one API call per file on every `ls -l`. Earlier TS versions instead reported a fake 100 MiB size with zero-padded reads (`JSON.parse` of a FUSE-read file failed on the padding); that sentinel is gone and reads are byte-exact. **Why Python behaves the same.** Unlike the other entries on this page, this one is not TS-specific: it is a design property of API-backed mounts, and Python's FUSE layer has identical semantics (see [Python FUSE setup](/python/setup/fuse#size-semantics-for-api-backed-files)). It is listed here because the stat-time zeros are the most common FUSE surprise in practice. *** ## Browser The browser SDK runs entirely in-page: no kernel, no subprocesses, no Node `fs`. That removes the Node sections above (neither FUSE nor `patchNodeFs` apply) but introduces its own constraints. ### 1. No FUSE Browsers can't mount filesystems. The browser `Workspace` takes plain mounts: there is no `Mount` backend option and no `addFuseMount`. Use `ws.shell(...)` (virtual executor) and `ws.vfs.read`/`write` instead. Every builtin (`cat`, `grep`, `jq`, `awk`, etc.) is reimplemented in-process, so most agent code paths work unchanged from Node; `python3` runs on Pyodide (see below). ### 2. OPFS quotas and persistence `OPFSVFS` writes through the [Origin Private File System](https://web.dev/articles/origin-private-file-system). Two things to know: * **Storage quota.** The browser sets per-origin quotas (typically a fraction of free disk, single-digit GB on most setups). Hitting it raises `QuotaExceededError`. Call `navigator.storage.estimate()` to inspect. * **Eviction.** Origins that aren't [persisted](https://web.dev/articles/persistent-storage) can be cleared by the browser under storage pressure. For long-lived workspaces, request `navigator.storage.persist()` early. ### 3. CORS for HTTP-backed VFS Mounts that hit third-party APIs (S3, GitHub, Linear, etc.) make `fetch` calls from the page. Anything not configured to allow your origin via CORS will fail with the usual browser error. Workarounds: * **Browser-native auth flows.** mounts like Box, Dropbox, GDrive, GDocs ship PKCE OAuth examples that work entirely in-browser. * **Pre-signed URLs.** For S3/R2/GCS, generate pre-signed URLs server-side and pass them in. The Mirage browser examples include a Vite dev-server `presigner` plugin as reference. * **Same-origin proxy.** Stand up a tiny proxy on your own domain that forwards to the upstream API with the right auth headers. ### 4. Pyodide caches accessed files for each run Pyodide's worker fetches workspace files on access and caches them for that execution. An external edit to a cached file is not visible until the next run. Without workers, or with neither `SharedArrayBuffer` nor Mirage's service worker, `python3` in a workspace exits 127 rather than copy every mount in before each run. See [worker and browser setup](/typescript/runtime/python#worker-and-browser-setup) for browser requirements and [file access](/typescript/runtime/python#files) for its limitations. ### 5. Some VFS drivers remain Node-only SSH, LanceDB, Email, Disk, GridFS, Nextcloud, and the Hugging Face mounts are only exposed by `@struktoai/mirage-node` because their drivers need Node APIs or raw TCP. Databricks Volumes and Jaeger use HTTP but are not exported by `@struktoai/mirage-browser` yet. Importing any of them from `@struktoai/mirage-browser` is a build error. Postgres and MongoDB do have browser implementations: * Postgres uses `NeonPgDriver` over HTTP. * MongoDB uses `HttpMongoDriver` and an HTTP proxy such as the bundled mongo-proxy example. Those HTTP drivers still need a browser-reachable endpoint with the correct CORS policy. They are not drop-in replacements for raw Postgres or MongoDB socket connections. *** ## Quick reference | Scenario | Runtime | Status | | - | - | - | | `patchNodeFs()` with `require('fs')` (CJS) | Node | ✅ works | | `patchNodeFs()` with `import from 'node:fs'` (ESM) | Node | ❌ silently bypassed; use FUSE or the VFS API | | FUSE `cat`/`readFile` of API-backed size-unknown files | Node | ✅ works (stats 0 until opened, like `/proc`) | | `tar`/`rsync` of an unopened size-unknown file | Node | ❌ copies 0 bytes (stat-only tools; same in Python) — read the file first or use `cp` | | Synchronous access to your own mount from the mounting process | Node | ❌ deadlocks; use async APIs or a child process | | `ws.shell(...)` virtual builtins | Browser | ✅ works | | `Workspace` with a fuse `Mount` | Browser | ❌ not supported; the browser `Workspace` takes plain mounts | | OPFS reads/writes within quota | Browser | ✅ works | | OPFS over quota | Browser | ❌ `QuotaExceededError`; check `navigator.storage.estimate()` | | HTTP-backed mounts without CORS allow-list | Browser | ❌ blocked; use PKCE, presigned URLs, or a same-origin proxy | | Python `open()` writes back through mount | Browser | ✅ with workers and `SharedArrayBuffer` or the service worker | | Postgres through `NeonPgDriver` | Browser | ✅ over HTTP; endpoint must allow the browser origin | | MongoDB through `HttpMongoDriver` | Browser | ✅ through an HTTP proxy; direct MongoDB sockets are unavailable | | Node-only VFS types (SSH, LanceDB, Email, Disk, Hugging Face, GridFS, Nextcloud, FUSE) | Browser | ❌ Node APIs or raw TCP required | | Databricks Volumes, Jaeger | Browser | ❌ not exported by the browser package yet | The Node limitations are runtime-level, not Mirage design decisions. Python's equivalent behavior is strictly better in each case, so if a workflow absolutely requires ESM-level `fs` patching or large API-backed FUSE reads, consider whether the Python SDK fits better for that specific piece. The Browser limitations are by design (no kernel, no subprocess), so the workarounds there are about choosing the right runtime for the task. ## CPU-bound builtin processing Line readers, cache drains, and `wc` processing periodically yield to the event loop. Large RAM files and warm cache reads therefore allow host timers and I/O callbacks to run. `Workspace.shell(command, { signal })` forwards caller cancellation to builtin input processing; Python provides the corresponding `cancel=asyncio.Event()` path and task cancellation. File-cache fingerprints use incremental MD5: the Node package installs native hashing with 64 KiB updates, while browser/core uses JavaScript block batches. Both yield on a time budget; Python uses incremental `hashlib` updates. These checkpoints are cooperative, not a hard execution-time bound. A synchronous regex call, native sort, whole-buffer allocation, or individual hash chunk can still occupy the thread until that operation returns. Custom handlers must observe cancellation themselves. Embeddings requiring isolation from arbitrary CPU work should run the workspace in a separate worker or process. Queued calls have not started execution: cancelling one removes its waiter immediately, even while the preceding call is still blocked. Once a call starts, cancellation is cooperative and usually leaves backend writes in place; [conditional S3 file moves](/typescript/setup/s3) may attempt rollback. Cancellation itself has one seam. Python runs the whole line as one task, cancels it and joins it, so every await in the line unwinds before `execute` raises; the line's own flush and history record get the same 250 ms grace after the cancel and are cancelled too if a store holds them past it. A JavaScript promise cannot be cancelled, so TypeScript fires the signal, joins the tree for a short grace (250 ms) while responsive leaves close their producers and settle, then releases the caller. `execute` always rejects with an `AbortError` whose `cause` is the signal's reason. A leaf that does not observe the signal within the grace (a custom handler, a backend call with no signal parameter) keeps running in the background until it settles on its own; its output is dropped and it cannot change `$?` (the status entry point refuses a statement that settles after the release), but any write it completes still lands on the backend. A handler that loops over operands reaches its backend through slots (a generic-bound command such as `rm`, `cp` or `mkdir`) or through the dispatcher (a namespace-routed one such as `chmod`, `touch` or `rm` of a link), and both refuse to start once the signal has fired, so a released line begins no further read or write between operands; only a custom handler that reaches its backend directly can. Python's cancelled task never reaches the next operand, and a Python handler or store must let `CancelledError` propagate: one that swallows both deliveries holds `execute` until it returns, as it would hold `asyncio.wait_for`, and a warning is logged while it does. A caller cancelled from outside (`asyncio.wait_for` around `execute`) gets the same grace as the event. Loading workspace state, parsing, routing, the fetch of a managed variable's secret, the history record and the session flush are raced against the signal as well, so a stalled state store or secret source cannot hold the caller either. A line is recorded in history once it has been parsed; an abort that lands while workspace state is still loading records nothing, in both languages. A command timeout is the line's own answer (exit 124), never an abort of the invocation: neither language writes the caller's signal or event. A background job, and every line it evaluates, runs without the caller's signal or event; only `kill` reaches it. The cancellation boundary is caller completion, not proof that every custom handler has stopped. TypeScript retains the evaluation and its owned parser programs until the command tree settles, even after the grace releases the caller. An uncooperative mount handler can keep running after that tree settles. An embedding that needs a hard stop for arbitrary handlers must provide process or worker isolation. ## Streaming resource bounds Named gzip/gunzip/zgrep, `iconv -o`, archive commands, deferred redirects and script output, external sort, split/csplit and record reordering use incremental I/O or replayable scratch storage. Known-size tar members can emit immediately; unknown-size members must be spooled before writing their headers. ZIP updates copy unchanged compressed members, but archive indexing and updates still read the existing archive in full. They do not yet use remote range reads to fetch only the central directory or selected members. Streaming bounds payload memory in supported host packages; it does not make every algorithm constant-memory. A single large record, archive metadata, AWK arrays, regex `tac`, `diff`/`patch` and `jq --slurp` retain their algorithmic working data. Whole-byte results still collect output. The standard `rg` engine on Python, Node and Browser limits requested scratch storage for each search to 64 MiB. This covers both state tables, their capture rows, start and candidate capture slots, and the closure stack. Compiled expressions, input, emitted matches and captures, printer output, and allocator overhead are outside that limit. Ordinary search retains only whole-match captures. Replacement templates containing `$` conservatively retain all capture groups when the selected output uses replacement. A pattern whose scratch storage would exceed the limit is refused before searching. `--regex-size-limit` controls compilation separately and does not raise the search scratch limit. Native write paths cover disk, SSH, OPFS, GridFS and the upload-session APIs for Drive, Dropbox, OneDrive, SharePoint and Box. Uploads that require a length or replay stage their input first. Provider sessions are cleaned up where the API supports it; this is not a durable upload-resume service across process restarts. S3 uses 8 MiB multipart parts, with a 10,000-part limit (about 78.1 GiB with this fixed part size). Presigned uploads and conditional writes to custom S3 endpoints retain a single PUT, backed by scratch storage and limited to 5 GiB. Store-native append is unavailable on S3: it still downloads and uploads the object again. Async I/O lets another request run while an operation waits. Compression and comparison still consume CPU; spooling adds local I/O. Reductions in peak memory or time to first output do not imply an equal increase in server throughput or lower cloud network bills. ### Measured command-level costs The mirrored Python implementations were measured with Python 3.12.11 on macOS, using three isolated runs over a 128 MiB deterministic binary input. Each probe consumes output without collecting it. These are median tracked Python allocations (`tracemalloc`), not process RSS or TypeScript measurements; the baseline measured implementations match main at `866615ceb7`. | Operation | Peak allocations before → after | First 64 KiB before → after | Total before → after | | - | - | - | - | | Named gzip | 512.13 → 0.54 MiB | 2,016 → 1.36 ms | 2,064 → 2,225 ms | | Tar, known member size | 263.74 → 0.28 MiB | 160.68 → 0.31 ms | 209 → 173 ms | | Tar, unknown size | 263.74 → 1.21 MiB | 160.68 → 217.73 ms | 209 → 489 ms | | Default streamed cache fill | 256.24 → 8.13 MiB | 0.09 → 0.07 ms | 137 → 103 ms | Output SHA-256 values matched before and after. Named gzip's maximum event-loop lag fell from 1,877 ms to 4.88 ms in the same probe. Its total compression time did not improve. Unknown-size tar incurs scratch I/O and remains slower than collecting the input; a known size avoids that staging. The cache result also changes admission: the 128 MiB file is no longer cached with the default fill budget, so repeated reads can cost more backend I/O. Run from the repository root: ```bash theme={null} PYTHONPATH=python python/.venv/bin/python scripts/benchmark_streaming.py gzip_file ``` Other modes are `gzip_stdin`, `tar_current` (with `--known-size` to skip staging), `cache_default`, `cache_8mib` and `cache_0`. `--mib` changes the input size. For the previous reader contract, run the same script with the previous source tree on `PYTHONPATH` and `--whole-read` for named gzip and tar. Whole-result workspace APIs collect their output, so their final result memory is outside this streaming probe. # TypeScript Quickstart Source: https://docs.mirage.strukto.ai/typescript/quickstart Create a Mirage TypeScript workspace, mount RAM as a virtual filesystem, and run shell commands with @struktoai/mirage-node. ## Installation Use a [supported Node release](/typescript/install#quick-install), then install the runtime: ```bash theme={null} pnpm add @struktoai/mirage-node pnpm add -D tsx typescript ``` `npm install @struktoai/mirage-node` and `yarn add @struktoai/mirage-node` work too. The packages require ECMAScript modules (ESM). In the same directory, set `"type": "module"` in your `package.json`: ```bash theme={null} npm pkg set type=module ``` ## Create a Workspace Start with the RAM VFS so you can try Mirage without credentials. ```ts quickstart.ts theme={null} import { MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node' async function main(): Promise<void> { const ws = new Workspace({ '/data': new RAMVFS() }, { mode: MountMode.WRITE }) await ws.shell(`echo '{"name": "alice"}' > /data/user.json`) const files = await ws.shell('ls /data') process.stdout.write(files.stdoutText) const name = await ws.shell('jq -r ".name" /data/user.json') process.stdout.write(name.stdoutText) const match = await ws.shell('grep alice /data/user.json') process.stdout.write(match.stdoutText) await ws.close() } main() ``` Run it; it lists `user.json`, prints `alice`, then prints the matching JSON document: ```bash theme={null} pnpm tsx quickstart.ts ``` Shell failures are returned in the result; check `exitCode` and `stderrText` when needed. See the [in-app API reference](/typescript/access/in-app#session-shell). ## Next Steps * See [TypeScript Installation](/typescript/install) for optional native peers (FUSE, Redis, Postgres, MongoDB, SSH, Email). * Building for the browser? Start with the [Browser Quickstart](/typescript/browser-quickstart). * Configure [command output limits](/home/core/output-limits) for large files and long-running commands. * Browse [TypeScript Agents](/typescript/agents/index) to wire Mirage into OpenAI Agents SDK, Vercel AI SDK, LangChain, Mastra, and more. * Pick a real backend from the VFS section, such as [S3](/typescript/setup/s3), [Slack](/typescript/setup/slack), or [Discord](/typescript/setup/discord). # Runtimes Source: https://docs.mirage.strukto.ai/typescript/runtime/python What only the TypeScript SDK has for runtimes, Pyodide details, browsers, managing runtimes in code, and child processes. Setup and behavior of every runtime are on the [Runtimes](/home/setup/runtime/overview) pages. This page covers what is specific to the TypeScript SDK. ## Differences from the Python SDK * **Monty:** each run executes in a crash-isolated worker, from one pool of four that every workspace in the process shares. `os.chdir()` raises `RuntimeError`; use `cd` in the shell or the run's `ctx.cwd`. `os.stat()` has only the named fields (`st.st_size`). * **QuickJS:** a `std` and `os` shim with the calls the [QuickJS](/home/setup/runtime/quickjs) table lists. A write shows to other commands once the file is flushed or closed, or the run ends. A timeout stops the run, and the engine caps a run at 64 MiB of memory and 1 MiB of stack. * **Local:** in `@struktoai/mirage-node` only. With neither `home` nor `MIRAGE_LOCAL_HOME`, `python3` is the one on `PATH`. * **Machines:** in `@struktoai/mirage-node`; `e2b` also runs in browsers. `mountType` `ssh` and `both` need the `ssh2` package; a browser serves no files into a machine. The `ssh` machine authenticates through `SSH_AUTH_SOCK` when there is no `identityFile`, and `username` defaults to the local user. * **Config objects** are camelCase in code (`sandboxId`, `mountType`); YAML spells the same keys in snake\_case. * **Pyodide** is in the TypeScript SDK only; WASI is in the Python SDK only. Runtime output uses the normal `Workspace.shell()` result: `stdout` and `stderr` are `Uint8Array`; use `stdoutText` and `stderrText` when you want decoded strings. ## Pyodide ### Scripts and flags * Each command and one-shot evaluation starts a fresh interpreter, so imports do not carry over; files on the mounts do. A console session keeps its own interpreter. * A script runs as in CPython: `__file__` is absolute, tracebacks quote its lines, and `sys.path[0]` is its directory. `-P` leaves that entry off, and for `-c` and stdin omits the working directory entry. `sys_path` entries stay either way. * `-P`, `-O`/`-OO` and `-B` show in a read-only `sys.flags`. `-O` and `-OO` compile imported modules from source. Flags and import paths reset when the command ends, errors included. * An installed Python CLI gets bare `argv` (its name at index 0) and `stdin` (bytes, or `None`), as on Monty; Pyodide also keeps `sys.argv` and `sys.stdin`. * Standard streams support text and `.buffer` I/O, but do not expose native OS file descriptors. ### Files * Native packages such as PIL and NumPy reach the same mounts as `open()`. * A file is fetched on first access and cached for the run; edits made elsewhere during the run are not seen. * A create, delete, rename, mkdir, chmod or truncate reaches the mount when the call is made, and a write when the file is closed, so a refusal fails that call with the mount's errno. Writes still open at the end land then; a failure there exits nonzero with a message. Concurrent writes are not conflict-checked. * A path no mount serves answers `ENOTSUP` to `os.getxattr`. * A console keeps its own `os.chdir()`, even through an exception; if its directory disappears, the next input fails, resets the working directory to `/` and keeps the variables. * Mount files under a prefix such as `/data`: a mount at `/` cannot replace Pyodide's own filesystem, which holds its standard library. ### Worker and browser setup Pyodide runs in a worker, which Node needs no setup for. In a browser, the page needs one of two things: * **Cross-origin isolation:** the page is served with `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp`. * **Mirage's service worker**, on any other page: copy `node_modules/@struktoai/mirage-browser/dist/pyodide-sw.js` to the folder your site serves at its root, and register it before the first `python3`: ```ts theme={null} const container = navigator.serviceWorker await container.register('/pyodide-sw.js') if (container.controller === null) { const controlled = new Promise((resolve) => { container.addEventListener('controllerchange', resolve, { once: true }) }) ;(await container.ready).active?.postMessage('claim') await controlled } ``` The service worker answers only the file calls of Pyodide and QuickJS, which runs in a worker the same way, and lets every other request through. The check after `register` covers a first visit and a hard reload, which both leave the page uncontrolled. Service workers need HTTPS or `localhost`. A site that already has a service worker adds the bridge to it instead: call `importScripts('/pyodide-sw.js')` at the top of that worker (`import '/pyodide-sw.js'` in a module worker) and register it in place of `/pyodide-sw.js`. With neither, `python3` and `node` exit 127 and say why. JSPI is not needed. In a browser, Pyodide loads from its CDN unless `home` names another place, such as a folder on your site holding the `pyodide` package's files (`home: '/pyodide/'`). Mirage starts its workers from `blob:` URLs, so a Content-Security-Policy needs `blob:` in `worker-src`, and `https://cdn.jsdelivr.net` in `script-src` and `connect-src` while Pyodide loads from the CDN. ### Concurrency and timeouts * `max_concurrency` (default 1) bounds active top-level commands, one-shot evaluations and inputs to distinct consoles; extra calls wait. Calls in one shell session stay ordered; give independent work its own session with `ws.createSession(id)` and `{ sessionId: id }`. Nested subprocesses bypass the limit. In a browser the limit stays 1, so commands from every session take turns; a second `Workspace` runs alongside the first. * A timeout raises `KeyboardInterrupt` in the program, even in a busy loop. That needs `SharedArrayBuffer`. Without it, a workspace command's worker is stopped instead, and a standalone run on the main thread blocks the event loop until it ends. ### Sockets `connect` and `sendto` raise `ENETUNREACH`, and `listen`, a UDP `bind` and `socket.socketpair()` raise `ENETDOWN`, so `urllib.request.urlopen` fails fast. Compare against `errno.ENETUNREACH`, not a number: the values are Emscripten's. `socket.socket()`, a TCP `bind` and name lookups still answer. An `init_module` that calls `useNodeSockFS()` installs real sockets. ### Containment Guest Python can run JavaScript in its worker through Pyodide. On Node with `module.registerHooks`, Mirage hardens the worker after interpreter setup and before guest execution: * Further module loads are refused, including `import('node:child_process')` and imports of already loaded Node modules. * Host globals (`process`, `global`, `fetch`, `WebSocket`, and an injected `require`) are removed. * Exposed host filesystem and socket APIs are disabled, including `mountNodeFS`, `mountNativeFS`, `useNodeSockFS`, `NODEFS`, and host file preloading. Binary reads are restricted to configured local distribution and package directories, with traversal and symlink escape checks. Automatic package loading still works from a local distribution. After the seal, network package loading and CDN fallback are unavailable. Packages listed in `packages` and trusted `bootstrap_code` run during initialization, before the seal. An `init_module` opts into host access (`reach: process`), so its worker is left unsealed. Node releases without `module.registerHooks`, including Node 20 and Node 22 before 22.15, also run unsealed; use them only for trusted code. Standalone SDK execution without a workspace can run on the main thread and is trusted-only. Workspace-backed execution requires a worker. Browser workers are left unsealed: JavaScript can still use `fetch` and module loading, subject to the page's Content Security Policy. Each command gets its own worker. These measures close known host access paths. They do not make arbitrary JavaScript safe: Pyodide exposes mutable interpreter internals, and a worker thread shares the host process. For hostile code, use a [machine](/home/setup/machine/overview) with a process and kernel boundary. ### Child processes `subprocess` runs Mirage commands: ```python theme={null} import subprocess result = subprocess.run(["printf", "%s", "hello"], capture_output=True, text=True, check=True) print(result.stdout) ``` * Supported: `run`, `call`, `check_call`, `check_output`, `Popen` with live pipes, `poll`, `wait`, `communicate`, termination, timeout retries, text mode, `stderr=STDOUT`, and `shell=True` through the workspace's `sh`. * `sys.executable` is `/usr/bin/python3`, and `shutil.which` sees the profile's programs. Functions and shell builtins are not programs. * The environment is inherited unless `env` replaces it. Writes land before each process call, and file caches reset after it. * A timed-out `wait` or `communicate` leaves the child running; `run` kills it. Children still running when the program ends are cancelled. * Not supported: native descriptors, PTYs, process groups, user switching, `preexec_fn`, `asyncio.create_subprocess_exec` and signal handlers. An unsupported option fails with an error. ### Configuration The package keys are on the [Pyodide](/home/setup/runtime/pyodide#packages) page. The others: | Key (YAML) | Meaning | | - | - | | `home` | Where the distribution loads from. Without it, `MIRAGE_PYODIDE_HOME`, then the installed package in Node or the pinned CDN in browsers. | | `max_concurrency` | Active top-level calls, default 1. | | `lock_file_url` | A custom `pyodide-lock.json`. | | `bootstrap_code` | Python run when each interpreter starts. | | `init_module` | A trusted host module whose default export receives Pyodide before `bootstrap_code`, and may return a cleanup. | `init_module` runs per command or evaluation and once per console, inside the worker. It has host privileges, so keep it in deployment config: `POST /v1/workspaces` rejects it, and setting it gives the runtime host access. Only an in-process shutdown calls its cleanup. ## E2B in browsers Import the E2B machine from core (`pnpm add @struktoai/mirage-core`), which also registers the `e2b` provider for `machines:`, and pass `apiKey`: ```ts theme={null} import { E2BMachine } from '@struktoai/mirage-core/machine/e2b/handle' ``` Keep account keys out of shared frontend bundles; have your backend authenticate the app. `mountType` `ssh` and `both` need Node, so a browser uses `fuse` or none. ## Managing runtimes in code `new Workspace(mounts, { runtimes: [...] })` takes names and runtime objects, and adds `workspace` when the list leaves it out. On a live workspace, `addRuntime` appends an entry (a `remote` runtime goes after the last one listed, else ahead of Monty and QuickJS), `removeRuntime` takes one out, and `runtimes()` lists them: ```ts theme={null} await ws.removeRuntime('monty') ws.addRuntime('pyodide') ``` `python3` moves to the new runtime at once. A running line finishes before its removed runtime closes, a removed instance cannot be added again, and `workspace` cannot be removed. `registerRuntime(name, cls)` makes your own runtime class available by name in YAML. The `@external` capture is also exported as `EXTERNAL_COMMANDS`. A machine subclass that overrides `loadSdk()` imports the SDK type from the provider's `sdk` module. The E2B one needs `pnpm add @struktoai/mirage-core`: ```ts theme={null} import type { E2bSdk } from '@struktoai/mirage-core/machine/e2b/sdk' import type { DaytonaSdk } from '@struktoai/mirage-node/machine/daytona/sdk' import type { Ssh2Sdk } from '@struktoai/mirage-node/machine/ssh/sdk' ``` ## Child processes A host application starts a program through the same admitted entry point as the shell. ```ts theme={null} const child = ws.spawn({ argv: ['cat'] }) const result = await child.communicate(new TextEncoder().encode('hello\n')) ``` # Airtable Source: https://docs.mirage.strukto.ai/typescript/setup/airtable Mount Airtable bases, tables, and records as a Mirage filesystem. `AirtableVFS` exposes the bases a personal access token can reach as a read-only tree of tables, records, and saved views. Reads go through the Airtable Web API with plain `fetch`, so one class serves Node and the browser. Setup steps for the token live at [Airtable Credentials](/home/setup/airtable). ## Node ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { AirtableVFS, MountMode, Workspace } from '@struktoai/mirage-node' const airtable = new AirtableVFS({ token: process.env.AIRTABLE_TOKEN! }) const ws = new Workspace({ '/airtable': airtable }, { mode: MountMode.READ }) await ws.shell('ls /airtable/bases/') ``` ## Browser ```bash theme={null} pnpm add @struktoai/mirage-browser ``` ```ts theme={null} import { AirtableVFS, MountMode, Workspace } from '@struktoai/mirage-browser' const airtable = new AirtableVFS({ token: AIRTABLE_TOKEN }) ``` The Airtable API sends `access-control-allow-origin: *`, so the browser calls it directly; a token in a page is visible to that page's user. ## Config | Field | Description | | - | - | | `timeout` 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. | | `token` required, secret | Personal access token (or OAuth access token), sent as `Authorization: Bearer`. | | `baseIds` | Only these bases are listed or readable. Unset shows every base the token can reach. | | `baseUrl` default `'https://api.airtable.com/v0'` | Airtable API root; override to point at a fake or proxy. | | `maxReadRecords` default `10000` | The most records one file renders. A full read of a larger table or view fails with `File too large` once it passes the cap; `head -n N` still reads its first records. | | `requestsPerSecond` default `5` | Requests per second per base. Airtable allows 5 and answers a burst with a 30-second penalty. | Fields marked secret are redacted in snapshots. ## Mount mode `read`. Writes go through the [airtable CLI](/typescript/cli/airtable), which takes the same config and names a base, a table and a record by the id after the last `__` of the mount's directory names. For the mounted layout (`bases/`, `table.json`, `records.jsonl`, `views/`) and the reading rules see the [Python Airtable docs](/python/vfs/airtable). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Airtable mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `airtable`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > bases/ > <base-name>__<base-id>/ > base.json # base id, name, permission, tables > <table-name>__<table-id>/ > table.json # typed fields (with options), views > records.jsonl # one record per line > views/ > <view-name>__<view-id>.jsonl # records the view shows, in order > ``` > > * `ls` a directory first to find exact names: the name part of a segment > is sanitized, the id after the last `__` is exact. > * A `records.jsonl` line is a normalized record: `record_id`, > `created_time` and `fields`, keyed by field name with values as > Airtable returns them. `table.json` gives each field's type. > * Airtable omits empty cells, so a missing key means empty, a `false` > checkbox included. A link field is a list of record ids; an attachment > URL expires two hours after it was read. > * `records.jsonl` lists in the API's own order; a view file applies the > view's filter and sort. > * A file over `max_read_records` records stops with `File too large` > after that many, while `head -n N` fetches just N records. > * The `airtable` CLI, if installed, reaches what a file cannot: > server-side filters (`airtable record list --formula` or `--view`), one > record by id (`airtable record get`) and comments > (`airtable comment list`). > > ```sh theme={null} > head -n 20 /<path>/bases/<base>/<table>/records.jsonl | jq .fields > ``` > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep` and `rg` ask `airtable` for the matching lines. `head` asks `airtable` instead of reading a file. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `airtable`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > bases/ > <base-name>__<base-id>/ > base.json # base id, name, permission, tables > <table-name>__<table-id>/ > table.json # typed fields (with options), views > records.jsonl # one record per line > views/ > <view-name>__<view-id>.jsonl # records the view shows, in order > ``` > > - `ls` a directory first to find exact names: the name part of a segment > is sanitized, the id after the last `__` is exact. > - A `records.jsonl` line is a normalized record: `record_id`, > `created_time` and `fields`, keyed by field name with values as > Airtable returns them. `table.json` gives each field's type. > - Airtable omits empty cells, so a missing key means empty, a `false` > checkbox included. A link field is a list of record ids; an attachment > URL expires two hours after it was read. > - `records.jsonl` lists in the API's own order; a view file applies the > view's filter and sort. > - A file over `max_read_records` records stops with `File too large` > after that many, while `head -n N` fetches just N records. > - The `airtable` CLI, if installed, reaches what a file cannot: > server-side filters (`airtable record list --formula` or `--view`), one > record by id (`airtable record get`) and comments > (`airtable comment list`). > > ```sh > head -n 20 /<path>/bases/<base>/<table>/records.jsonl | jq .fields > ``` > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep` and `rg` ask `airtable` for the matching lines. `head` asks `airtable` instead of reading a file. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ```` ## Integration What Airtable answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Airtable | | - | - | | `grep`, `rg` on one file | A `filterByFormula` fetches only the records that may match | | `head -n N` | Fetches N records | The [Python Airtable docs](/python/vfs/airtable#integration) list when each search answers and what it can miss. # Alibaba OSS Source: https://docs.mirage.strukto.ai/typescript/setup/aliyun Set up Alibaba Cloud OSS as a MIRAGE VFS from Node or the browser. Alibaba Cloud OSS exposes an S3-compatible API with AWS Signature V4 against `https://s3.oss-<region>.aliyuncs.com`. MIRAGE derives this endpoint from your region automatically. Credentials (RAM `AccessKey ID` and `AccessKey Secret`) are created the same way in both runtimes, see [Alibaba OSS Credentials](/home/setup/aliyun). ## Node (server-side) ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { AliyunVFS, MountMode, Workspace } from '@struktoai/mirage-node' const oss = new AliyunVFS({ bucket: process.env.OSS_BUCKET!, region: process.env.OSS_REGION!, accessKeyId: process.env.OSS_ACCESS_KEY_ID!, secretAccessKey: process.env.OSS_ACCESS_KEY_SECRET!, }) const ws = new Workspace({ '/bucket/': oss }, { mode: MountMode.READ }) const res = await ws.shell('ls /bucket/') console.log(res.stdoutText) ``` ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `accessKeyId` secret | Access key ID; set it with `secretAccessKey`. Unset uses the AWS SDK credential chain. | | `secretAccessKey` secret | Secret access key paired with `accessKeyId`. | | `sessionToken` secret | Session token for temporary credentials, sent with the access key pair. | | `profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `forcePathStyle` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `keyPrefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `timeout` 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. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | | `region` required | Provider region every request is signed for. Most providers also build their endpoint URL from it unless `endpoint` is set. | | `endpoint` | Endpoint URL that replaces the one the provider derives. | Fields marked secret are redacted in snapshots. ## Browser (presigned URLs) ```bash theme={null} pnpm add @struktoai/mirage-browser ``` The browser `AliyunVFS` is secret-free, your backend signs each operation using your RAM keys and returns a URL. OSS's S3-compatible endpoint accepts AWS Signature V4, so `@aws-sdk/s3-request-presigner` works, pointed at the OSS endpoint. ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `presignedUrlProvider` required, secret | Function `(path, operation, options)` that returns a signed URL for each S3 operation; your server signs it, so the browser holds no keys. | | `region` | Region of the bucket. Most providers derive the endpoint from it; requests go to the host each presigned URL names. | | `endpoint` | Endpoint URL that replaces the one the provider derives. Requests go to the host each presigned URL names; the mount uses it to name its storage location. | | `defaultContentType` default `'application/octet-stream'` | `Content-Type` stored with every object the mount writes. | | `keyPrefix` | Key prefix the mount treats as its root. The browser can change it before a URL is signed, so enforce the prefix on the signing server. | | `timeout` 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. | Fields marked secret are redacted in snapshots. ### 1. Server: sign URLs with the OSS endpoint ```ts theme={null} import { CopyObjectCommand, DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client, } from '@aws-sdk/client-s3' import { getSignedUrl } from '@aws-sdk/s3-request-presigner' const REGION = process.env.OSS_REGION! const client = new S3Client({ region: REGION, endpoint: `https://s3.oss-${REGION}.aliyuncs.com`, credentials: { accessKeyId: process.env.OSS_ACCESS_KEY_ID!, secretAccessKey: process.env.OSS_ACCESS_KEY_SECRET!, }, }) const BUCKET = process.env.OSS_BUCKET! app.post('/presign/oss', async (req, res) => { const { path, op, opts } = req.body const key = path.replace(/^\/+/, '') const ttl = typeof opts?.ttlSec === 'number' ? opts.ttlSec : 300 let cmd switch (op) { case 'GET': cmd = new GetObjectCommand({ Bucket: BUCKET, Key: key }); break case 'PUT': cmd = new PutObjectCommand({ Bucket: BUCKET, Key: key, ContentType: opts?.contentType }); break case 'HEAD': cmd = new HeadObjectCommand({ Bucket: BUCKET, Key: key }); break case 'DELETE': cmd = new DeleteObjectCommand({ Bucket: BUCKET, Key: key }); break case 'LIST': cmd = new ListObjectsV2Command({ Bucket: BUCKET, Prefix: opts?.listPrefix, Delimiter: opts?.listDelimiter, ContinuationToken: opts?.listContinuationToken, }); break case 'COPY': cmd = new CopyObjectCommand({ Bucket: BUCKET, Key: key, CopySource: `${BUCKET}/${opts?.copySource}`, }); break } res.json({ url: await getSignedUrl(client, cmd, { expiresIn: ttl }) }) }) ``` ### 2. Browser: wire it up ```ts theme={null} import { AliyunVFS, MountMode, Workspace } from '@struktoai/mirage-browser' const oss = new AliyunVFS({ bucket: 'my-bucket', region: 'cn-hangzhou', presignedUrlProvider: async (path, op, opts) => { const r = await fetch('/presign/oss', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path, op, opts }), }) const { url } = await r.json() return url }, }) const ws = new Workspace({ '/bucket/': oss }, { mode: MountMode.READ }) ``` > [!TIP] > > `region` on the browser config is only used for display/logging; the actual endpoint is baked into the presigned URLs your backend returns. ### 3. CORS Configure CORS rules in the Alibaba Cloud console: OSS -> your bucket -> **Content Security** -> **CORS**. Allow your dev/production origins with methods `GET, PUT, HEAD, DELETE, POST`, allowed headers `*`, and expose headers `ETag, Content-Length, Content-Type, Last-Modified`. See the [Alibaba OSS VFS](/python/vfs/aliyun) docs for the equivalent Python wiring. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Alibaba OSS mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Integration What Aliyun OSS answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Aliyun OSS | | - | - | | `find`, `du`, `ls -R`, `tree` | One recursive listing | # Backblaze B2 Source: https://docs.mirage.strukto.ai/typescript/setup/backblaze Set up Backblaze B2 as a MIRAGE VFS from Node or the browser. Backblaze B2 uses the S3 API with AWS Signature V4 against `https://s3.<region>.backblazeb2.com`. MIRAGE derives this endpoint from your region automatically. Credentials (B2 application key, the `keyID` is the access key and the `applicationKey` is the secret) are created the same way in both runtimes, see [Backblaze B2 Credentials](/home/setup/backblaze). ## Node (server-side) ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { BackblazeVFS, MountMode, Workspace } from '@struktoai/mirage-node' const b2 = new BackblazeVFS({ bucket: process.env.B2_BUCKET!, region: process.env.B2_REGION!, accessKeyId: process.env.B2_ACCESS_KEY_ID!, secretAccessKey: process.env.B2_SECRET_ACCESS_KEY!, }) const ws = new Workspace({ '/bucket/': b2 }, { mode: MountMode.READ }) const res = await ws.shell('ls /bucket/') console.log(res.stdoutText) ``` ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `accessKeyId` secret | Access key ID; set it with `secretAccessKey`. Unset uses the AWS SDK credential chain. | | `secretAccessKey` secret | Secret access key paired with `accessKeyId`. | | `sessionToken` secret | Session token for temporary credentials, sent with the access key pair. | | `profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `forcePathStyle` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `keyPrefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `timeout` 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. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | | `region` required | Provider region every request is signed for. Most providers also build their endpoint URL from it unless `endpoint` is set. | | `endpoint` | Endpoint URL that replaces the one the provider derives. | Fields marked secret are redacted in snapshots. ## Browser (presigned URLs) ```bash theme={null} pnpm add @struktoai/mirage-browser ``` The browser `BackblazeVFS` is secret-free, your backend signs each operation using your B2 application key and returns a URL. B2 accepts AWS Signature V4, so `@aws-sdk/s3-request-presigner` works, pointed at the B2 endpoint. ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `presignedUrlProvider` required, secret | Function `(path, operation, options)` that returns a signed URL for each S3 operation; your server signs it, so the browser holds no keys. | | `region` | Region of the bucket. Most providers derive the endpoint from it; requests go to the host each presigned URL names. | | `endpoint` | Endpoint URL that replaces the one the provider derives. Requests go to the host each presigned URL names; the mount uses it to name its storage location. | | `defaultContentType` default `'application/octet-stream'` | `Content-Type` stored with every object the mount writes. | | `keyPrefix` | Key prefix the mount treats as its root. The browser can change it before a URL is signed, so enforce the prefix on the signing server. | | `timeout` 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. | Fields marked secret are redacted in snapshots. ### 1. Server: sign URLs with the B2 endpoint ```ts theme={null} import { CopyObjectCommand, DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client, } from '@aws-sdk/client-s3' import { getSignedUrl } from '@aws-sdk/s3-request-presigner' const REGION = process.env.B2_REGION! const client = new S3Client({ region: REGION, endpoint: `https://s3.${REGION}.backblazeb2.com`, credentials: { accessKeyId: process.env.B2_ACCESS_KEY_ID!, secretAccessKey: process.env.B2_SECRET_ACCESS_KEY!, }, }) const BUCKET = process.env.B2_BUCKET! app.post('/presign/b2', async (req, res) => { const { path, op, opts } = req.body const key = path.replace(/^\/+/, '') const ttl = typeof opts?.ttlSec === 'number' ? opts.ttlSec : 300 let cmd switch (op) { case 'GET': cmd = new GetObjectCommand({ Bucket: BUCKET, Key: key }); break case 'PUT': cmd = new PutObjectCommand({ Bucket: BUCKET, Key: key, ContentType: opts?.contentType }); break case 'HEAD': cmd = new HeadObjectCommand({ Bucket: BUCKET, Key: key }); break case 'DELETE': cmd = new DeleteObjectCommand({ Bucket: BUCKET, Key: key }); break case 'LIST': cmd = new ListObjectsV2Command({ Bucket: BUCKET, Prefix: opts?.listPrefix, Delimiter: opts?.listDelimiter, ContinuationToken: opts?.listContinuationToken, }); break case 'COPY': cmd = new CopyObjectCommand({ Bucket: BUCKET, Key: key, CopySource: `${BUCKET}/${opts?.copySource}`, }); break } res.json({ url: await getSignedUrl(client, cmd, { expiresIn: ttl }) }) }) ``` ### 2. Browser: wire it up ```ts theme={null} import { BackblazeVFS, MountMode, Workspace } from '@struktoai/mirage-browser' const b2 = new BackblazeVFS({ bucket: 'my-bucket', region: 'us-west-004', presignedUrlProvider: async (path, op, opts) => { const r = await fetch('/presign/b2', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path, op, opts }), }) const { url } = await r.json() return url }, }) const ws = new Workspace({ '/bucket/': b2 }, { mode: MountMode.READ }) ``` > [!TIP] > > `region` on the browser config is only used for display/logging; the actual endpoint is baked into the presigned URLs your backend returns. ### 3. CORS B2 manages CORS through its **native API**, not the S3 `PutBucketCors` call. Set CORS rules in the Backblaze web console (Bucket Settings -> CORS Rules) or with the `b2` CLI: ```bash theme={null} b2 bucket update my-bucket \ --cors-rules '[{"corsRuleName":"mirage","allowedOrigins":["http://localhost:5173","https://app.example.com"],"allowedOperations":["s3_get","s3_put","s3_head","s3_delete","s3_post"],"allowedHeaders":["*"],"exposeHeaders":["etag","content-length","content-type","last-modified"],"maxAgeSeconds":3000}]' ``` See the [Backblaze VFS](/python/vfs/backblaze) docs for the equivalent Python wiring. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Backblaze B2 mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Integration What Backblaze B2 answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Backblaze B2 | | - | - | | `find`, `du`, `ls -R`, `tree` | One recursive listing | # Box Source: https://docs.mirage.strukto.ai/typescript/setup/box Mount Box as a MIRAGE VFS from Node or the browser via OAuth2. Mirage ships `BoxVFS` in **two runtimes**: * `@struktoai/mirage-node`, uses `client_id` + `client_secret` + refresh token (rotated on each use) * `@struktoai/mirage-browser`, supports the same refresh token via PKCE (no client secret in the bundle) Both runtimes hit the same [Box v2 API](https://developer.box.com/reference/) endpoints (`/folders/{id}/items`, `/files/{id}/content`, `/search`, plus multipart upload, folder create, delete, rename/move, and copy for writes). Credentials are obtained the same way in both runtimes, see [Box Credentials](/home/setup/box). Both `READ` and `WRITE` modes are supported (mount with `{ mode: MountMode.WRITE }` to enable `tee`/`cp`/`mv`/`rm`/`mkdir`/`touch`). Pass `rootFolderId` to mount a single Box folder as the workspace root instead of the whole account; folder ids are stable across renames and moves. The Python package ships the same backend, see [Box (Python)](/python/vfs/box). ## Quick start: developer token For exploration, skip the OAuth flow and use a developer token (one-button-click in the Box app console, 60-minute lifetime). The `BoxVFS` accepts an `accessToken` field that short-circuits the refresh logic: ```ts theme={null} import { BoxVFS, MountMode, Workspace } from '@struktoai/mirage-node' const box = new BoxVFS({ accessToken: process.env.BOX_DEVELOPER_TOKEN!, }) const ws = new Workspace({ '/box': box }, { mode: MountMode.READ }) await ws.shell('ls /box/') ``` When the token expires (Box 401s with `invalid_token`), regenerate it in the console and re-run. See [Box Credentials -> Quick Start](/home/setup/box#quick-start-developer-token-60-minutes-no-oauth). ## Service account (client credentials, no refresh token) For headless server auth, skip OAuth and refresh tokens entirely. Create a Box app with the **Server Authentication (Client Credentials Grant)** method, authorize it once in the Box admin console (**Apps -> Custom Apps Manager**), and pass the enterprise ID: ```ts theme={null} const box = new BoxVFS({ clientId: process.env.BOX_CLIENT_ID!, clientSecret: process.env.BOX_CLIENT_SECRET!, enterpriseId: process.env.BOX_ENTERPRISE_ID!, }) ``` Tokens are minted for the app's **service account** and re-fetched automatically on expiry; there is no refresh token to rotate or persist. > [!WARNING] > > The service account is a separate Box user with its own (initially empty) root folder. To see > your content, share folders with the service account's email address, shown under the app's > **General Settings** in the developer console. ## Node (server-side, long-running) ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import fs from 'node:fs/promises' import { BoxVFS, MountMode, Workspace } from '@struktoai/mirage-node' const box = new BoxVFS({ clientId: process.env.BOX_CLIENT_ID!, clientSecret: process.env.BOX_CLIENT_SECRET!, refreshToken: process.env.BOX_REFRESH_TOKEN!, // Box rotates the refresh token; persist the new one if you want to survive restarts. onRefreshTokenRotated: async (next) => { await fs.writeFile('.box-refresh', next, 'utf-8') }, }) const ws = new Workspace({ '/box': box }, { mode: MountMode.READ }) const res = await ws.shell('ls /box/') console.log(res.stdoutText) ``` The `BoxTokenManager` caches the access token in memory (5-minute safety buffer before expiry) and rotates the refresh token on every refresh. Without `onRefreshTokenRotated`, the rotation is in-memory only and a process restart needs a fresh refresh token. ### Config | Field | Description | | - | - | | `timeout` 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. | | `endpoint` | Base URL that replaces Box's API, upload and OAuth token hosts, such as a test server. Unset uses Box's hosts. | | `rootFolderId` default `'0'` | Box folder ID the mount uses as its root, from the folder's web URL (`box.com/folder/<id>`); unlike a path it survives renames and moves. `0` is the account root. | | `clientId` | Box app client ID. Required with `refreshToken` (OAuth) or with `clientSecret` and `enterpriseId` (client credentials). | | `clientSecret` secret | Box app client secret. Required for client credentials; the OAuth refresh sends it when set, so a PKCE client can omit it. | | `refreshToken` secret | OAuth refresh token; needs `clientId`. Box rotates it on every refresh, so persist the new one with `onRefreshTokenRotated`. | | `enterpriseId` | Box enterprise ID for the client-credentials grant. With `clientId` and `clientSecret`, tokens are minted for the app's service account and no refresh token is involved. | | `accessToken` secret | Box developer token, used as is with no refresh flow; it expires after about 60 minutes. It wins over every other credential. Also accepted as `developer_token`. | | `refreshFn` secret | Function that takes the current refresh token and returns `{ accessToken, refreshToken, expiresIn }`, called instead of Box's token endpoint. Needs `clientId` and `refreshToken`. | | `onRefreshTokenRotated` secret | Function (sync or async) given the new refresh token whenever a refresh rotates it, to persist it; the token it replaces stops working after its first use. | Fields marked secret are redacted in snapshots. ## Browser (PKCE, no client secret) ```bash theme={null} pnpm add @struktoai/mirage-browser ``` ```ts theme={null} import { BoxVFS, MountMode, Workspace } from '@struktoai/mirage-browser' // Refresh token obtained via the PKCE flow, see examples/browser/vfs/box/box_pkce.ts. const box = new BoxVFS({ clientId: import.meta.env.VITE_BOX_CLIENT_ID, refreshToken: localStorage.getItem('box-refresh')!, onRefreshTokenRotated: (next) => localStorage.setItem('box-refresh', next), }) const ws = new Workspace({ '/box': box }, { mode: MountMode.READ }) await ws.shell('ls /box/') ``` Box requires the origin to be allowlisted on the app's **Allowed Origins** config (see [setup](/home/setup/box#cors-notes)). The bundled [`examples/browser/vfs/box/box_pkce.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/browser/vfs/box/box_pkce.ts) runs the full PKCE dance and persists the rotated refresh token to `localStorage`. ## VFS mode (`patchNodeFs`) ```ts theme={null} import { createRequire } from 'node:module' import { BoxVFS, MountMode, patchNodeFs, Workspace } from '@struktoai/mirage-node' const require = createRequire(import.meta.url) const fs = require('fs') as typeof import('fs') const box = new BoxVFS({ accessToken: process.env.BOX_DEVELOPER_TOKEN! }) const ws = new Workspace({ '/box': box }, { mode: MountMode.READ }) const restore = patchNodeFs(ws) const entries = await fs.promises.readdir('/box/') const stat = await fs.promises.stat('/box/Documents') const bytes = await fs.promises.readFile('/box/Documents/example.json') restore() ``` The async forms (`fs.promises.*` and the callbacks) are routed; a sync form like `fs.statSync` refuses a mounted path. ## FUSE mode ```ts theme={null} import { BoxVFS, Mount, MountBackend, MountMode, Workspace } from '@struktoai/mirage-node' const box = new BoxVFS({ accessToken: process.env.BOX_DEVELOPER_TOKEN! }) const ws = new Workspace({ '/box': new Mount(box, { mode: MountMode.READ, backend: MountBackend.FUSE }) }) await ws.fuseReady() const mp = ws.fuseMountpoint // The box subtree is exposed at the mountpoint root, so ${mp}/ is a real path: // ls ${mp}/ // find ${mp} -type f // cat ${mp}/example.json | jq . await ws.close() ``` Requires [macFUSE](https://osxfuse.github.io/) on macOS or libfuse on Linux. ## Path → ID resolution Box uses numeric folder/file IDs internally (root folder is id `0`). Mirage caches the path → ID mapping in the mount's index store (RAM unless an `index:` is configured). The first time you `ls /box/foo/bar/`, it walks the tree top-down (one API call per level) and caches each entry's ID. Subsequent reads of `/box/foo/bar/anyfile.json` hit the cache instead of re-walking. With no `index:` configured, listings live for the mount's `ttl` (600 s by default), at most 24 hours; a configured `index:` uses its own `ttl`, still capped by the mount's `ttl:`. To force re-resolution, unmount the prefix and mount a new `BoxVFS` there. ## Writes A write records the `sha1` its upload reply names, so a `fresh` read right after a `tee` or `sed -i` downloads nothing. ## Conditional writes A rewrite that observes a missing file requires atomic create-only support, which this backend does not currently enable. Appending to a missing file therefore returns an unsupported-operation error under either write policy. An intentional write with `>` can create the file, and subsequent appends to that existing file retain the selected policy. A Box mount accepts `write: conditional`. A write or a file delete compares the `sha1` mirage holds with the one the folder listing it walks anyway shows, and refuses a file changed since it was read before sending anything; the request then carries the file's `etag` as `If-Match`, so Box refuses (412) a change that lands in between. A conditional write costs no request more than a plain one. `rm -r` walks the folder file by file, and a `mv` within the mount is Box's own move, which is not refused when its source changed (a `mv` to another mount is a copy and a conditioned delete, so there a changed source stays and `mv` reports the failed removal). ## Reads under `fresh` A Box mount accepts `read: fresh`. The token is the file's `sha1`, which a folder listing and `GET /files/{id}` both carry; a download names no version, so a whole read stamps the listed `sha1` only when the downloaded bytes hash to it, and a ranged read stamps nothing. On a `write: conditional` mount a whole read stamps the `sha1` of the bytes it downloaded, so a listing another client has since outdated cannot leave the next write without the version the agent read. `modified_at` is never the token: two same-size edits in one second share it. Checking a cached file costs one request, `GET /files/{id}` by the id the mount last listed, while the mount still holds that file's listing row. The answer is trusted only when Box places the same active file at the same path from the mount root; a file that was moved, renamed, trashed or recreated falls back to listing each folder from the mount root, one listing per level (up to two per level when the file is gone). When that fallback confirms byte-identical content, the built-in RAM and Redis indexes retain the newly resolved file row if the original hint is still current. A later check then uses the recovered id without refreshing the parent listing. Custom indexes must implement `replaceIfUnchanged` to retain this row; otherwise later checks repeat the fallback walk. A persistent 403 still requires the failed point request and a listing walk on each check. Any stale, unknown or gone verdict on the mount drops its cached listings, so the checks after one walk until a cold read or an `ls` lists the folders again. A file Box reports without a `sha1` cannot be verified: each fresh read of it downloads it again and drops the mount's cached listings. A folder's `etag` does not move when its children change, so under `fresh` listings are re-fetched once per command. Repeated uses within that command share the result; outside commands, the existing one-second listing trust window applies. Before fetching a nested listing, mirage resolves its folder through current parent listings up to the configured mount root. A folder moved away and replaced under the same name is therefore resolved to the replacement on the next fresh command. This costs one listing per ancestor level; a warm file check still uses one metadata request. ## Box-native file types Every Box item is served as its **raw bytes**, keeping its real name (no `.json` suffix). Box has no API to edit these formats from a structured payload, so Mirage does not render them, it hands back exactly what Box stores: * `.boxnote` / `.boxcanvas`, Box's native Notes and Canvas, stored as ProseMirror-style JSON. They are text, so `cat foo.boxnote | jq .` works if you want to poke at the structure. * `.gdoc` / `.gsheet` / `.gslides`, Box's V2 Google-format files, stored as Office Open XML zips (`.docx` / `.xlsx` / `.pptx`). These are opaque binary, like any other Office document on a Mirage mount. For a rich, editable view of Google-format documents, mount them through [Google Drive](/home/setup/google) with Google credentials instead, the `gws docs ...` commands operate on Google file IDs and do not apply to Box. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Box mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `box`, write | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > <folder>/ # the Box folder hierarchy, mirrored > <name>.boxnote # Box Note: raw ProseMirror-style JSON > <name>.boxcanvas # Box Canvas: raw canvas JSON > <name>.gdoc # Box's Google Workspace files, stored as > <name>.gsheet # Office Open XML (docx, xlsx, pptx): > <name>.gslides # opaque binary > <file> # PDFs, images and the rest: raw bytes > ``` > > * Every item is served as its raw bytes; pipe the JSON ones to `jq`. > * This is a remote mount: prefer targeted reads over full scans. > * Box names folders by numeric id (the root is `0`). The path-to-id > mapping is cached, so a nested directory costs one API call per level > on first access. `ls` the parent before constructing a path. > > #### 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 `box` 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>` | `box`, write | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > <folder>/ # the Box folder hierarchy, mirrored > <name>.boxnote # Box Note: raw ProseMirror-style JSON > <name>.boxcanvas # Box Canvas: raw canvas JSON > <name>.gdoc # Box's Google Workspace files, stored as > <name>.gsheet # Office Open XML (docx, xlsx, pptx): > <name>.gslides # opaque binary > <file> # PDFs, images and the rest: raw bytes > ``` > > - Every item is served as its raw bytes; pipe the JSON ones to `jq`. > - This is a remote mount: prefer targeted reads over full scans. > - Box names folders by numeric id (the root is `0`). The path-to-id > mapping is cached, so a nested directory costs one API call per level > on first access. `ls` the parent before constructing a path. > > ## 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 `box` 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. > ```` ## Integration What Box answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Box | | - | - | | `grep -r`, `rg` | Box search, for whole words. It can miss Office files, PDFs, archives, the end of large files, words Box splits differently (`foo.bar`) and recent writes. | | `sha1sum` | The SHA-1 Box keeps, asked live | The [Python Box docs](/python/vfs/box#integration) list when each search answers and what it can miss. ## Available commands `BoxVFS` ships the same shell command set as `GoogleDriveVFS` and `DropboxVFS`: * **Filesystem**: `ls`, `cat`, `head`, `tail`, `nl`, `wc`, `stat`, `find`, `tree`, `du`, `file`, `realpath`, `basename`, `dirname` * **Writes** (in `WRITE` mode): `tee`, `cp`, `mv`, `rm` (`-r`), `mkdir` (`-p`), `touch`, `truncate` * **Search/text**: `grep`, `rg`, `awk`, `sed`, `sort`, `uniq`, `cut`, `diff`, `cmp`, `jq` * **Encoding**: `base64` ## Examples End-to-end runnable scripts are in [`examples/typescript/vfs/box/`](https://github.com/strukto-ai/mirage/tree/main/examples/typescript/vfs/box): * [`box.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/vfs/box/box.ts), `Workspace.shell('ls/stat/cat/tree …')` shell demo * [`box_vfs.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/vfs/box/box_vfs.ts), `patchNodeFs` + native `fs.promises.*` calls * [`box_fuse.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/vfs/box/box_fuse.ts), FUSE mount with shell access in another terminal # Ceph Source: https://docs.mirage.strukto.ai/typescript/setup/ceph Set up Ceph Rados Gateway as a MIRAGE VFS from Node or the browser. Ceph Rados Gateway (RGW) speaks the S3 API with AWS Signature V4 against your own gateway endpoint (e.g. `https://ceph.example.com`). RGW is self-hosted, so the endpoint is required and path-style addressing is used by default. Credentials (RGW user access key + secret key) are created the same way in both runtimes, see [Ceph Credentials](/home/setup/ceph). ## Node (server-side) ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { CephVFS, MountMode, Workspace } from '@struktoai/mirage-node' const ceph = new CephVFS({ bucket: process.env.CEPH_BUCKET!, endpoint: process.env.CEPH_ENDPOINT_URL!, accessKeyId: process.env.CEPH_ACCESS_KEY_ID!, secretAccessKey: process.env.CEPH_SECRET_ACCESS_KEY!, }) const ws = new Workspace({ '/bucket/': ceph }, { mode: MountMode.READ }) const res = await ws.shell('ls /bucket/') console.log(res.stdoutText) ``` ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `accessKeyId` secret | Access key ID; set it with `secretAccessKey`. Unset uses the AWS SDK credential chain. | | `secretAccessKey` secret | Secret access key paired with `accessKeyId`. | | `sessionToken` secret | Session token for temporary credentials, sent with the access key pair. | | `profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `forcePathStyle` default `true` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `keyPrefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `timeout` 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. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | | `region` default `'us-east-1'` | Region requests are signed for; the gateway's endpoint does not depend on it. | | `endpoint` required | URL of the self-hosted S3 gateway, such as `http://localhost:9000`. | Fields marked secret are redacted in snapshots. ## Browser (presigned URLs) ```bash theme={null} pnpm add @struktoai/mirage-browser ``` The browser `CephVFS` is secret-free, your backend signs each operation using your RGW keys and returns a URL. RGW accepts AWS Signature V4, so `@aws-sdk/s3-request-presigner` works, pointed at your gateway endpoint. ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `presignedUrlProvider` required, secret | Function `(path, operation, options)` that returns a signed URL for each S3 operation; your server signs it, so the browser holds no keys. | | `region` | Region of the bucket. Most providers derive the endpoint from it; requests go to the host each presigned URL names. | | `endpoint` | Endpoint URL that replaces the one the provider derives. Requests go to the host each presigned URL names; the mount uses it to name its storage location. | | `defaultContentType` default `'application/octet-stream'` | `Content-Type` stored with every object the mount writes. | | `keyPrefix` | Key prefix the mount treats as its root. The browser can change it before a URL is signed, so enforce the prefix on the signing server. | | `timeout` 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. | Fields marked secret are redacted in snapshots. ### 1. Server: sign URLs with the RGW endpoint ```ts theme={null} import { CopyObjectCommand, DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client, } from '@aws-sdk/client-s3' import { getSignedUrl } from '@aws-sdk/s3-request-presigner' const client = new S3Client({ region: 'us-east-1', endpoint: process.env.CEPH_ENDPOINT_URL, forcePathStyle: true, credentials: { accessKeyId: process.env.CEPH_ACCESS_KEY_ID!, secretAccessKey: process.env.CEPH_SECRET_ACCESS_KEY!, }, }) const BUCKET = process.env.CEPH_BUCKET! app.post('/presign/ceph', async (req, res) => { const { path, op, opts } = req.body const key = path.replace(/^\/+/, '') const ttl = typeof opts?.ttlSec === 'number' ? opts.ttlSec : 300 let cmd switch (op) { case 'GET': cmd = new GetObjectCommand({ Bucket: BUCKET, Key: key }); break case 'PUT': cmd = new PutObjectCommand({ Bucket: BUCKET, Key: key, ContentType: opts?.contentType }); break case 'HEAD': cmd = new HeadObjectCommand({ Bucket: BUCKET, Key: key }); break case 'DELETE': cmd = new DeleteObjectCommand({ Bucket: BUCKET, Key: key }); break case 'LIST': cmd = new ListObjectsV2Command({ Bucket: BUCKET, Prefix: opts?.listPrefix, Delimiter: opts?.listDelimiter, ContinuationToken: opts?.listContinuationToken, }); break case 'COPY': cmd = new CopyObjectCommand({ Bucket: BUCKET, Key: key, CopySource: `${BUCKET}/${opts?.copySource}`, }); break } res.json({ url: await getSignedUrl(client, cmd, { expiresIn: ttl }) }) }) ``` > [!WARNING] > > RGW uses **path-style** URLs (`forcePathStyle: true`), virtual-hosted style requires wildcard DNS on the gateway. ### 2. Browser: wire it up ```ts theme={null} import { CephVFS, MountMode, Workspace } from '@struktoai/mirage-browser' const ceph = new CephVFS({ bucket: 'my-bucket', endpoint: 'https://ceph.example.com', presignedUrlProvider: async (path, op, opts) => { const r = await fetch('/presign/ceph', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path, op, opts }), }) const { url } = await r.json() return url }, }) const ws = new Workspace({ '/bucket/': ceph }, { mode: MountMode.READ }) ``` > [!TIP] > > `endpoint` on the browser config is only used for display/logging; the actual endpoint is baked into the presigned URLs your backend returns. ### 3. CORS RGW supports the S3 `PutBucketCors` call, so the AWS CLI works against your gateway: ```bash theme={null} aws s3api put-bucket-cors --bucket "$CEPH_BUCKET" \ --endpoint-url "$CEPH_ENDPOINT_URL" \ --cors-configuration '{"CORSRules":[{"AllowedOrigins":["http://localhost:5173","https://app.example.com"],"AllowedMethods":["GET","PUT","HEAD","DELETE","POST"],"AllowedHeaders":["*"],"ExposeHeaders":["ETag","Content-Length","Content-Type","Last-Modified"]}]}' ``` See the [Ceph VFS](/python/vfs/ceph) docs for the equivalent Python wiring. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Ceph mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Integration What Ceph answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Ceph | | - | - | | `md5sum` | The object's ETag, when it is the MD5: a single-part upload, unencrypted or under SSE-S3 | | `find`, `du`, `ls -R`, `tree` | One recursive listing | # Chroma Source: https://docs.mirage.strukto.ai/typescript/setup/chroma Mount a ChromaDB collection as a Mirage filesystem in TypeScript, with shell commands and vector retrieval through the search CLI. `ChromaVFS` exposes a ChromaDB collection as a read-only filesystem: the directory tree comes from the collection's `__path_tree__` document, pages are chunk sets joined in `chunk_index` order, and vector retrieval is the [`search` CLI](/typescript/cli/search). The TypeScript backend mirrors the [Python one](/python/vfs/chroma) and returns identical results. ## Node The `chromadb` client is an optional peer dependency; install it alongside Mirage: ```bash theme={null} pnpm add @struktoai/mirage-node chromadb ``` ```ts theme={null} import { ChromaVFS, MountMode, SEARCH, Workspace } from '@struktoai/mirage-node' const knowledge = new ChromaVFS({ config: { host: 'localhost', port: 8000, collectionName: 'knowledge', // slugField: 'page_slug', (default) // chunkIndexField: 'chunk_index', (default) }, }) const ws = new Workspace({ '/knowledge': knowledge }, { mode: MountMode.READ }) ws.registerCli('search', SEARCH) console.log(await (await ws.shell('tree /knowledge/')).stdoutStr()) console.log(await (await ws.shell('grep -r refund /knowledge/policies/')).stdoutStr()) console.log( await (await ws.shell('search "how am I throttled" /knowledge/')).stdoutStr(), ) ``` `grep` pushes `$contains` / `$regex` filters down to ChromaDB before fine filtering locally, so recursive searches avoid fetching the whole collection. `search` takes `--top-k`, `--threshold` and `--method` as it does in [Python](/python/vfs/chroma#vector-search). ### Config | Field | Description | | - | - | | `host` default `'localhost'` | Host name of the Chroma HTTP server. | | `port` default `8000` | Port of the Chroma HTTP server. | | `ssl` default `false` | Connect over HTTPS instead of HTTP. | | `collectionName` required | Name of the existing Chroma collection to mount. | | `slugField` default `'page_slug'` | Chunk metadata key that holds the path of the file a chunk belongs to, relative to the mount root (`guides/quickstart.md`). | | `chunkIndexField` default `'chunk_index'` | Chunk metadata key whose integer orders a file's chunks; a chunk without one sorts as `0`. | ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Chroma mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `chroma`, read | > > #### VFS Layout > > ##### `/<path>` > > * One ChromaDB collection, mounted read only. > * Paths are document slugs from the collection's path tree. > * Inspect documents with `cat`, `head`, `tail`, `ls`, `find`, `tree` and > `grep`. Writes are not supported. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `chroma` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `chroma`, read | > > ## VFS Layout > > ### `/<path>` > > - One ChromaDB collection, mounted read only. > - Paths are document slugs from the collection's path tree. > - Inspect documents with `cat`, `head`, `tail`, `ls`, `find`, `tree` and > `grep`. Writes are not supported. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `chroma` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ``` # Databricks Volume Source: https://docs.mirage.strukto.ai/typescript/setup/databricks_volume Set up a Databricks Unity Catalog volume as a MIRAGE VFS from Node. `DatabricksVolumeVFS` exposes files from a Unity Catalog volume through MIRAGE's standard filesystem interface. Agents can list, stat, read, stream, glob, and write files under the configured volume root. MIRAGE ships it in `@struktoai/mirage-node` only. The TypeScript client calls the Databricks Files REST API directly with `fetch`; the Databricks API does not allow cross-origin browser requests, so there is no browser runtime. For auth and environment setup, see [Databricks Volume Setup](/home/setup/databricks). ## Node ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { buildVfs, MountMode, Workspace } from '@struktoai/mirage-node' const vfs = await buildVfs('databricks_volume', { catalog: 'main', schema: 'default', volume: 'agent_files', root_path: '/reports', host: process.env.DATABRICKS_HOST, token: process.env.DATABRICKS_TOKEN, }) const ws = new Workspace({ '/dbx/': vfs }, { mode: MountMode.READ }) const res = await ws.shell('ls /dbx/') console.log(res.stdoutText) ``` | Field | Description | | - | - | | `timeout` 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. | | `catalog` required | Unity Catalog catalog name; one path segment, no `/`. | | `schema` required | Unity Catalog schema name; one path segment, no `/`. | | `volume` required | Unity Catalog volume name; one path segment, no `/`. | | `rootPath` default `'/'` | Subdirectory inside the volume that becomes the mount root; `..` segments are refused. | | `host` required | Workspace origin, `http://` or `https://`, with no path, query, fragment or credentials. | | `token` required, secret | Bearer token as a string, or a function, synchronous or asynchronous, that returns one for each request. | Fields marked secret are redacted in snapshots. Pass `host` and `token` explicitly. Mirage does not discover environment variables, SDK profiles, or default credentials. An application can read its environment as shown above or use its own credential broker. For rotating credentials, pass a callback that returns a token or a promise of one. Mirage resolves it once for each outbound request, including listing pages and metadata probes. A stream resolves it when iteration starts. The provider owns token caching, refresh, and concurrent refresh coordination. Authentication failures propagate without a fallback or automatic replay. ```ts theme={null} const rotating = await buildVfs('databricks_volume', { catalog: 'main', schema: 'default', volume: 'agent_files', host: process.env.DATABRICKS_HOST, token: async () => broker.getAccessToken(), }) ``` Keep the principal and permission scope fixed for a VFS and its workspace. Different identities require isolated workspaces, file caches, indexes, and external cache prefixes. If permissions change, rebuild or invalidate those caches before further access. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Databricks Volume mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` MIRAGE maps the configured mount prefix onto the configured volume subtree. With `root_path: '/reports/2026'` and mount prefix `/dbx/`, the volume path ```text theme={null} /Volumes/main/default/agent_files/reports/2026/q1/summary.md ``` appears in MIRAGE as ```text theme={null} /dbx/q1/summary.md ``` `root_path` is normalized before use, and MIRAGE rejects any virtual path that would escape above that configured subtree. ## Supported operations Reads: `readdir`, `stat`, `exists`, `read` (streamed whole or a byte range), and glob resolution. Writes: `write`, `create`, `mkdir`, `rmdir`, `unlink`, recursive `rm`, `cp`, and `mv`. Standard shell commands like `ls`, `cat`, `head`, `tail`, `grep`, `rg`, `find`, `tree`, `touch`, `mkdir`, `rm`, `cp`, and `mv` work through those primitives. `mv`/`cp` are non-atomic download + upload — the Files API has no server-side rename. A directory `mv` removes only what it copied: a file or directory written into the source after the copy listed its directory stays there, and `mv` fails with `Directory not empty`. ## Snapshot behavior `token` is redacted in VFS state. A callback is never called or serialized during a snapshot. Loading the snapshot requires a live VFS override with fresh credentials. ## Example See `examples/typescript/vfs/databricks_volume/databricks_volume.ts`, which mirrors `examples/python/vfs/databricks_volume/databricks_volume.py`. # Dify Source: https://docs.mirage.strukto.ai/typescript/setup/dify Mount a Dify Knowledge dataset as a read-only virtual filesystem. The Dify VFS exposes completed Dify Knowledge documents as text files mounted at a prefix such as `/knowledge/`. Each file is assembled from the document's completed, enabled segments. For API key setup and dataset creation, see [Dify Setup](/home/setup/dify). For Python, see the [Dify (Python)](/python/vfs/dify) documentation. ## Config ```typescript theme={null} import { MountMode, Workspace } from '@struktoai/mirage-node' import { DifyVFS } from '@struktoai/mirage-core' const vfs = new DifyVFS({ apiKey: process.env.DIFY_API_KEY!, baseUrl: process.env.DIFY_BASE_URL ?? 'https://api.dify.ai/v1', datasetId: process.env.DIFY_DATASET_ID!, slugMetadataName: process.env.DIFY_SLUG_METADATA_NAME ?? 'slug', }) const ws = new Workspace({ '/knowledge/': vfs }, { mode: MountMode.READ }) ``` The VFS is read-only. Snapshots redact credentials, so `Workspace.load` needs a live `DifyVFS` in its third argument for `/knowledge/` (e.g. `Workspace.load(snapshot, {}, { '/knowledge/': freshDifyVfs })`). Restored cache entries are served as saved and un-cached reads reach the live backend. | Field | Description | | - | - | | `apiKey` required, secret | Dify Knowledge API key, sent as `Authorization: Bearer`. | | `baseUrl` required | Dify API root, such as `https://api.dify.ai/v1`. | | `datasetId` required | ID of the Knowledge dataset the mount shows. | | `slugMetadataName` default `'slug'` | Document metadata field whose value is the document's path in the mount. A document without it is mounted under its document name. | | `maxConcurrency` default `10` | The most Dify API requests in flight at once. | | `retryAttempts` default `4` | Attempts per request, the first included. A 429, a 5xx or a transport error is retried. | | `retryMaxDelay` default `30` | Longest wait in seconds before a retry, whether from backoff or `Retry-After`. | | `timeout` 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. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Dify mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `dify`, read | > > #### VFS Layout > > ##### `/<path>` > > * A Dify knowledge base, mounted read only. > * Every file is plain text assembled from the document's Dify segments, > whatever its original extension. > * `cat`, `head`, `tail`, `grep`, `find`, `ls` and `wc` work on these > files. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `dify`, read | > > ## VFS Layout > > ### `/<path>` > > - A Dify knowledge base, mounted read only. > - Every file is plain text assembled from the document's Dify segments, > whatever its original extension. > - `cat`, `head`, `tail`, `grep`, `find`, `ls` and `wc` work on these > files. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ``` ## Document metadata and paths Mirage mounts documents using a slug metadata field when present (defaulting to `slug`), falling back to the document name. Adding a `slug` metadata field to your Dify Knowledge dataset allows you to organize virtual paths into a clean nested directory structure: | Dify document | `slug` metadata value | Virtual path | | - | - | - | | Quickstart Guide | `guides/quickstart.md` | `/knowledge/guides/quickstart.md` | | API Overview | `api/overview.md` | `/knowledge/api/overview.md` | ## Example ```typescript theme={null} import { MountMode, Workspace } from '@struktoai/mirage-node' import { DifyVFS } from '@struktoai/mirage-core' const vfs = new DifyVFS({ apiKey: process.env.DIFY_API_KEY!, baseUrl: process.env.DIFY_BASE_URL ?? 'https://api.dify.ai/v1', datasetId: process.env.DIFY_DATASET_ID!, }) const ws = new Workspace({ '/knowledge/': vfs }, { mode: MountMode.READ }) // List available knowledge documents const ls = await ws.shell('ls -la /knowledge/') console.log(await ls.stdoutStr()) // Read document contents const content = await ws.shell('cat /knowledge/guides/quickstart.md') console.log(await content.stdoutStr()) // Search for keywords const grep = await ws.shell('shopt -s globstar; grep -i "authentication" /knowledge/**/*.md') console.log(await grep.stdoutStr()) ``` # DigitalOcean Spaces Source: https://docs.mirage.strukto.ai/typescript/setup/digitalocean Set up DigitalOcean Spaces as a MIRAGE VFS from Node or the browser. DigitalOcean Spaces uses the S3 API with AWS Signature V4 against `https://<region>.digitaloceanspaces.com`. MIRAGE derives this endpoint from your region automatically. Credentials (Spaces access key pair) are created the same way in both runtimes, see [DigitalOcean Credentials](/home/setup/digitalocean). ## Node (server-side) ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { DigitalOceanVFS, MountMode, Workspace } from '@struktoai/mirage-node' const spaces = new DigitalOceanVFS({ bucket: process.env.DO_SPACE!, region: process.env.DO_REGION!, accessKeyId: process.env.DO_ACCESS_KEY_ID!, secretAccessKey: process.env.DO_SECRET_ACCESS_KEY!, }) const ws = new Workspace({ '/bucket/': spaces }, { mode: MountMode.READ }) const res = await ws.shell('ls /bucket/') console.log(res.stdoutText) ``` ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `accessKeyId` secret | Access key ID; set it with `secretAccessKey`. Unset uses the AWS SDK credential chain. | | `secretAccessKey` secret | Secret access key paired with `accessKeyId`. | | `sessionToken` secret | Session token for temporary credentials, sent with the access key pair. | | `profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `forcePathStyle` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `keyPrefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `timeout` 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. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | | `region` required | Provider region every request is signed for. Most providers also build their endpoint URL from it unless `endpoint` is set. | | `endpoint` | Endpoint URL that replaces the one the provider derives. | Fields marked secret are redacted in snapshots. ## Browser (presigned URLs) ```bash theme={null} pnpm add @struktoai/mirage-browser ``` The browser `DigitalOceanVFS` is secret-free, your backend signs each operation using your Spaces keys and returns a URL. Spaces accepts AWS Signature V4, so `@aws-sdk/s3-request-presigner` works, pointed at the Spaces endpoint. ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `presignedUrlProvider` required, secret | Function `(path, operation, options)` that returns a signed URL for each S3 operation; your server signs it, so the browser holds no keys. | | `region` | Region of the bucket. Most providers derive the endpoint from it; requests go to the host each presigned URL names. | | `endpoint` | Endpoint URL that replaces the one the provider derives. Requests go to the host each presigned URL names; the mount uses it to name its storage location. | | `defaultContentType` default `'application/octet-stream'` | `Content-Type` stored with every object the mount writes. | | `keyPrefix` | Key prefix the mount treats as its root. The browser can change it before a URL is signed, so enforce the prefix on the signing server. | | `timeout` 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. | Fields marked secret are redacted in snapshots. ### 1. Server: sign URLs with the Spaces endpoint ```ts theme={null} import { CopyObjectCommand, DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client, } from '@aws-sdk/client-s3' import { getSignedUrl } from '@aws-sdk/s3-request-presigner' const REGION = process.env.DO_REGION! const client = new S3Client({ region: REGION, endpoint: `https://${REGION}.digitaloceanspaces.com`, credentials: { accessKeyId: process.env.DO_ACCESS_KEY_ID!, secretAccessKey: process.env.DO_SECRET_ACCESS_KEY!, }, }) const BUCKET = process.env.DO_SPACE! app.post('/presign/spaces', async (req, res) => { const { path, op, opts } = req.body const key = path.replace(/^\/+/, '') const ttl = typeof opts?.ttlSec === 'number' ? opts.ttlSec : 300 let cmd switch (op) { case 'GET': cmd = new GetObjectCommand({ Bucket: BUCKET, Key: key }); break case 'PUT': cmd = new PutObjectCommand({ Bucket: BUCKET, Key: key, ContentType: opts?.contentType }); break case 'HEAD': cmd = new HeadObjectCommand({ Bucket: BUCKET, Key: key }); break case 'DELETE': cmd = new DeleteObjectCommand({ Bucket: BUCKET, Key: key }); break case 'LIST': cmd = new ListObjectsV2Command({ Bucket: BUCKET, Prefix: opts?.listPrefix, Delimiter: opts?.listDelimiter, ContinuationToken: opts?.listContinuationToken, }); break case 'COPY': cmd = new CopyObjectCommand({ Bucket: BUCKET, Key: key, CopySource: `${BUCKET}/${opts?.copySource}`, }); break } res.json({ url: await getSignedUrl(client, cmd, { expiresIn: ttl }) }) }) ``` ### 2. Browser: wire it up ```ts theme={null} import { DigitalOceanVFS, MountMode, Workspace } from '@struktoai/mirage-browser' const spaces = new DigitalOceanVFS({ bucket: 'my-space', region: 'nyc3', presignedUrlProvider: async (path, op, opts) => { const r = await fetch('/presign/spaces', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path, op, opts }), }) const { url } = await r.json() return url }, }) const ws = new Workspace({ '/bucket/': spaces }, { mode: MountMode.READ }) ``` > [!TIP] > > `region` on the browser config is only used for display/logging; the actual endpoint is baked into the presigned URLs your backend returns. ### 3. CORS Spaces supports the S3 `PutBucketCors` call, so the AWS CLI works against the Spaces endpoint (you can also use the DigitalOcean control panel, Space -> Settings -> CORS Configurations): ```bash theme={null} aws s3api put-bucket-cors --bucket "$DO_SPACE" \ --endpoint-url "https://$DO_REGION.digitaloceanspaces.com" \ --cors-configuration '{"CORSRules":[{"AllowedOrigins":["http://localhost:5173","https://app.example.com"],"AllowedMethods":["GET","PUT","HEAD","DELETE","POST"],"AllowedHeaders":["*"],"ExposeHeaders":["ETag","Content-Length","Content-Type","Last-Modified"]}]}' ``` See the [DigitalOcean VFS](/python/vfs/digitalocean) docs for the equivalent Python wiring. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with DigitalOcean Spaces mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Integration What DigitalOcean Spaces answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On DigitalOcean Spaces | | - | - | | `md5sum` | The object's ETag, when it is the MD5: a single-part upload, unencrypted or under SSE-S3 | | `find`, `du`, `ls -R`, `tree` | One recursive listing | # Discord Source: https://docs.mirage.strukto.ai/typescript/setup/discord Mount Discord guilds, channels, and members as a virtual filesystem from Node or the browser. MIRAGE ships `DiscordVFS` in **two runtimes**: * `@struktoai/mirage-node`, talks to `https://discord.com/api/v10/*` directly using a bot token. * `@struktoai/mirage-browser`, stays secret-free: a small proxy server on your backend holds the token and forwards `/api/discord/*` to `https://discord.com/api/v10/*`. The browser only ever sees the proxy URL. Both runtimes expose the same filesystem shape (`/discord/<guild>/channels/<channel>/<date>/{chat.jsonl,files/}`, `/discord/<guild>/members/`) and the same shell commands, and both pair with the [discord CLI](/typescript/cli/discord) for acting on the server. ## Get a bot token 1. Visit the [Discord Developer Portal](https://discord.com/developers/applications) and create a new application. 2. Under **Bot**, add a bot user and copy the **Bot Token**. 3. Under **Bot → Privileged Gateway Intents**, enable: * **Server Members Intent**, required for `/discord/<guild>/members/` listings. * **Message Content Intent**, required to read message text in `.jsonl` history files. 4. Under **OAuth2 → URL Generator**, select the `bot` scope and the following bot permissions: * `Read Messages/View Channels` * `Read Message History` * `Send Messages` (only if you'll use `discord send`) * `Add Reactions` (only if you'll use `discord react`) 5. Open the generated URL in a browser and invite the bot to your guild. ```bash theme={null} # .env.development DISCORD_BOT_TOKEN=... ``` ## Node (server-side) ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { DiscordVFS, MountMode, Workspace } from '@struktoai/mirage-node' const discord = new DiscordVFS({ token: process.env.DISCORD_BOT_TOKEN!, }) const ws = new Workspace({ '/discord': discord }, { mode: MountMode.READ }) const res = await ws.shell('ls /discord/') console.log(res.stdoutText) ``` ### Config | Field | Description | | - | - | | `timeout` 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. | | `token` required, secret | Discord bot token, sent as `Authorization: Bot <token>`. | | `baseUrl` default `'https://discord.com/api/v10'` | Discord API root; override to point at a fake or proxy. | | `startTime` | Start of the mount's time scope, inclusive: an RFC 3339 timestamp with an explicit timezone and at most millisecond precision. Unset leaves the start open. | | `endTime` | End of the mount's time scope, exclusive, in the same format as `startTime`, which it must follow. Unset leaves the end open. | Fields marked secret are redacted in snapshots. ## Browser ```bash theme={null} pnpm add @struktoai/mirage-browser ``` The browser package never sees the bot token. Instead, point it at a relative URL that your backend proxies to `https://discord.com/api/v10/*`, attaching the `Authorization: Bot …` header server-side. ### Config | Field | Description | | - | - | | `timeout` 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. | | `startTime` | Start of the mount's time scope, inclusive: an RFC 3339 timestamp with an explicit timezone and at most millisecond precision. Unset leaves the start open. | | `endTime` | End of the mount's time scope, exclusive, in the same format as `startTime`, which it must follow. Unset leaves the end open. | | `proxyUrl` required | URL of your backend proxy, which forwards to `https://discord.com/api/v10` and attaches the bot token. A path resolves against the page's origin; no query string or fragment. | | `getHeaders` secret | Function returning extra headers sent with every request to the proxy, such as your own session credential. | Fields marked secret are redacted in snapshots. ### 1. Server: minimal proxy ```ts theme={null} import { createServer } from 'node:http' const TOKEN = process.env.DISCORD_BOT_TOKEN! const PREFIX = '/api/discord/' createServer(async (req, res) => { const url = new URL(req.url ?? '/', 'http://localhost') if (!url.pathname.startsWith(PREFIX)) { res.statusCode = 404 res.end() return } const upstream = new URL(`https://discord.com/api/v10/${url.pathname.slice(PREFIX.length)}`) upstream.search = url.search const method = (req.method ?? 'GET').toUpperCase() const chunks: Buffer[] = [] if (method !== 'GET' && method !== 'HEAD') { for await (const chunk of req) chunks.push(chunk as Buffer) } const body = chunks.length > 0 ? Buffer.concat(chunks).toString('utf-8') : undefined const headers: Record<string, string> = { Authorization: `Bot ${TOKEN}` } const ct = req.headers['content-type'] if (typeof ct === 'string') headers['content-type'] = ct const upstreamRes = await fetch(upstream, { method, headers, ...(body !== undefined ? { body } : {}) }) const text = await upstreamRes.text() res.statusCode = upstreamRes.status const upstreamCt = upstreamRes.headers.get('content-type') if (upstreamCt !== null) res.setHeader('content-type', upstreamCt) res.end(text) }).listen(8902, '127.0.0.1') ``` > [!WARNING] > > Discord bot tokens use the `Bot <token>` auth scheme, **not** `Bearer`. Sending `Bearer …` returns `401 Unauthorized`. ### 2. Browser: wire it up ```ts theme={null} import { DiscordVFS, MountMode, Workspace } from '@struktoai/mirage-browser' const discord = new DiscordVFS({ proxyUrl: '/api/discord', // For multi-tenant setups, return per-request auth headers: // getHeaders: async () => ({ Authorization: `Bearer ${userJwt}` }), }) const ws = new Workspace({ '/discord': discord }, { mode: MountMode.READ }) const res = await ws.shell('ls /discord/') console.log(res.stdoutText) ``` > [!WARNING] > > Calling `https://discord.com/api/v10/*` directly from a browser fails CORS. The proxy is mandatory, Discord does not set permissive CORS headers for the bot API. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Discord mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `discord`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > <guild-name>__<guild-id>/ > channels/ > <channel-name>__<channel-id>/ > <yyyy-mm-dd>/ > chat.jsonl # messages for that date > files/ # attachments shared that day > <name>__<att-id>.<ext> # cat downloads it from Discord's CDN > members/ > <username>__<user-id>.json # member profile > ``` > > * A guild, channel, member or attachment name is `<display-name>__<id>`. > The display name keeps Discord's spelling (spaces, apostrophes, emoji); > only `/` becomes `∕` (U+2215). `ls` the parent first to find exact > names, and quote a name that has spaces. > * Messages are JSONL; use `jq` for fields such as `.content`, > `.author.username` and `.attachments`. A day's `files/` may be empty. > * Without `start_time`/`end_time`, a channel lists the latest 30 days up > to its newest message; a date glob finds earlier days. > * With `start_time`/`end_time`, listings cover that scope; messages and > attachments outside it are absent, direct paths included. Users and > channel metadata stay available as context. > * `grep` and `rg` read the files they reach, so `grep` needs `-r` for a > directory. Under a channel that reads every listed day, attachments > included: they download from the CDN, and binary ones such as JPG or > PDF produce noise. > > Time scope: `start_time=unbounded` (inclusive), `end_time=unbounded` (exclusive). Explicit paths and globs cannot escape this scope. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `discord`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > <guild-name>__<guild-id>/ > channels/ > <channel-name>__<channel-id>/ > <yyyy-mm-dd>/ > chat.jsonl # messages for that date > files/ # attachments shared that day > <name>__<att-id>.<ext> # cat downloads it from Discord's CDN > members/ > <username>__<user-id>.json # member profile > ``` > > - A guild, channel, member or attachment name is `<display-name>__<id>`. > The display name keeps Discord's spelling (spaces, apostrophes, emoji); > only `/` becomes `∕` (U+2215). `ls` the parent first to find exact > names, and quote a name that has spaces. > - Messages are JSONL; use `jq` for fields such as `.content`, > `.author.username` and `.attachments`. A day's `files/` may be empty. > - Without `start_time`/`end_time`, a channel lists the latest 30 days up > to its newest message; a date glob finds earlier days. > - With `start_time`/`end_time`, listings cover that scope; messages and > attachments outside it are absent, direct paths included. Users and > channel metadata stay available as context. > - `grep` and `rg` read the files they reach, so `grep` needs `-r` for a > directory. Under a channel that reads every listed day, attachments > included: they download from the CDN, and binary ones such as JPG or > PDF produce noise. > > Time scope: `start_time=unbounded` (inclusive), `end_time=unbounded` (exclusive). Explicit paths and globs cannot escape this scope. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ```` The root lists one directory per guild the bot has access to. Each guild contains a `channels/` directory with text channels (types 0, 5, 15) and a `members/` directory with one `.json` file per member. Each channel directory contains day-partitioned **directories** for the 30 days leading up to the channel's last message, inactive channels show dates around their last activity, not today. Each day directory holds `chat.jsonl` (one JSON object per message) and a `files/` directory with that day's attachments, `cat`'ing a blob downloads it from the Discord CDN. Soft errors (403 missing permissions, 404 unknown channel, 429 rate limit) on a single day are swallowed so listings, `find`, and `grep` keep working across the rest of the tree. Display names keep their original spelling from Discord (spaces, apostrophes, emoji are all preserved). Only `/` is replaced with `∕` (U+2215) so it cannot collide with a directory boundary. The Discord snowflake ID is appended after `__` (double underscore) on guild, channel, member, and attachment names so VFS-specific commands can extract it without an extra lookup, and so two same named entities never collide. Quote names containing spaces in shell commands. ## Shell commands Every standard MIRAGE shell command works on the mounted Discord tree: | Command | Notes | | - | - | | `ls` | List guilds, channels, members, dates, attachments | | `cat` | Read `chat.jsonl`, member `.json`, or download an attachment | | `head` / `tail` | Smart: uses messages API for file scope | | `grep` / `rg` | Pattern search (file or directory level) | | `jq` | Query JSON; runs once per line of a JSONL file (`-s` for all) | | `wc` | Line/word/byte counts | | `stat` | File metadata (name, size, type, ID via `extra`) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `pwd` / `cd` | Navigate the virtual tree | | `echo` (glob) | Glob expansion via the derived `glob` op | Acting on Discord (sending, editing, reactions, threads, polls, member and guild info, search) goes through the [discord CLI](/typescript/cli/discord) when installed; the mounted tree stays read-oriented. ## Troubleshooting > [accordion] Empty `/discord/\<guild\>/members/` listing > > Listing members requires the **Server Members Intent**. Enable it in the Discord Developer Portal under **Bot → Privileged Gateway Intents**. Without it, `members/` returns an empty directory and `discord members` fails. > [accordion] Empty `content` field in JSONL messages > > Reading message text requires the **Message Content Intent**. Enable it in the Discord Developer Portal under **Bot → Privileged Gateway Intents**. Without it, the `content` field on every message is empty. > [accordion] `401 Unauthorized` from the proxy > > Discord bot tokens use the `Authorization: Bot <token>` scheme, **not** `Bearer`. Double-check the proxy server attaches the correct prefix. > [accordion] CORS error in browser > > The browser cannot call `https://discord.com/api/v10/*` directly, Discord does not set permissive CORS headers. You must run the proxy server shown above (or your own equivalent) and point `proxyUrl` at it. > [accordion] `rate_limited` from Discord > > `DiscordVFS` uses an `IndexCacheStore` (default TTL 600s) to deduplicate guild / channel / member listings, but high-volume reads of `.jsonl` files can still hit Discord's per-route rate limits. The HTTP transport retries 429 responses honoring `retry_after` up to 3 times, repeated failures usually mean you should slow down or scope reads to specific channels. ## Integration What Discord answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Discord | | - | - | | `tail -f` | Each new message as it is posted | ## Examples * [`examples/typescript/vfs/discord/discord.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/vfs/discord/discord.ts), shell commands against `/discord/` (`ls`, `cat`, `grep`, `jq`, `tree`, `find`, `cd`, glob). * [`examples/typescript/vfs/discord/discord_vfs.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/vfs/discord/discord_vfs.ts), `patchNodeFs(ws)` so native `node:fs` calls route through the workspace. * [`examples/typescript/vfs/discord/discord_fuse.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/vfs/discord/discord_fuse.ts), FUSE-mount the workspace so external processes can browse `/discord/` as a real filesystem. * [`examples/browser/vfs/discord/`](https://github.com/strukto-ai/mirage/tree/main/examples/browser/vfs/discord), proxy server + `@struktoai/mirage-browser` DiscordVFS demo. See [Python Discord VFS](/python/vfs/discord) for the equivalent Python wiring. ## Time scope Set `start_time` and/or `end_time` in the mount's YAML `config` (or pass `start_time`/`end_time` to Python; `startTime`/`endTime` to the TypeScript constructor). Bounds are RFC3339 timestamps with an explicit timezone and at most millisecond precision. Start is inclusive; end is exclusive. An omitted or null bound is open. Start must precede end. ```yaml theme={null} mounts: /history: vfs: discord mode: read config: token: "<bot-token>" start_time: "2026-06-01T10:00:00Z" end_time: "2026-06-02T00:00:00Z" ``` With a bound configured, channel listings cover the selected period rather than the default recent window. Day directories use UTC. Messages are selected by creation time, and attachments follow their parent messages. Direct paths, `stat`, date globs, and `grep`/`rg` cannot escape the scope. Scoped searches scan the filtered files. User/member and channel/server metadata remain visible as context. These settings apply to the VFS, not to separately installed account CLIs. `mode: read` prevents mount writes; it does not freeze upstream edits or deletions. Rebuild/remount the VFS to change its scope so cached listings and bytes are cleared. # Disk Source: https://docs.mirage.strukto.ai/typescript/setup/disk Mount a directory on the host filesystem as a Mirage VFS (Node only). `DiskVFS` mounts a directory on the host filesystem. Reads and writes go through `node:fs` against the configured `root`. > [!NOTE] > > Node only. The browser SDK has no kernel filesystem; use [OPFS](/typescript/setup/opfs) instead. ## Install ```bash theme={null} pnpm add @struktoai/mirage-node ``` ## Config ```ts theme={null} import { DiskVFS, MountMode, Workspace } from '@struktoai/mirage-node' const disk = new DiskVFS({ root: '/Users/me/data' }) const ws = new Workspace({ '/disk': disk }, { mode: MountMode.WRITE }) await ws.shell('echo hello | tee /disk/note.txt') await ws.shell('cat /disk/note.txt') ``` | Field | Default | Notes | | - | - | - | | `root` | required | Absolute path on the host. Reads and writes are scoped to this directory. A second disk mount whose root resolves to a folder already mounted is refused; a folder inside one is fine. | | `folderVersions` | `true` | Store each listing at its folder's version (device, inode, change and modified time), so a `read: fresh` mount re-lists only folders that changed. Must be a boolean. Set `false` for a network or FUSE root (NFS, SMB, rclone, s3fs, mirage's own FUSE), whose change time may not move with its entries. In YAML: `folder_versions`. | A folder changed in the last 2 seconds gets no version and is re-listed until it has been quiet that long. ## Mount mode `read`, `write`, `exec`. Use `MountMode.EXEC` if `python3` or `js` should run scripts from the mount. ## Snapshot behavior A snapshot carries the mount's files, and loading it restores them. For behavior shared with Python (filesystem layout, supported shell commands), see the [Python Disk docs](/python/vfs/disk). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Disk mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `grep -r`, `find` and `du` stop after 10000 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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `grep -r`, `find` and `du` stop after 10000 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. > ``` # Dropbox Source: https://docs.mirage.strukto.ai/typescript/setup/dropbox Mount Dropbox as a read/write MIRAGE VFS from Node or the browser via OAuth2. Mirage ships `DropboxVFS` in **two runtimes**: * `@struktoai/mirage-node`, uses `client_id` + `client_secret` + long-lived refresh token to fetch short-lived access tokens server-side. * `@struktoai/mirage-browser`, supports the same refresh token via PKCE (no client secret in the bundle). Both runtimes hit the same [Dropbox v2 HTTP API](https://www.dropbox.com/developers/documentation/http/documentation): `/2/files/list_folder` for directories, `/2/files/download` for content, and `/2/files/upload` / `create_folder_v2` / `delete_v2` / `move_v2` / `copy_v2` for writes. Credentials are obtained the same way in both runtimes, see [Dropbox Credentials](/home/setup/dropbox). The Python package ships the same backend, see [Dropbox (Python)](/python/vfs/dropbox). ## Node (server-side) ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { DropboxVFS, MountMode, Workspace } from '@struktoai/mirage-node' const dropbox = new DropboxVFS({ clientId: process.env.DROPBOX_APP_KEY!, clientSecret: process.env.DROPBOX_APP_SECRET!, refreshToken: process.env.DROPBOX_REFRESH_TOKEN!, }) const ws = new Workspace({ '/dropbox': dropbox }, { mode: MountMode.READ }) const res = await ws.shell('ls /dropbox/') console.log(res.stdoutText) ``` The `DropboxTokenManager` caches the access token in memory and refreshes it \~5 minutes before expiry, so cold-start API calls don't pay the refresh round-trip. ### Config | Field | Description | | - | - | | `timeout` 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. | | `clientId` required | Dropbox app key. | | `clientSecret` required, secret | Dropbox app secret. | | `refreshToken` required, secret | Long-lived OAuth refresh token; mirage mints short-lived access tokens from it. | | `rootPath` | Dropbox folder the mount uses as its root, such as `/Projects`; unset or `/` is the account root. `..` segments are rejected. | | `endpoint` | Base URL that replaces Dropbox's OAuth, API and content hosts, such as a test server. Unset uses Dropbox's hosts. | | `refreshFn` secret | Function that takes the refresh token and returns `{ accessToken, expiresIn }` (seconds), called instead of Dropbox's token endpoint, for example so the app secret stays on a backend. | Fields marked secret are redacted in snapshots. ## Mount a subfolder Pass `rootPath` to expose a single Dropbox folder as the mount root instead of the whole account. Every command and FUSE/VFS op is scoped to that folder; paths outside it are unreachable. ```ts theme={null} const dropbox = new DropboxVFS({ clientId: process.env.DROPBOX_APP_KEY!, clientSecret: process.env.DROPBOX_APP_SECRET!, refreshToken: process.env.DROPBOX_REFRESH_TOKEN!, rootPath: '/Team/data', }) const ws = new Workspace({ '/dropbox': dropbox }, { mode: MountMode.READ }) await ws.shell('ls /dropbox/') // lists the contents of /Team/data ``` `rootPath` accepts `Team/data`, `/Team/data`, or `/Team/data/` (all normalized the same way); `..` segments are rejected. Config dictionaries (e.g. via the VFS registry) may spell it `root_path`. Omitting it (or passing `/`) mounts the account root as before. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Dropbox mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `dropbox`, write | > > #### 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 `dropbox` 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>` | `dropbox`, write | > > ## 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 `dropbox` 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. > ``` ## Integration What Dropbox answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Dropbox | | - | - | | `grep -r`, `rg` | Dropbox search, for whole words. It can miss Office files, PDFs, archives, the end of large files, words Dropbox splits differently (`foo.bar`) and recent writes; file contents on plans below Professional. | | `find`, `du`, `ls -R`, `tree` | One recursive listing | The [Python Dropbox docs](/python/vfs/dropbox#integration) list when each search answers and what it can miss. ## Names missing from a listing A name missing from a cached listing that the running command did not fetch is looked up on Dropbox by path before mirage answers that it does not exist: one `get_metadata` for a `stat`, or the download itself for a read. A file another client created after the listing is therefore found, and `>>`, `touch` and `sed -i` act on it instead of replacing it. A listing the running command fetched itself is trusted as is, for the whole command. Each command of a script is its own command, but one long-running command, such as a program a runtime runs, does not see a file another client creates after it listed the folder. Some lookups run outside any shell command: FUSE, programmatic calls, `[ ]` and `[[ ]]` tests, and a redirect on anything but a simple command (a brace group, subshell, loop, `if` or `case`). No listing is the caller's own there, so each lookup of a name missing from a cached listing costs one request. ## Reads under `fresh` Under `read: fresh`, a cached file is checked against its `content_hash` before it is served: one `get_metadata` per warm read, never a folder listing. A download names the hash in its `Dropbox-API-Result` header, full or ranged, so a read stamps it with no extra request. `server_modified` is not used: Dropbox repeats it across same-size rewrites. ## Writes A write records the `content_hash` its upload reply names, so a `fresh` read right after a `tee` or `sed -i` downloads nothing. ## Conditional writes A rewrite that observes a missing file requires atomic create-only support, which this backend does not currently enable. Appending to a missing file therefore returns an unsupported-operation error under either write policy. An intentional write with `>` can create the file, and subsequent appends to that existing file retain the selected policy. A Dropbox mount accepts `write: conditional`. A write that holds a version looks the file up once (`get_metadata`), refuses a file whose `content_hash` changed since it was read, and uploads in `update` mode with the file's `rev`, so Dropbox refuses (409 `path/conflict`) a change that lands in between; a delete sends the `rev` as `parent_rev`. `rm -r` walks the folder file by file, and a `mv` within the mount is Dropbox's own move, which is not refused when its source changed (a `mv` to another mount is a copy and a conditioned delete, so there a changed source stays and `mv` reports the failed removal). ## Browser (PKCE, no client secret) ```bash theme={null} pnpm add @struktoai/mirage-browser ``` ```ts theme={null} import { DropboxVFS, MountMode, Workspace } from '@struktoai/mirage-browser' // Refresh token obtained via the PKCE flow, see examples/browser/vfs/dropbox/dropbox_pkce.ts. const dropbox = new DropboxVFS({ clientId: import.meta.env.VITE_DROPBOX_APP_KEY, refreshToken: refreshTokenFromLocalStorage, }) const ws = new Workspace({ '/dropbox': dropbox }, { mode: MountMode.READ }) await ws.shell('ls /dropbox/') ``` Set the redirect URI on your Dropbox app's **Settings** tab to your dev/prod origin (e.g. `http://localhost:5173/vfs/dropbox/dropbox_pkce.html`). The bundled [`examples/browser/vfs/dropbox/dropbox_pkce.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/browser/vfs/dropbox/dropbox_pkce.ts) runs the full PKCE dance end-to-end and persists the refresh token to `localStorage`. ## VFS mode (`patchNodeFs`) Mirage exposes a `patchNodeFs(workspace)` shim that routes `fs` calls under a mount through the workspace, so any library that uses Node's `fs` API can read directly from Dropbox without code changes. ```ts theme={null} import { createRequire } from 'node:module' import { DropboxVFS, MountMode, patchNodeFs, Workspace } from '@struktoai/mirage-node' const require = createRequire(import.meta.url) const fs = require('fs') as typeof import('fs') const dropbox = new DropboxVFS({ clientId: process.env.DROPBOX_APP_KEY!, clientSecret: process.env.DROPBOX_APP_SECRET!, refreshToken: process.env.DROPBOX_REFRESH_TOKEN!, }) const ws = new Workspace({ '/dropbox': dropbox }, { mode: MountMode.READ }) const restore = patchNodeFs(ws) const entries = await fs.promises.readdir('/dropbox/') const stat = await fs.promises.stat('/dropbox/data') const bytes = await fs.promises.readFile('/dropbox/data/example.parquet') restore() ``` The async forms (`fs.promises.*` and the callbacks) are routed. Sync forms like `fs.statSync` and `fs.readFileSync` refuse a mounted path because remote reads can't block the event loop. ## FUSE mode For tools that need a real filesystem path (CLI tools, editors, system utilities), mount the workspace under FUSE: ```ts theme={null} import { DropboxVFS, Mount, MountBackend, MountMode, Workspace } from '@struktoai/mirage-node' const dropbox = new DropboxVFS({ clientId: process.env.DROPBOX_APP_KEY!, clientSecret: process.env.DROPBOX_APP_SECRET!, refreshToken: process.env.DROPBOX_REFRESH_TOKEN!, }) const ws = new Workspace({ '/dropbox': new Mount(dropbox, { mode: MountMode.READ, backend: MountBackend.FUSE }) }) await ws.fuseReady() const mp = ws.fuseMountpoint // The dropbox subtree is exposed at the mountpoint root, so `${mp}/` is a real path: // ls ${mp}/ // find ${mp} -name '*.parquet' // cat ${mp}/data/example.json | jq . await ws.close() ``` Requires [macFUSE](https://osxfuse.github.io/) on macOS or libfuse on Linux. See [FUSE setup](/home/setup/macos). ## Available commands `DropboxVFS` ships the same shell command set as the GDrive VFS: * **Filesystem**: `ls`, `cat`, `head`, `tail`, `nl`, `wc`, `stat`, `find`, `tree`, `du`, `file`, `realpath`, `basename`, `dirname` * **Write** (on a `WRITE` mount): `tee`, `touch`, `mkdir`, `rm`, `rmdir`, `mv`, `cp`, `truncate`, shell redirection (`>` / `>>`) * **Search/text**: `grep`, `rg`, `awk`, `sed`, `sort`, `uniq`, `cut`, `diff`, `cmp`, `jq` * **Encoding**: `base64` ## Examples End-to-end runnable scripts are in [`examples/typescript/vfs/dropbox/`](https://github.com/strukto-ai/mirage/tree/main/examples/typescript/vfs/dropbox): * [`dropbox.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/vfs/dropbox/dropbox.ts), `Workspace.shell('ls/stat/cat/tree …')` shell demo * [`dropbox_vfs.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/vfs/dropbox/dropbox_vfs.ts), `patchNodeFs` + native `fs.promises.*` calls * [`dropbox_fuse.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/vfs/dropbox/dropbox_fuse.ts), FUSE mount with shell access in another terminal `grep` classifies the bytes it reads, including downloaded attachments. Use `-I` to skip binary inputs or `-a` (`--binary-files=text`) to search them as text. Text mode bypasses the content-search index and scans files directly. # Email Source: https://docs.mirage.strukto.ai/typescript/setup/email Mount an IMAP/SMTP mailbox as a Mirage filesystem (Node only). `EmailVFS` reads the mailbox over IMAP as a tree of folders and messages. The [himalaya CLI](/typescript/cli/himalaya) sends mail. > [!NOTE] > > Node only. Requires `imapflow`, `mailparser`, and `nodemailer` peers. The browser cannot speak raw TCP for IMAP/SMTP. ## Install ```bash theme={null} pnpm add @struktoai/mirage-node imapflow mailparser nodemailer ``` ## Config ```ts theme={null} import { EmailVFS, MountMode, Workspace } from '@struktoai/mirage-node' const email = new EmailVFS({ imapHost: 'imap.example.com', smtpHost: 'smtp.example.com', username: process.env.EMAIL_USERNAME!, password: process.env.EMAIL_PASSWORD!, }) const ws = new Workspace({ '/mail': email }, { mode: MountMode.READ }) await ws.shell('ls /mail/INBOX/') ``` | Field | Description | | - | - | | `timeout` 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. | | `imapHost` required | IMAP server hostname. | | `imapPort` default `993` | IMAP server port. | | `smtpHost` required | SMTP server hostname `himalaya` sends mail through. | | `smtpPort` default `587` | SMTP server port. `465` uses implicit TLS; any other port starts in plaintext and upgrades with STARTTLS when the server offers it. | | `username` required | Login for both IMAP and SMTP, usually the email address. | | `password` required, secret | Password or app password for `username`. | | `useSsl` default `true` | Speak TLS from the first byte of the IMAP connection (IMAPS); off connects in plaintext. SMTP follows `smtpPort` instead. | | `maxMessages` default `200` | How many of a folder's newest messages the mount lists and `grep` searches, and the window `himalaya envelope list` and `search` page through. | | `saveCopy` default `true` | After `himalaya` sends a message, append a copy to `sentFolder`, as upstream himalaya's `message.send.save-copy`. Off saves a copy only when `--save` names a mailbox. | | `sentFolder` default `null` | Mailbox a sent copy goes to. Unset asks the server for the mailbox tagged `\Sent` and falls back to `Sent`. | | `trashFolder` default `null` | Mailbox `himalaya message delete` moves messages to, as upstream's `mailbox.alias.trash`. Unset asks the server for the mailbox tagged `\Trash` and falls back to `Trash`. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Email mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `email`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > <folder>/ # INBOX, Sent, Drafts, ... > <yyyy-mm-dd>/ > <subject>__<uid>.email.json # the message as JSON > <subject>__<uid>/ # its attachments, if any > <attachment-filename> > ``` > > * `<subject>` is sanitized: `ls` the date directory rather than > construct it. > * To list, search, read, compose, reply or forward, use the `himalaya` > CLI if installed (`himalaya --help`). > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `email` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `email` answers only for `*/*/*.email.json`; `grep -r` and `rg` read every other 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>` | `email`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > <folder>/ # INBOX, Sent, Drafts, ... > <yyyy-mm-dd>/ > <subject>__<uid>.email.json # the message as JSON > <subject>__<uid>/ # its attachments, if any > <attachment-filename> > ``` > > - `<subject>` is sanitized: `ls` the date directory rather than > construct it. > - To list, search, read, compose, reply or forward, use the `himalaya` > CLI if installed (`himalaya --help`). > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `email` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `email` answers only for `*/*/*.email.json`; `grep -r` and `rg` read every other 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. > ```` ## Integration What Email answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Email | | - | - | | `grep -r`, `rg` | IMAP `SEARCH TEXT`, for any text. It can miss on a server that searches words rather than substrings (Dovecot with full-text search). | The [Python Email docs](/python/vfs/email#integration) list when each search answers and what it can miss. ## Mount mode `read`. Send mail through the [himalaya CLI](/typescript/cli/himalaya). For mailbox layout, search behavior, and synthesized date directories see the [Python Email docs](/python/vfs/email). # FUSE Source: https://docs.mirage.strukto.ai/typescript/setup/fuse Set up FUSE support for MIRAGE with the TypeScript SDK. ## Prerequisites * Node.js 22.20+ (22.x), 24.12+ (24.x), or 25+ * [pnpm](https://pnpm.io/) (recommended, `npm` and `yarn` also work, but the FUSE binding's install script needs extra configuration with pnpm). ## System FUSE Install the OS-level FUSE kernel support first (see the [support matrix](/home/setup/fuse) for the full OS overview): * [macOS FUSE Setup](/home/setup/macos), macFUSE + kernel extension + Apple Silicon recovery mode steps. * [Linux FUSE Setup](/home/setup/linux), `fuse3` install and `/etc/fuse.conf`. > [!NOTE] > > **No Windows support in TypeScript.** `@zkochan/fuse-native` targets macOS > and Linux only; its legacy Windows path builds against the unmaintained > Dokany-based `fuse-shared-library-win32`, not WinFsp. Python's FUSE mounts > run on Windows experimentally, see [Windows FUSE Setup](/home/setup/windows). ## Install the Node Binding The Node package (`@struktoai/mirage-node`) ships FUSE support via an **optional peer dependency** on [`@zkochan/fuse-native`](https://www.npmjs.com/package/@zkochan/fuse-native), the pnpm author's actively-maintained fork that supports both macOS and Linux (thanks to [@zkochan](https://github.com/fuse-friends/fuse-native/issues/36#issuecomment-3089754579)). ```bash theme={null} pnpm add @struktoai/mirage-node @zkochan/fuse-native ``` > [!TIP] > > Non-FUSE users don't need `@zkochan/fuse-native`, the base `@struktoai/mirage-node` package works without it. Only install the binding when you want a real mountpoint. ### Allow pnpm to run the install script `@zkochan/fuse-native` compiles native code on install. pnpm blocks install scripts by default, allow this one explicitly in `pnpm-workspace.yaml`: ```yaml theme={null} onlyBuiltDependencies: - '@zkochan/fuse-native' ``` Or, if you're not using a pnpm workspace, in `package.json`: ```json theme={null} { "pnpm": { "onlyBuiltDependencies": ["@zkochan/fuse-native"] } } ``` ## macFUSE 4 symlink workaround > [tab] macOS > > macFUSE 4 ships `libfuse.2.dylib` instead of the legacy `libosxfuse.2.dylib` that `@zkochan/fuse-native` links against when it builds; the built `fuse.node` then loads `/usr/local/lib/libfuse.2.dylib`. Create a one-time symlink before the build: > > ```bash theme={null} > sudo ln -sf /usr/local/lib/libfuse.2.dylib /usr/local/lib/libosxfuse.2.dylib > pnpm rebuild @zkochan/fuse-native > ``` > [tab] Linux > > No workaround needed on Linux, `@zkochan/fuse-native` links against `libfuse3` directly. ## Verify ```ts theme={null} import { Mount, MountBackend, MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node' const ws = new Workspace({ '/data': new Mount(new RAMVFS(), { mode: MountMode.WRITE, backend: MountBackend.FUSE }), }) await ws.fuseReady() await ws.shell('echo hello | tee /data/x.txt') console.log('mountpoints:', ws.fuseMountpoints) // Any tool (ls, cat, external subprocess) can now see x.txt under the mountpoint. await ws.close() // auto-unmounts ``` If `ws.fuseMountpoints` prints a `mirage-fuse-XXXXXX` path under `os.tmpdir()` and no error is thrown, the binding is wired up correctly. Mounts are async, so `await ws.fuseReady()` once after constructing the workspace; it resolves when every kernel mount is live (and rejects if one fails to mount). Until then `ws.fuseMountpoints` may be empty. (In Python, where mounts are synchronous, the constructor blocks until ready instead.) The folder is served on Node's event loop. Never block it on the folder: a synchronous `fs` call there, or a child process spawned with `cwd` inside it, waits on a call only that loop can answer. Use the async `fs` API, or pass the folder's paths as arguments to the child. ## Per-mount backends How a mount is exposed is configured **per mount**, through one `backend` field: | `backend` | Effect | | - | - | | `workspace` (default) | Lives only inside mirage's own filesystem, reached through the command surface. Nothing is registered with the kernel. | | `fuse` | Also exposed as a real mountpoint via FUSE. | | `fskit` | Also exposed as a real mountpoint via FSKit, with no kernel extension. macOS 15.4+ only; see below. | | `nfs` | Also exposed as a real mountpoint through the operating system's NFS client: mirage serves NFSv3 on a local port and runs the system `mount`, so no FUSE install is needed. Linux and macOS; Linux needs root to mount. Read-only. A mount that does not set `sizesAlwaysKnown` still mounts, with a warning, but its size-unknown files read as empty; use `fuse` for it. | A kernel-backed mount shows only that mount's subtree. `mountpoint` pins where it lands; omit it for a fresh temp directory: ```yaml theme={null} mode: WRITE mounts: /data: vfs: ram backend: fuse mountpoint: /tmp/data-repo # explicit path /s3: vfs: s3 backend: fuse # temp directory ``` Programmatically, set `backend` per mount: `{ '/data': new Mount(dataVfs, { backend: MountBackend.FUSE, mountpoint: '/tmp/data-repo' }), '/s3': new Mount(s3Vfs, { backend: MountBackend.FUSE }) }`. `ws.fuseMountpoints` returns a `{ prefix: path }` map of the live mountpoints. ## Mounting without the kernel extension (FSKit) Apple has deprecated third-party kernel extensions; FSKit (macOS 15.4+) is the supported userspace replacement, and macFUSE 5.x serves the same libfuse API through it. This works from TypeScript: `fuse.node` links `/usr/local/lib/libfuse.2.dylib` by absolute path, so `backend: 'fskit'` reaches the same macFUSE 5.x libfuse the Python package uses, keeping real mounts working on Macs where the kext is blocked. Only the kernel-to-userspace hop changes: ```mermaid theme={null} flowchart LR A[cat /Volumes/.../file] --> K[kernel VFS] K -->|backend=fuse| X[macFUSE kext] --> L[libfuse] K -->|backend=fskit| F[fskitd + macFUSE FSKit module] --> L L --> M[MirageFS] --> R[vfs] ``` ```ts theme={null} import { Mount, MountBackend, RAMVFS, Workspace } from '@struktoai/mirage-node' const dataVfs = new RAMVFS() const ws = new Workspace({ '/data': new Mount(dataVfs, { backend: MountBackend.FSKIT }), }) await ws.fuseReady() ws.fuseMountpoints['/data'] // => /Volumes/mirage-<id>, tagged fskit ``` The same rules as Python apply, checked at mount time: macOS-only, the mountpoint must be under `/Volumes` (named by mirage, created by the system), and every mounted VFS should report exact sizes (`sizesAlwaysKnown`; the `checkSizes` guard warns about anything else by name, and those files read as empty). **TS fskit mounts are read-mostly**, twice over. The shim's data-write zeroing (see [the Python page](/python/setup/fuse#mounting-without-the-kernel-extension-fskit)) applies to both languages, and `checkWrites` warns at mount time on writable fskit mounts. On top of that, TypeScript cannot create new names: `create`, `mkdir` and `rename` return ENOSYS (and a failed create can still apply). The shim finalizes new items through macFUSE's Darwin-only `setattr_x`/`renamex` callbacks, which Python installs at runtime (`mirage/fuse/darwin.py`) but `@zkochan/fuse-native`'s compiled op table cannot gain from JavaScript. > [!WARNING] > > **A wedged FSKit mount blocks more than itself.** A TS mount is served by > the mounting process's event loop, and in testing an FSKit mount > intermittently hung on a write op even when probed from child processes. > A dead FSKit volume blocks `mount`-table enumeration system-wide until > the macFUSE FSKit extension process is killed. Prefer `backend: 'fuse'` > for anything long-running or write-heavy; treat `fskit` from TypeScript > as read-mostly and experimental. `examples/typescript/fuse/fskit.ts` is > the live end-to-end check. ## Size semantics for API-backed files Some mounts (Linear, Trello, Slack, ...) cannot report a file's size without fetching its content, so over the FUSE mount those files behave like Linux `/proc` files: they stat as **0 bytes until first open** and become fully readable the moment anything opens them. See [Limitations → Size-unknown API files](/typescript/limitations#3-size-unknown-api-files-stat-as-0-bytes-until-first-open) for the per-tool table and the mechanics (`direct_io` + `attr_timeout=0`). > [!NOTE] > > FUSE on Node has two runtime constraints worth knowing: `patchNodeFs` can't patch ESM `node:fs` imports, and synchronous access to your own mount from the mounting process deadlocks the event loop that serves it. See [TypeScript Limitations](/typescript/limitations) for details and workarounds. > [!WARNING] > > **macOS allows only one in-process FUSE mount.** macFUSE registers a > process-global signal source, so a second simultaneous mount in the same > process fails. Multiple per-mount FUSE mounts work on Linux; on macOS, enable > a kernel backend on a single mount per workspace (or run extra mounts in separate > processes). ## Symlinks and Permissions Symlinks live in Mirage's namespace, not in any backend. Links created with `ln -s` in the Mirage shell (or with `ln -s` inside the mountpoint) appear as real symlinks over FUSE: `ls -l` shows `lrwxrwxrwx`, `readlink` prints the target, and reads follow the link. Absolute targets are displayed relative to the link's directory so they always resolve inside the mountpoint. Permission bits shown over FUSE come from Mirage's metadata (`chmod`, `chown`, `touch` results), and they are **display only**: access control is enforced by Mirage mount modes, not by the kernel. For that reason, never mount with the `default_permissions` FUSE option. It would make the kernel enforce the displayed bits, and a `chmod 000` could lock Mirage out of its own files. Extended attributes over FUSE are the ones the Mirage shell's `getfattr` and `setfattr` read and write. Mirage stores them in its namespace beside the symlinks, so every backend takes them. # Google Calendar Source: https://docs.mirage.strukto.ai/typescript/setup/gcal Mount Google Calendar calendars and events as JSON files from Node or the browser. `GCalVFS` exposes every calendar the account can see as a directory of date buckets, with one `.gcal.json` file per event. Setup steps for OAuth credentials live at [Google Workspace Credentials](/home/setup/google). For the Python SDK, see [Google Calendar (Python)](/python/vfs/gcal). ## Node ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { GCalVFS, MountMode, Workspace } from '@struktoai/mirage-node' const gcal = new GCalVFS({ clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET!, refreshToken: process.env.GOOGLE_REFRESH_TOKEN!, }) const ws = new Workspace({ '/gcal': gcal }, { mode: MountMode.READ }) const res = await ws.shell('ls /gcal/primary') console.log(res.stdoutText) ``` ## Browser ```bash theme={null} pnpm add @struktoai/mirage-browser ``` ```ts theme={null} import { GCalVFS, MountMode, Workspace } from '@struktoai/mirage-browser' const gcal = new GCalVFS({ accessToken: async () => (await fetch('/api/google-token')).text(), }) const ws = new Workspace({ '/gcal': gcal }, { mode: MountMode.READ }) ``` In the browser, get the access token from your backend so the client secret never reaches the page. `/api/google-token` stands for that endpoint. ## Config | Field | Description | | - | - | | `timeout` 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` secret | OAuth access token, or a function (sync or async) that returns one. Takes precedence over `clientId` and `refreshToken`. | | `clientId` | Google OAuth client ID. Required with `refreshToken` when `accessToken` is unset; mirage then mints and renews access tokens itself. | | `clientSecret` secret | Google OAuth client secret, sent with the refresh-token grant. Omit it for a PKCE client. | | `refreshToken` secret | User's OAuth refresh token. Required with `clientId` when `accessToken` is unset. | | `refreshFn` secret | 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` | One base URL that replaces every Google API host and the OAuth token endpoint, such as a test server. Unset uses Google's hosts. | | `startTime` | Start of the mount's time scope, inclusive: an RFC 3339 timestamp with an explicit timezone and at most millisecond precision. Unset leaves the start open. | | `endTime` | End of the mount's time scope, exclusive, in the same format as `startTime`, which it must follow. Unset leaves the end open. | | `timeZone` | IANA time zone the mount buckets every calendar's days in. Unset uses the primary calendar's zone. | | `bucketDays` default `1` | Days each date directory under a calendar holds: `1` names it by its day, `7` and `30` by its first and last day (`<first>--<last>`). | | `minAccessRole` | List only calendars where the account has at least this access role: `freeBusyReader`, `reader`, `writer` or `owner`. Unset lists every calendar. | | `today` | Day (`YYYY-MM-DD`) the default listing's 90-day future horizon is measured from, for tests and snapshots. Unset uses the current date in the mount's time zone. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Google Calendar mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `gcal`, write | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > primary/ > calendar.json > 2026-08-11/ > <eventId>__0900-1030_Team_Standup.gcal.json > Engineering__team@group.calendar.google.com/ > 2026-08-11/ > ... > ``` > > Reading the tree: > > * `ls /<path>/` lists the calendars. The primary one is always spelled > `primary`; every other directory ends in `__<calendarId>`. > * `ls /<path>/primary/` lists buckets with events from all available > history through today +90 days unless `end_time` is configured. > `start_time`/`end_time` restrict this mount, including direct paths, > date globs and event reads. A date glob such as > `ls /<path>/primary/2027-03-*` selects its own listing range within > that scope, beyond the default future horizon. > * A bucket is one local day, named by its date. A well-formed date > inside the configured scope is a directory even when it holds no > events. Dates outside the scope are absent. > * A file name is `<eventId>__<HHMM-HHMM>_<Title>.gcal.json`. The times > are clamped to that day, so an event running through it reads > `0000-2400`. A multi-day event appears under every day it covers. > * `cat` an event for the unmodified Calendar API payload, including > attendees, description, location and the original start and end with > offsets. > * `calendar.json` carries the calendar's `accessRole` and, in > `bucketTimeZone`, the zone the buckets are cut in. That zone is > mount-wide, so every calendar's `2026-08-11/` covers the same hours. > * On a calendar shared as free/busy only, Google returns no titles at > all, so events render as `busy`. > > Acting on it: > > * On a `write` path, `rm` an event file to delete that event for every > attendee. > * Everything else goes through the `gws calendar` CLI, which takes the > ids the tree renders. > * A written event must carry an explicit UTC offset or `timeZone`; an > ambiguous local time is not interpreted for you. > > Time scope: `start_time=unbounded` (inclusive), `end_time=unbounded` (exclusive). Explicit paths and globs cannot escape this scope. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest), and `rm` and `unlink`. `grep -r` and `rg` with `-w` ask `gcal` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Not supported: `>`, `>>`, `tee`, `tee -a`, `touch` of a new file, `cp`, `cp -r`, `mkdir`, `mv`, `rm -r`, `rmdir`, `truncate`, `sed -i`. Without `-w`, `grep -r` and `rg` read every file. `gcal` answers only for `*/*/*.gcal.json`; `grep -r` and `rg` read every other 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>` | `gcal`, write | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > primary/ > calendar.json > 2026-08-11/ > <eventId>__0900-1030_Team_Standup.gcal.json > Engineering__team@group.calendar.google.com/ > 2026-08-11/ > ... > ``` > > Reading the tree: > > - `ls /<path>/` lists the calendars. The primary one is always spelled > `primary`; every other directory ends in `__<calendarId>`. > - `ls /<path>/primary/` lists buckets with events from all available > history through today +90 days unless `end_time` is configured. > `start_time`/`end_time` restrict this mount, including direct paths, > date globs and event reads. A date glob such as > `ls /<path>/primary/2027-03-*` selects its own listing range within > that scope, beyond the default future horizon. > - A bucket is one local day, named by its date. A well-formed date > inside the configured scope is a directory even when it holds no > events. Dates outside the scope are absent. > - A file name is `<eventId>__<HHMM-HHMM>_<Title>.gcal.json`. The times > are clamped to that day, so an event running through it reads > `0000-2400`. A multi-day event appears under every day it covers. > - `cat` an event for the unmodified Calendar API payload, including > attendees, description, location and the original start and end with > offsets. > - `calendar.json` carries the calendar's `accessRole` and, in > `bucketTimeZone`, the zone the buckets are cut in. That zone is > mount-wide, so every calendar's `2026-08-11/` covers the same hours. > - On a calendar shared as free/busy only, Google returns no titles at > all, so events render as `busy`. > > Acting on it: > > - On a `write` path, `rm` an event file to delete that event for every > attendee. > - Everything else goes through the `gws calendar` CLI, which takes the > ids the tree renders. > - A written event must carry an explicit UTC offset or `timeZone`; an > ambiguous local time is not interpreted for you. > > Time scope: `start_time=unbounded` (inclusive), `end_time=unbounded` (exclusive). Explicit paths and globs cannot escape this scope. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest), and `rm` and `unlink`. `grep -r` and `rg` with `-w` ask `gcal` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Not supported: `>`, `>>`, `tee`, `tee -a`, `touch` of a new file, `cp`, `cp -r`, `mkdir`, `mv`, `rm -r`, `rmdir`, `truncate`, `sed -i`. Without `-w`, `grep -r` and `rg` read every file. `gcal` answers only for `*/*/*.gcal.json`; `grep -r` and `rg` read every other 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. > ```` ## Write Support The only write is `rm` on an event file, on a mount in `MountMode.WRITE`. It deletes the event on its calendar, for every attendee. The account needs the `owner` or `writer` role on that calendar; otherwise `rm` fails with permission denied. Creating, editing and moving events go through the [`gws calendar`](/home/setup/cli/gws) CLI, which takes the calendar and event ids the tree shows. # Google Cloud Storage Source: https://docs.mirage.strukto.ai/typescript/setup/gcs Set up Google Cloud Storage as a MIRAGE VFS from Node or the browser. GCS exposes an S3-compatible API when you use HMAC keys, so MIRAGE signs GCS requests with the same AWS Signature V4 used for S3, against the endpoint `https://storage.googleapis.com`. Credentials (HMAC access key + secret for a service account) are created the same way in both runtimes, see [GCS Credentials](/home/setup/gcs). ## Node (server-side) ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { GCSVFS, MountMode, Workspace } from '@struktoai/mirage-node' const gcs = new GCSVFS({ bucket: process.env.GCS_BUCKET!, accessKeyId: process.env.GCS_ACCESS_KEY_ID!, secretAccessKey: process.env.GCS_SECRET_ACCESS_KEY!, }) const ws = new Workspace({ '/bucket/': gcs }, { mode: MountMode.READ }) const res = await ws.shell('ls /bucket/') console.log(res.stdoutText) ``` ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `accessKeyId` secret | Access key ID; set it with `secretAccessKey`. Unset uses the AWS SDK credential chain. | | `secretAccessKey` secret | Secret access key paired with `accessKeyId`. | | `sessionToken` secret | Session token for temporary credentials, sent with the access key pair. | | `profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `forcePathStyle` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `keyPrefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `timeout` 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. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | | `region` default `'auto'` | Region requests are signed for; GCS serves every region from one host. | | `endpoint` default `'https://storage.googleapis.com'` | Endpoint URL of the S3 interoperability API. | Fields marked secret are redacted in snapshots. ## Browser (presigned URLs) ```bash theme={null} pnpm add @struktoai/mirage-browser ``` The browser `GCSVFS` is secret-free, your backend signs each operation using your HMAC keys and hands back a URL. Since GCS accepts AWS Signature V4, the same `@aws-sdk/s3-request-presigner` code used for S3 works, pointed at the GCS endpoint. ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `presignedUrlProvider` required, secret | Function `(path, operation, options)` that returns a signed URL for each S3 operation; your server signs it, so the browser holds no keys. | | `region` default `'auto'` | Region the presigned URLs are signed for; GCS accepts `auto`. | | `endpoint` default `'https://storage.googleapis.com'` | Endpoint URL of the GCS XML API. Requests go to the host each presigned URL names; the mount uses it to name its storage location. | | `defaultContentType` default `'application/octet-stream'` | `Content-Type` stored with every object the mount writes. | | `keyPrefix` | Key prefix the mount treats as its root. The browser can change it before a URL is signed, so enforce the prefix on the signing server. | | `timeout` 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. | Fields marked secret are redacted in snapshots. ### 1. Server: sign URLs with the GCS endpoint ```ts theme={null} import { CopyObjectCommand, DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client, } from '@aws-sdk/client-s3' import { getSignedUrl } from '@aws-sdk/s3-request-presigner' const client = new S3Client({ region: 'auto', endpoint: 'https://storage.googleapis.com', credentials: { accessKeyId: process.env.GCS_ACCESS_KEY_ID!, secretAccessKey: process.env.GCS_SECRET_ACCESS_KEY!, }, }) const BUCKET = process.env.GCS_BUCKET! app.post('/presign/gcs', async (req, res) => { const { path, op, opts } = req.body const key = path.replace(/^\/+/, '') const ttl = typeof opts?.ttlSec === 'number' ? opts.ttlSec : 300 let cmd switch (op) { case 'GET': cmd = new GetObjectCommand({ Bucket: BUCKET, Key: key }); break case 'PUT': cmd = new PutObjectCommand({ Bucket: BUCKET, Key: key, ContentType: opts?.contentType }); break case 'HEAD': cmd = new HeadObjectCommand({ Bucket: BUCKET, Key: key }); break case 'DELETE': cmd = new DeleteObjectCommand({ Bucket: BUCKET, Key: key }); break case 'LIST': cmd = new ListObjectsV2Command({ Bucket: BUCKET, Prefix: opts?.listPrefix, Delimiter: opts?.listDelimiter, ContinuationToken: opts?.listContinuationToken, }); break case 'COPY': cmd = new CopyObjectCommand({ Bucket: BUCKET, Key: key, CopySource: `${BUCKET}/${opts?.copySource}`, }); break } res.json({ url: await getSignedUrl(client, cmd, { expiresIn: ttl }) }) }) ``` ### 2. Browser: wire it up ```ts theme={null} import { GCSVFS, MountMode, Workspace } from '@struktoai/mirage-browser' const gcs = new GCSVFS({ bucket: 'my-gcs-bucket', presignedUrlProvider: async (path, op, opts) => { const r = await fetch('/presign/gcs', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path, op, opts }), }) const { url } = await r.json() return url }, }) const ws = new Workspace({ '/bucket/': gcs }, { mode: MountMode.READ }) ``` > [!NOTE] > > If you prefer Google's native signer (Google-provided IAM-signed URLs via `@google-cloud/storage`'s `getSignedUrl`), you can use it here too, the presigner contract only cares that the returned URL works with `fetch()`. Native signing avoids shipping HMAC keys to your backend. ### 3. Configure CORS on the bucket GCS rejects S3-flavored `PutBucketCors` calls, its CORS schema differs. Use **either** the native XML API (via HMAC keys, same creds your presigner uses) **or** `gsutil cors set`. **Option A, helper script (no gcloud install):** The browser example ships a signer that crafts the GCS-shaped CORS XML and submits it via AWS SigV4 to `https://storage.googleapis.com/<bucket>?cors`: ```bash theme={null} cd examples/browser npx tsx scripts/configure-gcs-cors.ts http://localhost:5173 https://app.example.com ``` **Option B, `gsutil`:** ```bash theme={null} brew install google-cloud-sdk gcloud auth login cat > cors.json <<'EOF' [ { "origin": ["http://localhost:5173", "https://app.example.com"], "method": ["GET", "PUT", "HEAD", "DELETE", "POST"], "responseHeader": ["Content-Type", "ETag", "Last-Modified"], "maxAgeSeconds": 3000 } ] EOF gsutil cors set cors.json gs://$GCS_BUCKET ``` > [!WARNING] > > GCS's XML API accepts `<CorsConfig><Cors><Origins>…</Origins><Methods>…</Methods><ResponseHeaders>…</ResponseHeaders><MaxAgeSec>…</MaxAgeSec></Cors></CorsConfig>`. There is no `<Headers>` / `<AllowedHeaders>` element, GCS allows all request headers through automatically. See the [GCS VFS](/python/vfs/gcs) docs for the equivalent Python wiring. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Google Cloud Storage mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Integration What GCS answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On GCS | | - | - | | `md5sum` | The object's ETag, when it is the MD5: a single-part upload, unencrypted or under SSE-S3 | | `find`, `du`, `ls -R`, `tree` | One recursive listing | # Google Docs Source: https://docs.mirage.strukto.ai/typescript/setup/gdocs Mount Google Docs as JSON-backed files from Node or the browser. `GDocsVFS` exposes Google Docs as `.gdoc.json` files. Reads return the document's structured content. Setup steps for OAuth credentials live at [Google Workspace Credentials](/home/setup/google). ## Node ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { GDocsVFS, MountMode, Workspace } from '@struktoai/mirage-node' const docs = new GDocsVFS({ clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET!, refreshToken: process.env.GOOGLE_REFRESH_TOKEN!, }) const ws = new Workspace({ '/docs': docs }, { mode: MountMode.WRITE }) await ws.shell('cat /docs/owned/MyDoc.gdoc.json') ``` ## Browser ```bash theme={null} pnpm add @struktoai/mirage-browser ``` ```ts theme={null} import { GDocsVFS, MountMode, Workspace } from '@struktoai/mirage-browser' const docs = new GDocsVFS({ clientId: GOOGLE_CLIENT_ID, clientSecret: GOOGLE_CLIENT_SECRET, refreshToken: localStorage.getItem('gdocs.refresh_token')!, }) const ws = new Workspace({ '/docs': docs }, { mode: MountMode.WRITE }) ``` A PKCE example lives at `examples/browser/vfs/gdocs/gdocs_pkce.ts`. ## Config | Field | Description | | - | - | | `timeout` 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` secret | OAuth access token, or a function (sync or async) that returns one. Takes precedence over `clientId` and `refreshToken`. | | `clientId` | Google OAuth client ID. Required with `refreshToken` when `accessToken` is unset; mirage then mints and renews access tokens itself. | | `clientSecret` secret | Google OAuth client secret, sent with the refresh-token grant. Omit it for a PKCE client. | | `refreshToken` secret | User's OAuth refresh token. Required with `clientId` when `accessToken` is unset. | | `refreshFn` secret | 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` | One base URL that replaces every Google API host and the OAuth token endpoint, such as a test server. Unset uses Google's hosts. | Fields marked secret are redacted in snapshots. ## Mount mode `read`. A `MountMode.WRITE` mount also allows `mv` (retitle) and `rm` (delete). Append text with the [gws CLI](/typescript/cli/gws). For the JSON shape see the [Python Google Docs docs](/python/vfs/gdocs). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Google Docs mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `gdocs`, write | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > owned/ # docs you created > <YYYY-MM-DD>_<title>__<doc-id>.gdoc.json > shared/ # docs others shared with you > <YYYY-MM-DD>_<title>__<doc-id>.gdoc.json > ``` > > * `<YYYY-MM-DD>` is the file's `modifiedTime`, so a date glob such as > `2026-05-*` narrows by it. > * `<title>` is sanitized: spaces and any character outside > `[A-Za-z0-9_.-]` become `_`, at most 100 characters. > * `<doc-id>` is the Google Docs document id. > * `shared/` holds docs shared with you by others; ones you own > and shared with others are still in `owned/`. > > A `.gdoc.json` holds the Google Docs API `documents.get` response, read > with `includeTabsContent=true` so every tab is present: > > ```jsonc theme={null} > { > "documentId": "...", > "title": "...", > "tabs": [ // one entry per top-level tab > { > "tabProperties": { > "tabId": "t.0", // names a tab for gws docs write > "title": "Tab 1", > "index": 0 > }, > "documentTab": { > "body": { > "content": [ > { // one element per block > "paragraph": { > "elements": [ > { "textRun": { "content": "the actual text\n", > "textStyle": {...} } } > ], > "paragraphStyle": {...} > } > }, > { "table": {...} }, > { "sectionBreak": {...} } > ] > }, > "documentStyle": {...}, > "namedStyles": {...} > }, > "childTabs": [ { ...same shape, nested to any depth... } ] > // a nested tab also carries > // parentTabId and nestingLevel; > // a root tab carries neither > } > ], > "revisionId": "..." > } > ``` > > There is no top-level .body. A tab-aware response leaves the singleton > fields (`.body`, `.documentStyle`, `.namedStyles`) empty and hangs every > tab's content off `.tabs[].documentTab` instead. Tabs also nest, so text > can sit at any depth under `.childTabs`; the recursive recipes below read > a one-tab and a fifty-tab document alike. > > Useful `jq` paths: > > ```jq theme={null} > .title > [.. | .tabProperties? // empty | .title] # every tab name > [.. | .textRun? // empty | .content] | add # all text, any depth > [.. | .tabProperties? // empty] | length # tab count > [.tabs[0].documentTab.body.content[] > | .paragraph?.elements[]?.textRun.content] | add # first tab only > .revisionId > ``` > > The first block of a body is always a `sectionBreak`, which carries no > `.paragraph`, so a path through `.paragraph` needs the `?` or it fails > with `Cannot iterate over null`. > > Delete, on a `write` path: > > ```sh theme={null} > rm /<path>/owned/<file>.gdoc.json # deletes it from Drive for good > rm -f <path> # ignores a missing file > ``` > > Only `.gdoc.json` files can be removed; `owned/` and `shared/` cannot. > > Rename to a new title, on a `write` path: > > ```sh theme={null} > mv /<path>/owned/<date>_<old>__<id>.gdoc.json \ > /<path>/owned/<date>_<new>__<id>.gdoc.json > ``` > > Keep the folder, the date and the id, and spell the title the way the > listing does (spaces become `_`); any other name is refused. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest), and `mv`, `rm` and `unlink`. `grep -r` and `rg` with `-w` ask `gdocs` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Not supported: `>`, `>>`, `tee`, `tee -a`, `touch` of a new file, `cp`, `cp -r`, `mkdir`, `rm -r`, `rmdir`, `truncate`, `sed -i`. 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>` | `gdocs`, write | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > owned/ # docs you created > <YYYY-MM-DD>_<title>__<doc-id>.gdoc.json > shared/ # docs others shared with you > <YYYY-MM-DD>_<title>__<doc-id>.gdoc.json > ``` > > - `<YYYY-MM-DD>` is the file's `modifiedTime`, so a date glob such as > `2026-05-*` narrows by it. > - `<title>` is sanitized: spaces and any character outside > `[A-Za-z0-9_.-]` become `_`, at most 100 characters. > - `<doc-id>` is the Google Docs document id. > - `shared/` holds docs shared with you by others; ones you own > and shared with others are still in `owned/`. > > A `.gdoc.json` holds the Google Docs API `documents.get` response, read > with `includeTabsContent=true` so every tab is present: > > ```jsonc > { > "documentId": "...", > "title": "...", > "tabs": [ // one entry per top-level tab > { > "tabProperties": { > "tabId": "t.0", // names a tab for gws docs write > "title": "Tab 1", > "index": 0 > }, > "documentTab": { > "body": { > "content": [ > { // one element per block > "paragraph": { > "elements": [ > { "textRun": { "content": "the actual text\n", > "textStyle": {...} } } > ], > "paragraphStyle": {...} > } > }, > { "table": {...} }, > { "sectionBreak": {...} } > ] > }, > "documentStyle": {...}, > "namedStyles": {...} > }, > "childTabs": [ { ...same shape, nested to any depth... } ] > // a nested tab also carries > // parentTabId and nestingLevel; > // a root tab carries neither > } > ], > "revisionId": "..." > } > ``` > > There is no top-level .body. A tab-aware response leaves the singleton > fields (`.body`, `.documentStyle`, `.namedStyles`) empty and hangs every > tab's content off `.tabs[].documentTab` instead. Tabs also nest, so text > can sit at any depth under `.childTabs`; the recursive recipes below read > a one-tab and a fifty-tab document alike. > > Useful `jq` paths: > > ```jq > .title > [.. | .tabProperties? // empty | .title] # every tab name > [.. | .textRun? // empty | .content] | add # all text, any depth > [.. | .tabProperties? // empty] | length # tab count > [.tabs[0].documentTab.body.content[] > | .paragraph?.elements[]?.textRun.content] | add # first tab only > .revisionId > ``` > > The first block of a body is always a `sectionBreak`, which carries no > `.paragraph`, so a path through `.paragraph` needs the `?` or it fails > with `Cannot iterate over null`. > > Delete, on a `write` path: > > ```sh > rm /<path>/owned/<file>.gdoc.json # deletes it from Drive for good > rm -f <path> # ignores a missing file > ``` > > Only `.gdoc.json` files can be removed; `owned/` and `shared/` cannot. > > Rename to a new title, on a `write` path: > > ```sh > mv /<path>/owned/<date>_<old>__<id>.gdoc.json \ > /<path>/owned/<date>_<new>__<id>.gdoc.json > ``` > > Keep the folder, the date and the id, and spell the title the way the > listing does (spaces become `_`); any other name is refused. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest), and `mv`, `rm` and `unlink`. `grep -r` and `rg` with `-w` ask `gdocs` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Not supported: `>`, `>>`, `tee`, `tee -a`, `touch` of a new file, `cp`, `cp -r`, `mkdir`, `rm -r`, `rmdir`, `truncate`, `sed -i`. 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. > ```` ## Integration What Google Docs answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Google Docs | | - | - | | `grep -r`, `rg` | Drive full-text search, for whole words. It can miss words only in non-text values (fonts, links and ids) or split by styling. | The [Python Google Docs docs](/python/vfs/gdocs#integration) list when each search answers and what it can miss. # Google Drive Source: https://docs.mirage.strukto.ai/typescript/setup/gdrive Mount Google Drive as a Mirage filesystem from Node or the browser. `GoogleDriveVFS` exposes a user's Drive (My Drive plus shared drives the user can see) as a tree. Setup steps for OAuth credentials live at [Google Workspace Credentials](/home/setup/google). ## Node ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```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({ '/drive': drive }, { mode: MountMode.WRITE }) await ws.shell('ls /drive/') ``` ## Browser ```bash theme={null} pnpm add @struktoai/mirage-browser ``` ```ts theme={null} import { GoogleDriveVFS, MountMode, Workspace } from '@struktoai/mirage-browser' const drive = new GoogleDriveVFS({ clientId: GOOGLE_CLIENT_ID, clientSecret: GOOGLE_CLIENT_SECRET, refreshToken: localStorage.getItem('gdrive.refresh_token')!, }) const ws = new Workspace({ '/drive': drive }, { mode: MountMode.WRITE }) ``` The browser examples in `examples/browser/vfs/gdrive/gdrive_pkce.ts` show a full PKCE flow that keeps the secret out of the page. ## Config | Field | Description | | - | - | | `timeout` 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` secret | OAuth access token, or a function (sync or async) that returns one. Takes precedence over `clientId` and `refreshToken`. | | `clientId` | Google OAuth client ID. Required with `refreshToken` when `accessToken` is unset; mirage then mints and renews access tokens itself. | | `clientSecret` secret | Google OAuth client secret, sent with the refresh-token grant. Omit it for a PKCE client. | | `refreshToken` secret | User's OAuth refresh token. Required with `clientId` when `accessToken` is unset. | | `refreshFn` secret | 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` | 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` | 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. ## Mount mode `read`, `write` and `exec`. Under write mode the standard write commands (`tee`, `cp`, `mv`, `rm`, `mkdir`, `sed -i`, ...) work on regular files and folders; Google-native files (`.gdoc.json`, `.gsheet.json`, `.gslide.json`) are mutated through the `gws` commands instead. Use `MountMode.EXEC` if `python3` or `js` should run scripts from the mount. A Shared Drive is writable on the same terms as My Drive: every Drive call carries `supportsAllDrives`, so what you may change is decided by your role on that drive rather than by the mount, and a role that forbids the change fails with `EACCES` on that operand. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Google Drive mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `gdrive`, write | > > #### 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 > ``` > > * There is no `owned/` and `shared/` split: this is your full Drive > view, including files shared with you that were added to My Drive. > * This is a remote mount: prefer targeted reads over full scans. A > date-prefixed glob (`2026-05-*`) becomes a Drive `modifiedTime` range > query. > * To act on Drive items by id (create, update, export, permissions), use > the `gws` CLI if installed (`gws drive --help`). > > #### 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`, write | > > ## 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 > ``` > > - There is no `owned/` and `shared/` split: this is your full Drive > view, including files shared with you that were added to My Drive. > - This is a remote mount: prefer targeted reads over full scans. A > date-prefixed glob (`2026-05-*`) becomes a Drive `modifiedTime` range > query. > - To act on Drive items by id (create, update, export, permissions), use > the `gws` CLI if installed (`gws drive --help`). > > ## 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. > ```` ## Integration What Google Drive answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Google Drive | | - | - | | `grep -r`, `rg` | Drive full-text search, for whole words (`-w`, `-x`). It can miss Docs, Sheets and Slides JSON, office files, PDFs, archives, the end of large files, words Drive splits differently (`foo.bar`) and recent writes. | | `md5sum`, `sha1sum`, `sha256sum` | The digest Drive keeps; a Docs, Sheets or Slides file is read | | `find`, `du`, `ls -R`, `tree` | One recursive listing | The [Python Google Drive docs](/python/vfs/gdrive#integration) list when each search answers and what it can miss. # GitHub Source: https://docs.mirage.strukto.ai/typescript/setup/github Mount a GitHub repository as a Mirage filesystem from Node or the browser. `GitHubVFS` exposes a single repository at a ref as a read-only filesystem. Reads stream blobs through GitHub's [REST API](https://docs.github.com/en/rest); it does not imitate another CLI. Setup steps for the personal access token live at [GitHub Credentials](/home/setup/github). ## Node ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { GitHubVFS, MountMode, Workspace } from '@struktoai/mirage-node' const gh = await GitHubVFS.create({ token: process.env.GITHUB_TOKEN!, owner: 'strukto-ai', repo: 'mirage', ref: 'main', }) const ws = new Workspace({ '/repo': gh }, { mode: MountMode.READ }) await ws.shell('cat /repo/README.md') ``` The constructor is private: `create` fetches the repo's git tree before it builds the VFS, so it has to be awaited. Python deliberately differs here: `GitHubVFS(...)` is an ordinary call that contacts nothing, and hydrates the tree on first read, which is what lets its `build_vfs` stay synchronous. ## Browser ```bash theme={null} pnpm add @struktoai/mirage-browser ``` ```ts theme={null} import { GitHubVFS, MountMode, Workspace } from '@struktoai/mirage-browser' const gh = await GitHubVFS.create({ token: GITHUB_TOKEN, owner: 'strukto-ai', repo: 'mirage', }) ``` The token reaches the browser, so use a fine-grained PAT scoped to read-only access on a single repo. ## Config | Field | Description | | - | - | | `timeout` 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. | | `token` required, secret | GitHub personal access token. | | `owner` required | Repository owner, a user or an organization. | | `repo` required | Repository name. | | `ref` | Branch, tag or commit SHA the mount reads. Unset uses the repository's default branch, resolved when the mount is created. | | `baseUrl` default `'https://api.github.com'` | GitHub API root; set it for GitHub Enterprise. | Fields marked secret are redacted in snapshots. ## Listings under `fresh` Under `read: fresh`, a cached listing is checked against the head commit the `ref` resolves to: one small check per command (a shallow `git/trees/{ref}`), after which every cached listing of the mount at that commit is served. A mount whose `ref` is a full 40- or 64-hex commit sha serves its cached listings with no request: github.com refuses a branch or tag named with 40 or 64 hex characters, so such a ref always names a commit (a GitHub Enterprise host is assumed to do the same). A repository whose recursive tree comes back truncated stores no version, so each folder is re-listed once per command. ## Mount mode `read`. Writes are not yet exposed. For the mounted layout (refs, paths, blob caching) see the [Python GitHub docs](/python/vfs/github). ## Integration What GitHub answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On GitHub | | - | - | | `grep -r`, `rg` | GitHub code search, for whole words, on the default branch, under a path with more than 100 files. It can miss recent pushes. | | `find`, `du`, `ls -R`, `tree` | One recursive tree listing | The [Python GitHub docs](/python/vfs/github#integration) list when each search answers and what it can miss. # Gmail Source: https://docs.mirage.strukto.ai/typescript/setup/gmail Mount a Gmail mailbox as a Mirage filesystem from Node or the browser. `GmailVFS` browses labels, messages, and attachments via the Gmail API. Both runtimes share the same OAuth config: a Google Cloud `clientId` / `clientSecret` plus a long-lived `refreshToken` for the user. Setup steps live at [Google Workspace Credentials](/home/setup/google). ## Node ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { GmailVFS, MountMode, Workspace } from '@struktoai/mirage-node' const gmail = new GmailVFS({ clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET!, refreshToken: process.env.GOOGLE_REFRESH_TOKEN!, }) const ws = new Workspace({ '/mail': gmail }, { mode: MountMode.READ }) await ws.shell('ls /mail/INBOX/') ``` ## Browser ```bash theme={null} pnpm add @struktoai/mirage-browser ``` ```ts theme={null} import { GmailVFS, MountMode, Workspace } from '@struktoai/mirage-browser' const gmail = new GmailVFS({ clientId: GOOGLE_CLIENT_ID, clientSecret: GOOGLE_CLIENT_SECRET, refreshToken: localStorage.getItem('gmail.refresh_token')!, }) const ws = new Workspace({ '/mail': gmail }, { mode: MountMode.READ }) ``` For OAuth in a browser, prefer PKCE so secrets stay off the page; the [Google setup guide](/home/setup/google) shows the flow. ## Config | Field | Description | | - | - | | `timeout` 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` secret | OAuth access token, or a function (sync or async) that returns one. Takes precedence over `clientId` and `refreshToken`. | | `clientId` | Google OAuth client ID. Required with `refreshToken` when `accessToken` is unset; mirage then mints and renews access tokens itself. | | `clientSecret` secret | Google OAuth client secret, sent with the refresh-token grant. Omit it for a PKCE client. | | `refreshToken` secret | User's OAuth refresh token. Required with `clientId` when `accessToken` is unset. | | `refreshFn` secret | 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` | One base URL that replaces every Google API host and the OAuth token endpoint, such as a test server. Unset uses Google's hosts. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Gmail mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `gmail`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > <label>/ > <yyyy-mm-dd>/ > <subject>__<message-id>.gmail.json # the email, body included > <subject>__<message-id>/ # its attachments, if any > <attachment-filename> > ``` > > * `<label>` is a Gmail label: `INBOX`, `SENT`, `DRAFT`, `IMPORTANT`, > `STARRED`, `TRASH`, `SPAM` or any user label. > * `<yyyy-mm-dd>` is the date the message was received. Listing one > (`ls /<path>/INBOX/2026-05-03/`) pushes `after:`/`before:` into the > Gmail query, much cheaper than scanning the whole label. > * `<subject>` is sanitized: `ls` the date directory rather than > construct it. `<message-id>` is the Gmail message id. > * The email body is in the `.gmail.json` file; read it with `cat`, > `head` or `jq`, keeping the suffix. The sibling directory, the same > name without the extension, holds attachments only: `cat` one to > download its bytes. `grep -r` over a date directory skips these binary > files. > * A `grep` or `rg` hit names the `.gmail.json` file, not the attachments > directory. To list a message's attachments, `ls` its path with > `.gmail.json` stripped; `ENOENT` means it has none: > `ls /<path>/INBOX/2026-05-03/<subject>__<message-id>/` > > A `.gmail.json` is processed by Mirage, not the raw Gmail API response: > > ```jsonc theme={null} > { > "id": "...", > "thread_id": "...", > "from": { "name": "...", "email": "..." }, > "to": [ { "name": "...", "email": "..." } ], > "cc": [ ... ], > "subject": "...", > "date": "Mon, 3 May 2026 10:00:00 -0700", > "body_text": "decoded plain-text body", > "snippet": "first ~200 chars from Gmail", > "labels": [ "INBOX", "IMPORTANT", ... ], > "attachments": [ > { "id": "...", "filename": "invoice.pdf", > "mime_type": "application/pdf", "size": 12345 } > ] > } > ``` > > Useful `jq` paths: > > ```jq theme={null} > .subject > .from.email > .body_text > .labels[] > .attachments[] | .filename > ``` > > To act on messages (read by id, triage, raw API calls), use the `gws` > CLI if installed (`gws gmail --help`). > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `gmail` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `gmail` answers only for `*/*/*.gmail.json`; `grep -r` and `rg` read every other 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>` | `gmail`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > <label>/ > <yyyy-mm-dd>/ > <subject>__<message-id>.gmail.json # the email, body included > <subject>__<message-id>/ # its attachments, if any > <attachment-filename> > ``` > > - `<label>` is a Gmail label: `INBOX`, `SENT`, `DRAFT`, `IMPORTANT`, > `STARRED`, `TRASH`, `SPAM` or any user label. > - `<yyyy-mm-dd>` is the date the message was received. Listing one > (`ls /<path>/INBOX/2026-05-03/`) pushes `after:`/`before:` into the > Gmail query, much cheaper than scanning the whole label. > - `<subject>` is sanitized: `ls` the date directory rather than > construct it. `<message-id>` is the Gmail message id. > - The email body is in the `.gmail.json` file; read it with `cat`, > `head` or `jq`, keeping the suffix. The sibling directory, the same > name without the extension, holds attachments only: `cat` one to > download its bytes. `grep -r` over a date directory skips these binary > files. > - A `grep` or `rg` hit names the `.gmail.json` file, not the attachments > directory. To list a message's attachments, `ls` its path with > `.gmail.json` stripped; `ENOENT` means it has none: > `ls /<path>/INBOX/2026-05-03/<subject>__<message-id>/` > > A `.gmail.json` is processed by Mirage, not the raw Gmail API response: > > ```jsonc > { > "id": "...", > "thread_id": "...", > "from": { "name": "...", "email": "..." }, > "to": [ { "name": "...", "email": "..." } ], > "cc": [ ... ], > "subject": "...", > "date": "Mon, 3 May 2026 10:00:00 -0700", > "body_text": "decoded plain-text body", > "snippet": "first ~200 chars from Gmail", > "labels": [ "INBOX", "IMPORTANT", ... ], > "attachments": [ > { "id": "...", "filename": "invoice.pdf", > "mime_type": "application/pdf", "size": 12345 } > ] > } > ``` > > Useful `jq` paths: > > ```jq > .subject > .from.email > .body_text > .labels[] > .attachments[] | .filename > ``` > > To act on messages (read by id, triage, raw API calls), use the `gws` > CLI if installed (`gws gmail --help`). > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `gmail` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `gmail` answers only for `*/*/*.gmail.json`; `grep -r` and `rg` read every other 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. > ```` ## Integration What Gmail answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Gmail | | - | - | | `grep -r`, `rg` | The message text the listing keeps, for ASCII text. It misses nothing. | The [Python Gmail docs](/python/vfs/gmail#integration) list when each search answers and what it can miss. ## Mount mode `read`. For the mounted layout (labels, dates, attachments) see the [Python Gmail docs](/python/vfs/gmail). # GridFS Source: https://docs.mirage.strukto.ai/typescript/setup/gridfs Mount a MongoDB GridFS bucket as a MIRAGE filesystem from Node. `GridFSVFS` mounts a MongoDB GridFS bucket (file metadata in `<bucket>.files`, content chunks in `<bucket>.chunks`) as a read-write filesystem. Files are keyed by slash-separated filenames, writes keep old revisions, and a walk (`find`, `du`, `ls -R`, `tree`, `grep -r`) reads the whole subtree with one `fs.files` query ([Walks](/home/integration/walks)). Setup steps for the connection URI live at [GridFS Credentials](/home/setup/gridfs). ## Node ```bash theme={null} pnpm add @struktoai/mirage-node mongodb ``` ```ts theme={null} import { GridFSVFS, MountMode, Workspace } from '@struktoai/mirage-node' const gridfs = new GridFSVFS({ uri: process.env.MONGODB_URI!, database: 'app', bucket: 'assets', // default "fs" }) const ws = new Workspace({ '/gridfs/': gridfs }, { mode: MountMode.WRITE }) await ws.shell('echo hello | tee /gridfs/notes/a.txt > /dev/null') const res = await ws.shell("find /gridfs/ -name '*.txt'") console.log(res.stdoutText) ``` The `mongodb` driver is an optional peer dependency; it is only loaded when a `GridFSVFS` is constructed. ### Config | Field | Description | | - | - | | `timeout` 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. | | `uri` required, secret | MongoDB connection URI. | | `database` required | Database that holds the GridFS bucket. | | `bucket` default `'fs'` | GridFS bucket name; its collections are `<bucket>.files` and `<bucket>.chunks`. | | `keyPrefix` | Filename prefix the mount treats as its root; files outside it are not listed. | | `chunkSizeBytes` | Chunk size in bytes for files the mount writes; unset uses the driver's default, 255 KiB. | | `keepRevisions` | Revisions kept per file, newest first: a write or an `rm` deletes the rest, under the file's name and in the trash `rm` moves revisions to (`/trash/<filename>`, which no mount path reaches). Unset keeps every revision, so a snapshot pinned to any of them still reads. | Fields marked secret are redacted in snapshots. ## Scoping to a key prefix ```ts theme={null} const scoped = new GridFSVFS({ uri: process.env.MONGODB_URI!, database: 'app', bucket: 'shared', keyPrefix: `users/${userId}`, }) ``` Every operation is transparently scoped to that subpath: agents see `/data/notes.md`, the stored filename is `users/<id>/data/notes.md`. YAML configs may spell it `key_prefix`; both are accepted. ## Revisions Every write uploads a new revision and keeps the old ones; reads and listings serve the newest per filename, and a snapshot-pinned read resolves an older revision by its `_id`. `mv` retags every revision server-side, and `rm` retags them into the trash, `/trash/<filename>`, which no mount path can reach, so the name reads as gone while a pinned read still works. Set `keepRevisions` (`keep_revisions` in YAML) to delete the revisions past that count per filename on each write or `rm`, oldest first, in the trash too; unset keeps every revision. The [Python page](/python/vfs/gridfs#revisions) has the details. ## Browser GridFS requires a direct MongoDB connection, so `GridFSVFS` ships in `@struktoai/mirage-node` only. Browser workspaces can reach GridFS content through a Node-side MIRAGE server instead. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with GridFS mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Integration What GridFS answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On GridFS | | - | - | | `find`, `du`, `ls -R`, `tree` | One recursive listing | # Google Sheets Source: https://docs.mirage.strukto.ai/typescript/setup/gsheets Mount Google Sheets spreadsheets as Mirage files from Node or the browser. `GSheetsVFS` exposes Google Sheets as `.gsheet.json` files. Reads return cell values. Setup steps for OAuth credentials live at [Google Workspace Credentials](/home/setup/google). ## Node ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { GSheetsVFS, MountMode, Workspace } from '@struktoai/mirage-node' const sheets = new GSheetsVFS({ clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET!, refreshToken: process.env.GOOGLE_REFRESH_TOKEN!, }) const ws = new Workspace({ '/sheets': sheets }, { mode: MountMode.READ }) await ws.shell('ls /sheets/owned/') ``` ## Browser ```bash theme={null} pnpm add @struktoai/mirage-browser ``` ```ts theme={null} import { GSheetsVFS, MountMode, Workspace } from '@struktoai/mirage-browser' const sheets = new GSheetsVFS({ clientId: GOOGLE_CLIENT_ID, clientSecret: GOOGLE_CLIENT_SECRET, refreshToken: localStorage.getItem('gsheets.refresh_token')!, }) ``` ## Config | Field | Description | | - | - | | `timeout` 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` secret | OAuth access token, or a function (sync or async) that returns one. Takes precedence over `clientId` and `refreshToken`. | | `clientId` | Google OAuth client ID. Required with `refreshToken` when `accessToken` is unset; mirage then mints and renews access tokens itself. | | `clientSecret` secret | Google OAuth client secret, sent with the refresh-token grant. Omit it for a PKCE client. | | `refreshToken` secret | User's OAuth refresh token. Required with `clientId` when `accessToken` is unset. | | `refreshFn` secret | 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` | One base URL that replaces every Google API host and the OAuth token endpoint, such as a test server. Unset uses Google's hosts. | Fields marked secret are redacted in snapshots. ## Mount mode `read`. A `MountMode.WRITE` mount also allows `mv` (retitle) and `rm` (delete). Write cells with the [gws CLI](/typescript/cli/gws). For the layout and sheet/tab structure see the [Python Sheets docs](/python/vfs/gsheets). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Google Sheets mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `gsheets`, write | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > owned/ # sheets you created > <YYYY-MM-DD>_<title>__<spreadsheet-id>.gsheet.json > shared/ # sheets others shared with you > <YYYY-MM-DD>_<title>__<spreadsheet-id>.gsheet.json > ``` > > * `<YYYY-MM-DD>` is the file's `modifiedTime`, so a date glob such as > `2026-05-*` narrows by it. > * `<title>` is sanitized: spaces and any character outside > `[A-Za-z0-9_.-]` become `_`, at most 100 characters. > * `<spreadsheet-id>` is the Google Sheets spreadsheet id. > * `shared/` holds sheets shared with you by others; ones you own > and shared with others are still in `owned/`. > > A `.gsheet.json` matches the Google Sheets API `spreadsheets.get` > response: > > ```jsonc theme={null} > { > "spreadsheetId": "...", > "spreadsheetUrl": "...", > "properties": { "title": "...", "locale": "...", "timeZone": "..." }, > "sheets": [ > { // one element per tab > "properties": { > "sheetId": 0, "title": "...", "index": 0, > "gridProperties": { "rowCount": 1000, "columnCount": 26 } > }, > "data": [ > { > "rowData": [ > { "values": [ > { "formattedValue": "...", > "userEnteredValue": {...}, > "effectiveValue": {...} } > ]} // an empty cell is {}, a trailing one absent > ] > } > ] > } > ], > "namedRanges": [...] > } > ``` > > Useful `jq` paths: > > ```jq theme={null} > .properties.title > .sheets[].properties.title # tab names > .sheets[0].data[0].rowData[].values[].formattedValue # cell strings > .namedRanges[] > ``` > > Delete, on a `write` path: > > ```sh theme={null} > rm /<path>/owned/<file>.gsheet.json # deletes it from Drive for good > rm -f <path> # ignores a missing file > ``` > > Only `.gsheet.json` files can be removed; `owned/` and `shared/` cannot. > > Rename to a new title, on a `write` path: > > ```sh theme={null} > mv /<path>/owned/<date>_<old>__<id>.gsheet.json \ > /<path>/owned/<date>_<new>__<id>.gsheet.json > ``` > > Keep the folder, the date and the id, and spell the title the way the > listing does (spaces become `_`); any other name is refused. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest), and `mv`, `rm` and `unlink`. `grep -r` and `rg` with `-w` ask `gsheets` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Not supported: `>`, `>>`, `tee`, `tee -a`, `touch` of a new file, `cp`, `cp -r`, `mkdir`, `rm -r`, `rmdir`, `truncate`, `sed -i`. 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>` | `gsheets`, write | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > owned/ # sheets you created > <YYYY-MM-DD>_<title>__<spreadsheet-id>.gsheet.json > shared/ # sheets others shared with you > <YYYY-MM-DD>_<title>__<spreadsheet-id>.gsheet.json > ``` > > - `<YYYY-MM-DD>` is the file's `modifiedTime`, so a date glob such as > `2026-05-*` narrows by it. > - `<title>` is sanitized: spaces and any character outside > `[A-Za-z0-9_.-]` become `_`, at most 100 characters. > - `<spreadsheet-id>` is the Google Sheets spreadsheet id. > - `shared/` holds sheets shared with you by others; ones you own > and shared with others are still in `owned/`. > > A `.gsheet.json` matches the Google Sheets API `spreadsheets.get` > response: > > ```jsonc > { > "spreadsheetId": "...", > "spreadsheetUrl": "...", > "properties": { "title": "...", "locale": "...", "timeZone": "..." }, > "sheets": [ > { // one element per tab > "properties": { > "sheetId": 0, "title": "...", "index": 0, > "gridProperties": { "rowCount": 1000, "columnCount": 26 } > }, > "data": [ > { > "rowData": [ > { "values": [ > { "formattedValue": "...", > "userEnteredValue": {...}, > "effectiveValue": {...} } > ]} // an empty cell is {}, a trailing one absent > ] > } > ] > } > ], > "namedRanges": [...] > } > ``` > > Useful `jq` paths: > > ```jq > .properties.title > .sheets[].properties.title # tab names > .sheets[0].data[0].rowData[].values[].formattedValue # cell strings > .namedRanges[] > ``` > > Delete, on a `write` path: > > ```sh > rm /<path>/owned/<file>.gsheet.json # deletes it from Drive for good > rm -f <path> # ignores a missing file > ``` > > Only `.gsheet.json` files can be removed; `owned/` and `shared/` cannot. > > Rename to a new title, on a `write` path: > > ```sh > mv /<path>/owned/<date>_<old>__<id>.gsheet.json \ > /<path>/owned/<date>_<new>__<id>.gsheet.json > ``` > > Keep the folder, the date and the id, and spell the title the way the > listing does (spaces become `_`); any other name is refused. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest), and `mv`, `rm` and `unlink`. `grep -r` and `rg` with `-w` ask `gsheets` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Not supported: `>`, `>>`, `tee`, `tee -a`, `touch` of a new file, `cp`, `cp -r`, `mkdir`, `rm -r`, `rmdir`, `truncate`, `sed -i`. 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. > ```` ## Integration What Google Sheets answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Google Sheets | | - | - | | `grep -r`, `rg` | Drive full-text search, for whole words. It can miss words only in non-text values (formulas, the time zone, sheet titles, links and ids). | The [Python Google Sheets docs](/python/vfs/gsheets#integration) list when each search answers and what it can miss. # Google Slides Source: https://docs.mirage.strukto.ai/typescript/setup/gslides Mount Google Slides decks as Mirage files from Node or the browser. `GSlidesVFS` exposes Slides decks as `.gslide.json` files containing the deck structure, slides, and text content. Setup steps for OAuth credentials live at [Google Workspace Credentials](/home/setup/google). ## Node ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { GSlidesVFS, MountMode, Workspace } from '@struktoai/mirage-node' const slides = new GSlidesVFS({ clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET!, refreshToken: process.env.GOOGLE_REFRESH_TOKEN!, }) const ws = new Workspace({ '/slides': slides }, { mode: MountMode.READ }) await ws.shell('ls /slides/owned/') ``` ## Browser ```bash theme={null} pnpm add @struktoai/mirage-browser ``` ```ts theme={null} import { GSlidesVFS, MountMode, Workspace } from '@struktoai/mirage-browser' const slides = new GSlidesVFS({ clientId: GOOGLE_CLIENT_ID, clientSecret: GOOGLE_CLIENT_SECRET, refreshToken: localStorage.getItem('gslides.refresh_token')!, }) ``` ## Config | Field | Description | | - | - | | `timeout` 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` secret | OAuth access token, or a function (sync or async) that returns one. Takes precedence over `clientId` and `refreshToken`. | | `clientId` | Google OAuth client ID. Required with `refreshToken` when `accessToken` is unset; mirage then mints and renews access tokens itself. | | `clientSecret` secret | Google OAuth client secret, sent with the refresh-token grant. Omit it for a PKCE client. | | `refreshToken` secret | User's OAuth refresh token. Required with `clientId` when `accessToken` is unset. | | `refreshFn` secret | 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` | One base URL that replaces every Google API host and the OAuth token endpoint, such as a test server. Unset uses Google's hosts. | Fields marked secret are redacted in snapshots. ## Mount mode `read`. A `MountMode.WRITE` mount also allows `mv` (retitle) and `rm` (delete). Edit a deck with the [gws CLI](/typescript/cli/gws). For the JSON structure (slides, layouts, text frames) see the [Python Slides docs](/python/vfs/gslides). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Google Slides mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `gslides`, write | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > owned/ # presentations you created > <YYYY-MM-DD>_<title>__<presentation-id>.gslide.json > shared/ # presentations others shared with you > <YYYY-MM-DD>_<title>__<presentation-id>.gslide.json > ``` > > * `<YYYY-MM-DD>` is the file's `modifiedTime`, so a date glob such as > `2026-05-*` narrows by it. > * `<title>` is sanitized: spaces and any character outside > `[A-Za-z0-9_.-]` become `_`, at most 100 characters. > * `<presentation-id>` is the Google Slides presentation id. > * `shared/` holds presentations shared with you by others; ones you own > and shared with others are still in `owned/`. > > A `.gslide.json` matches the Google Slides API `presentations.get` > response: > > ```jsonc theme={null} > { > "presentationId": "...", > "title": "...", > "pageSize": { "width": {...}, "height": {...} }, > "slides": [ > { // one element per slide > "objectId": "...", > "pageElements": [ > { > "objectId": "...", > "shape": { > "shapeType": "TEXT_BOX", > "text": { > "textElements": [ > { "textRun": { "content": "the actual text\n", > "style": {...} } } > ] > } > } > }, > { "image": {...} }, > { "table": {...} } > ] > } > ], > "masters": [...], > "layouts": [...] > } > ``` > > Useful `jq` paths: > > ```jq theme={null} > .title > .slides | length # slide count > .slides[].pageElements[].shape.text.textElements[].textRun.content # all text > .slides[0].objectId > ``` > > Delete, on a `write` path: > > ```sh theme={null} > rm /<path>/owned/<file>.gslide.json # deletes it from Drive for good > rm -f <path> # ignores a missing file > ``` > > Only `.gslide.json` files can be removed; `owned/` and `shared/` cannot. > > Rename to a new title, on a `write` path: > > ```sh theme={null} > mv /<path>/owned/<date>_<old>__<id>.gslide.json \ > /<path>/owned/<date>_<new>__<id>.gslide.json > ``` > > Keep the folder, the date and the id, and spell the title the way the > listing does (spaces become `_`); any other name is refused. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest), and `mv`, `rm` and `unlink`. `grep -r` and `rg` with `-w` ask `gslides` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Not supported: `>`, `>>`, `tee`, `tee -a`, `touch` of a new file, `cp`, `cp -r`, `mkdir`, `rm -r`, `rmdir`, `truncate`, `sed -i`. 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>` | `gslides`, write | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > owned/ # presentations you created > <YYYY-MM-DD>_<title>__<presentation-id>.gslide.json > shared/ # presentations others shared with you > <YYYY-MM-DD>_<title>__<presentation-id>.gslide.json > ``` > > - `<YYYY-MM-DD>` is the file's `modifiedTime`, so a date glob such as > `2026-05-*` narrows by it. > - `<title>` is sanitized: spaces and any character outside > `[A-Za-z0-9_.-]` become `_`, at most 100 characters. > - `<presentation-id>` is the Google Slides presentation id. > - `shared/` holds presentations shared with you by others; ones you own > and shared with others are still in `owned/`. > > A `.gslide.json` matches the Google Slides API `presentations.get` > response: > > ```jsonc > { > "presentationId": "...", > "title": "...", > "pageSize": { "width": {...}, "height": {...} }, > "slides": [ > { // one element per slide > "objectId": "...", > "pageElements": [ > { > "objectId": "...", > "shape": { > "shapeType": "TEXT_BOX", > "text": { > "textElements": [ > { "textRun": { "content": "the actual text\n", > "style": {...} } } > ] > } > } > }, > { "image": {...} }, > { "table": {...} } > ] > } > ], > "masters": [...], > "layouts": [...] > } > ``` > > Useful `jq` paths: > > ```jq > .title > .slides | length # slide count > .slides[].pageElements[].shape.text.textElements[].textRun.content # all text > .slides[0].objectId > ``` > > Delete, on a `write` path: > > ```sh > rm /<path>/owned/<file>.gslide.json # deletes it from Drive for good > rm -f <path> # ignores a missing file > ``` > > Only `.gslide.json` files can be removed; `owned/` and `shared/` cannot. > > Rename to a new title, on a `write` path: > > ```sh > mv /<path>/owned/<date>_<old>__<id>.gslide.json \ > /<path>/owned/<date>_<new>__<id>.gslide.json > ``` > > Keep the folder, the date and the id, and spell the title the way the > listing does (spaces become `_`); any other name is refused. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest), and `mv`, `rm` and `unlink`. `grep -r` and `rg` with `-w` ask `gslides` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Not supported: `>`, `>>`, `tee`, `tee -a`, `touch` of a new file, `cp`, `cp -r`, `mkdir`, `rm -r`, `rmdir`, `truncate`, `sed -i`. 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. > ```` ## Integration What Google Slides answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Google Slides | | - | - | | `grep -r`, `rg` | Drive full-text search, for whole words. It can miss words only in non-text values (fonts, links, layout names and ids) or split by styling. | The [Python Google Slides docs](/python/vfs/gslides#integration) list when each search answers and what it can miss. # HF Buckets Source: https://docs.mirage.strukto.ai/typescript/setup/hf_buckets Mount Hugging Face Buckets as a Mirage filesystem in TypeScript with lazy reads and writes. `HfBucketsVFS` mounts a [Hugging Face Bucket](https://huggingface.co/docs/hub/storage-buckets) at a prefix such as `/hf/`. The TypeScript backend mirrors the [Python one](/python/vfs/hf_buckets) and returns identical results. For credential setup, see [HF Buckets Setup](/home/setup/hf_buckets). > [!NOTE] > > Node only. The backend uses the native [opendal](https://www.npmjs.com/package/opendal) > binding, which does not run in the browser. ## Node ```bash theme={null} pnpm add @struktoai/mirage-node opendal ``` ```ts theme={null} import { HfBucketsVFS, MountMode, Workspace } from '@struktoai/mirage-node' const bucket = new HfBucketsVFS({ bucket: process.env.HF_BUCKET_NAME!, // "namespace/bucket-name" token: process.env.HF_TOKEN, // Optional: // endpoint: 'https://huggingface.co', // keyPrefix: 'data/', }) const ws = new Workspace({ '/hf/': bucket }, { mode: MountMode.READ }) console.log((await ws.shell('ls /hf/')).stdoutText) console.log((await ws.shell('tree /hf/')).stdoutText) console.log((await ws.shell("find /hf/ -name '*.json'")).stdoutText) console.log((await ws.shell('stat /hf/data/file.txt')).stdoutText) ``` `HfBucketsVFS` takes the bucket in `namespace/bucket-name` form plus an optional access token. Both `READ` and `WRITE` modes are supported out of the box. ### Config | Field | Description | | - | - | | `bucket` required | Bucket id in `namespace/name` form. | | `token` secret | Hugging Face access token. | | `endpoint` default `'https://huggingface.co'` | Hub origin requests go to, for a mirror or a self-hosted Hub. | | `timeout` 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. | | `keyPrefix` | Path inside the bucket that becomes the mount root; files outside it are not listed. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with HF Buckets mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Not supported: `mv`, `rmdir`. `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Not supported: `mv`, `rmdir`. `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. > ``` Bucket object keys map to virtual paths under the mount prefix: virtual `/hf/data/file.txt` maps to bucket key `data/file.txt`. ## Cache Directory listings are cached with `indexTtl = 600` (10 minutes) and populate file-size/type entries that `stat` reads via a fast path, so a `readdir` followed by per-entry `stat` calls (what `ls` and most shell commands trigger) costs one HTTP request instead of N. A configured `index:` replaces this lifetime with its own `ttl`, and the mount's `ttl:` caps it. ## Integration What Hugging Face buckets answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Hugging Face buckets | | - | - | | `find`, `du`, `ls -R`, `tree` | One recursive listing | ## Shell Commands The same command set as the Python backend, operating on real file content. Large files benefit from range reads to avoid downloading entire objects. ### Read Commands | Command | Notes | | - | - | | `cat` | Read file content | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search (file or directory level) | | `jq` | Query JSON fields | | `wc` | Line/word/byte counts | | `stat` | File metadata (name, size, type, modified) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `nl` | Number lines | | `du` | Disk usage summary | | `file` | Detect file type | | `strings` | Extract printable strings from binary | | `xxd` | Hex dump | | `md5` | MD5 checksum | | `sha256sum` | SHA-256 checksum | ### Text Processing `awk`, `sed`, `tr`, `sort`, `uniq`, `cut`, `join`, `paste`, `column`, `fold`, `expand`, `unexpand`, `fmt`, `rev`, `tac`, `look`, `shuf`, `tsort`, `comm`, `cmp`, `diff`, `iconv`, `base64`. ### File Operations `rm` (`-r` removes a subtree), `mkdir` (a no-op: a directory exists only while it holds a file), `touch`, `mktemp`, `split`, `csplit`. ### Path Utilities `ls`, `basename`, `dirname`, `realpath`, `readlink`. ### Compression `gzip`, `gunzip`, `zcat`, `zgrep`, `tar`, `zip`, `unzip`. # HF Datasets Source: https://docs.mirage.strukto.ai/typescript/setup/hf_datasets Mount a Hugging Face Dataset repo as a Mirage filesystem in TypeScript. `HfDatasetsVFS` mounts a [Hugging Face Dataset](https://huggingface.co/datasets) repo at a prefix such as `/ds/`. All reads are lazy: only the bytes you actually `cat`/`head` get transferred. The TypeScript backend mirrors the [Python one](/python/vfs/hf_datasets) and returns identical results. For credential setup, see [HF Datasets Setup](/home/setup/hf_datasets). > [!NOTE] > > Node only: the VFS ships in `@struktoai/mirage-node`. It needs no native > binding, though, because it speaks the Hub API over the runtime's own `fetch`. > The [opendal](https://www.npmjs.com/package/opendal) binding belongs to > [HF Buckets](/typescript/setup/hf_buckets), which is a different product. ## Node ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { HfDatasetsVFS, MountMode, Workspace } from '@struktoai/mirage-node' const dataset = new HfDatasetsVFS({ repoId: 'AlienKevin/SWE-ZERO-12M-trajectories', // "namespace/dataset-name" token: process.env.HF_TOKEN, // optional for public datasets // Optional: // endpoint: 'https://huggingface.co', // revision: 'main', // keyPrefix: 'train/', }) const ws = new Workspace({ '/ds/': dataset }, { mode: MountMode.READ }) console.log((await ws.shell('ls -lh /ds/')).stdoutText) console.log((await ws.shell("find /ds/ -name '*.parquet' | wc -l")).stdoutText) console.log((await ws.shell('cat /ds/README.md | head -n 20')).stdoutText) ``` `HfDatasetsVFS` takes `repoId` in `namespace/dataset-name` form plus an optional access token. Public datasets need no token. ### Config | Field | Description | | - | - | | `repoId` required | Repository id as `namespace/name`, or a bare `name` that resolves against the token's owner. | | `token` secret | Hugging Face access token; unset sends anonymous requests, which reach public repositories only. | | `endpoint` default `'https://huggingface.co'` | Hub origin requests go to, for a mirror or a self-hosted Hub. | | `timeout` 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. | | `keyPrefix` | Path inside the repository that becomes the mount root; files outside it are not listed. | | `revision` | Branch, tag or commit the mount reads; unset reads `main`. | | `expandCommits` | Fetch each file's last commit so listings carry modification times, at 50 entries per request instead of 1000. Unset does so only when the whole repository fits in one page. | Fields marked secret are redacted in snapshots. ## Reading, not writing This mount is read-only, the way a [`github`](/typescript/setup/github) mount is. A Hub write is a **commit**, and a POSIX write cannot say where a commit ends, so `echo >`, `rm`, `cp` and `mv` are refused here rather than silently making one commit per file. The [`hf` CLI](/typescript/cli/hf) is the write half: `hf download --local-dir` puts a copy on a ram or disk mount, which is an ordinary writable filesystem, and `hf upload` sends it back as a single commit. ## Listings under `fresh` Under `read: fresh`, a cached listing is checked against the commit the `revision` resolves to: one small check per command (`revision/{rev}?expand[]=sha`), after which every cached listing of the mount at that commit is served. A mount whose `revision` is a full 40- or 64-hex commit sha is checked the same way, with that one small request per command: a branch or tag named like the sha could take the name, and mirage does not assume which one the Hub resolves. With a `keyPrefix`, the stored version is that commit joined with the prefix, so mounts of different subtrees sharing an index never share a version. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with HF Datasets mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | read | > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | read | > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ``` Maps dataset repo files (README, parquet shards, etc.) to virtual paths under the mount prefix. Parquet shards stream lazily via byte-range reads. ## Integration What Hugging Face datasets answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Hugging Face datasets | | - | - | | `sha256sum` | The LFS sha256 the Hub keeps; other files are read | ## Shell Commands Every read command in [HF Buckets'](/typescript/setup/hf_buckets#read-commands) set works here, as do the text processing and path utilities, which only read. What does not is the [File Operations](/typescript/setup/hf_buckets#file-operations) group: this mount is read-only, so `rm` and `touch` are refused, as is any command asked to write into it. # HF Models Source: https://docs.mirage.strukto.ai/typescript/setup/hf_models Mount a Hugging Face Model repo as a Mirage filesystem in TypeScript. `HfModelsVFS` mounts a [Hugging Face Model](https://huggingface.co/models) repo at a prefix such as `/m/`. You can inspect configs, tokenizers, and READMEs without downloading the weights, weights stream only when you actually `cat` them. The TypeScript backend mirrors the [Python one](/python/vfs/hf_models) and returns identical results. For credential setup, see [HF Models Setup](/home/setup/hf_models). > [!NOTE] > > Node only: the VFS ships in `@struktoai/mirage-node`. It needs no native > binding, though, because it speaks the Hub API over the runtime's own `fetch`. > The [opendal](https://www.npmjs.com/package/opendal) binding belongs to > [HF Buckets](/typescript/setup/hf_buckets), which is a different product. ## Node ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { HfModelsVFS, MountMode, Workspace } from '@struktoai/mirage-node' const model = new HfModelsVFS({ repoId: 'sapientinc/HRM-Text-1B', // "namespace/model-name" token: process.env.HF_TOKEN, // optional for public repos // Optional: // endpoint: 'https://huggingface.co', // revision: 'main', }) const ws = new Workspace({ '/m/': model }, { mode: MountMode.READ }) // ls is cheap: one HTTP list call console.log((await ws.shell('ls -lh /m/')).stdoutText) // Read the config (small, fast) console.log((await ws.shell('cat /m/config.json')).stdoutText) // Stat the weights without downloading them console.log((await ws.shell('stat /m/model.safetensors')).stdoutText) ``` ### Config | Field | Description | | - | - | | `repoId` required | Repository id as `namespace/name`, or a bare `name` that resolves against the token's owner. | | `token` secret | Hugging Face access token; unset sends anonymous requests, which reach public repositories only. | | `endpoint` default `'https://huggingface.co'` | Hub origin requests go to, for a mirror or a self-hosted Hub. | | `timeout` 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. | | `keyPrefix` | Path inside the repository that becomes the mount root; files outside it are not listed. | | `revision` | Branch, tag or commit the mount reads; unset reads `main`. | | `expandCommits` | Fetch each file's last commit so listings carry modification times, at 50 entries per request instead of 1000. Unset does so only when the whole repository fits in one page. | Fields marked secret are redacted in snapshots. ## Reading, not writing This mount is read-only, the way a [`github`](/typescript/setup/github) mount is. A Hub write is a **commit**, and a POSIX write cannot say where a commit ends, so `echo >`, `rm`, `cp` and `mv` are refused here rather than silently making one commit per file. The [`hf` CLI](/typescript/cli/hf) is the write half: `hf download --local-dir` puts a copy on a ram or disk mount, which is an ordinary writable filesystem, and `hf upload` sends it back as a single commit. ## Listings under `fresh` Under `read: fresh`, a cached listing is checked against the commit the `revision` resolves to: one small check per command (`revision/{rev}?expand[]=sha`), after which every cached listing of the mount at that commit is served. A mount whose `revision` is a full 40- or 64-hex commit sha is checked the same way, with that one small request per command: a branch or tag named like the sha could take the name, and mirage does not assume which one the Hub resolves. With a `keyPrefix`, the stored version is that commit joined with the prefix, so mounts of different subtrees sharing an index never share a version. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with HF Models mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | read | > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | read | > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ``` Maps model repo files (config, tokenizer, weights, etc.) to virtual paths. For example, `sapientinc/HRM-Text-1B` mounted at `/m/` exposes: ```text theme={null} /m/ README.md config.json tokenizer.json tokenizer_config.json model.safetensors ← never downloaded unless you cat it ``` ## Integration What Hugging Face models answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Hugging Face models | | - | - | | `sha256sum` | The LFS sha256 the Hub keeps; other files are read | ## Shell Commands Every read command in [HF Buckets'](/typescript/setup/hf_buckets#read-commands) set works here, as do the text processing and path utilities, which only read. What does not is the [File Operations](/typescript/setup/hf_buckets#file-operations) group: this mount is read-only, so `rm` and `touch` are refused, as is any command asked to write into it. # HF Spaces Source: https://docs.mirage.strukto.ai/typescript/setup/hf_spaces Mount a Hugging Face Space repo as a Mirage filesystem in TypeScript. `HfSpacesVFS` mounts a [Hugging Face Space](https://huggingface.co/spaces) repo (app code, README, config, requirements) at a prefix such as `/s/`. The TypeScript backend mirrors the [Python one](/python/vfs/hf_spaces) and returns identical results. For credential setup, see [HF Spaces Setup](/home/setup/hf_spaces). > [!NOTE] > > Node only: the VFS ships in `@struktoai/mirage-node`. It needs no native > binding, though, because it speaks the Hub API over the runtime's own `fetch`. > The [opendal](https://www.npmjs.com/package/opendal) binding belongs to > [HF Buckets](/typescript/setup/hf_buckets), which is a different product. ## Node ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { HfSpacesVFS, MountMode, Workspace } from '@struktoai/mirage-node' const space = new HfSpacesVFS({ repoId: 'HuggingFaceBio/carbon-demo', // "namespace/space-name" token: process.env.HF_TOKEN, // optional for public spaces // Optional: // endpoint: 'https://huggingface.co', // revision: 'main', }) const ws = new Workspace({ '/s/': space }, { mode: MountMode.READ }) console.log((await ws.shell('ls /s/')).stdoutText) console.log((await ws.shell("find /s/ -name '*.py'")).stdoutText) console.log((await ws.shell('cat /s/README.md | head -n 15')).stdoutText) ``` ### Config | Field | Description | | - | - | | `repoId` required | Repository id as `namespace/name`, or a bare `name` that resolves against the token's owner. | | `token` secret | Hugging Face access token; unset sends anonymous requests, which reach public repositories only. | | `endpoint` default `'https://huggingface.co'` | Hub origin requests go to, for a mirror or a self-hosted Hub. | | `timeout` 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. | | `keyPrefix` | Path inside the repository that becomes the mount root; files outside it are not listed. | | `revision` | Branch, tag or commit the mount reads; unset reads `main`. | | `expandCommits` | Fetch each file's last commit so listings carry modification times, at 50 entries per request instead of 1000. Unset does so only when the whole repository fits in one page. | Fields marked secret are redacted in snapshots. ## Reading, not writing This mount is read-only, the way a [`github`](/typescript/setup/github) mount is. A Hub write is a **commit**, and a POSIX write cannot say where a commit ends, so `echo >`, `rm`, `cp` and `mv` are refused here rather than silently making one commit per file. The [`hf` CLI](/typescript/cli/hf) is the write half: `hf download --local-dir` puts a copy on a ram or disk mount, which is an ordinary writable filesystem, and `hf upload` sends it back as a single commit. ## Listings under `fresh` Under `read: fresh`, a cached listing is checked against the commit the `revision` resolves to: one small check per command (`revision/{rev}?expand[]=sha`), after which every cached listing of the mount at that commit is served. A mount whose `revision` is a full 40- or 64-hex commit sha is checked the same way, with that one small request per command: a branch or tag named like the sha could take the name, and mirage does not assume which one the Hub resolves. With a `keyPrefix`, the stored version is that commit joined with the prefix, so mounts of different subtrees sharing an index never share a version. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with HF Spaces mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | read | > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | read | > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ``` ## Integration What Hugging Face Spaces answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Hugging Face Spaces | | - | - | | `sha256sum` | The LFS sha256 the Hub keeps; other files are read | ## Shell Commands Every read command in [HF Buckets'](/typescript/setup/hf_buckets#read-commands) set works here, as do the text processing and path utilities, which only read. What does not is the [File Operations](/typescript/setup/hf_buckets#file-operations) group: this mount is read-only, so `rm` and `touch` are refused, as is any command asked to write into it. # Jaeger Source: https://docs.mirage.strukto.ai/typescript/setup/jaeger Read Jaeger services, operations, and traces as read-only JSON files. For connection setup, see [Jaeger Setup](/home/setup/jaeger). For the Python SDK, see [Jaeger (Python)](/python/vfs/jaeger). ```typescript theme={null} import { JaegerVFS, MountMode, Workspace } from '@struktoai/mirage-node' const ws = new Workspace({ '/jaeger': new JaegerVFS({ host: 'http://localhost:16686' }), }, { mode: MountMode.READ }) const res = await ws.shell('ls /jaeger/services') console.log(res.stdoutText) await ws.close() ``` The VFS ships in `@struktoai/mirage-node` only; `@struktoai/mirage-browser` does not export it. In a YAML config or `buildVfs('jaeger', ...)`, the same fields are snake\_case (`default_trace_limit`). ## Config | Field | Description | | - | - | | `host` default `'http://localhost:16686'` | Jaeger query service URL. | | `defaultTraceLimit` default `100` | The most traces one service's `traces/` listing shows, newest first. An older trace is still readable by its id. | | `defaultFromTimestamp` | Lower bound of trace listings, an ISO 8601 timestamp. Unset searches from the beginning. | | `defaultToTimestamp` | Upper bound of trace listings, an ISO 8601 timestamp. Unset means now. | | `timeout` 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. | ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Jaeger mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `jaeger`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > services/ > <service-name>/ > operations.json > traces/ > <trace-id>.json > ``` > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `jaeger`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > services/ > <service-name>/ > operations.json > traces/ > <trace-id>.json > ``` > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ```` ## Layout reference | Path | Contents | | - | - | | `services/` | One directory per service Jaeger's `/api/services` reports, including Jaeger's own `jaeger` service when it traces itself | | `services/<service>/operations.json` | The operation records `/api/operations` returns for the service | | `services/<service>/traces/<trace-id>.json` | The trace document `/api/traces/<trace-id>` returns | The `traces/` listing shows the newest `defaultTraceLimit` traces of the service within `defaultFromTimestamp` and `defaultToTimestamp`. Unset bounds search from the beginning up to now. A trace older than the listing is still readable by its id, as long as one of its spans comes from that service. A service Jaeger does not know, a trace id that is not 16 or 32 hex digits, and a trace without a span from the addressed service are reported as missing paths. Every listed file has an exact size, so `ls -l`, `du`, and `stat` work without reading the files. The mount has no write operations. # LanceDB Source: https://docs.mirage.strukto.ai/typescript/setup/lancedb Mount a LanceDB table as a Mirage filesystem in TypeScript, with label folders and semantic search through the search CLI. `LanceDBVFS` exposes a LanceDB table as a read-only filesystem: group-by columns become nested folders, each row is a card plus an optional blob file, and semantic search is the [`search` CLI](/typescript/cli/search). The TypeScript backend mirrors the [Python one](/python/vfs/lancedb) and returns identical results. ## Node ```bash theme={null} pnpm add @struktoai/mirage-node @lancedb/lancedb ``` ```ts theme={null} import { LanceDBVFS, MountMode, SEARCH, Workspace } from '@struktoai/mirage-node' const fashion = new LanceDBVFS({ config: { uri: '/data/fashion.lancedb', // or s3://, gs://, db:// (LanceDB Cloud) table: 'fashion', groupBy: ['gender', 'articleType', 'baseColour'], idColumn: 'id', titleColumn: 'productDisplayName', blobColumn: 'image_bytes', blobExt: 'jpg', vectorColumn: 'vector', searchLimit: 5, }, }) const ws = new Workspace({ '/fashion/': fashion }, { mode: MountMode.READ }) ws.registerCli('search', SEARCH) await ws.shell('ls /fashion/Men/Shoes/White') await ws.shell('search "red running shoes" /fashion') ``` ### Config | Field | Description | | - | - | | `timeout` 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. | | `uri` required | Database location: a local directory, an `s3://`, `gs://` or `az://` URI, or a `db://` URI for LanceDB Cloud or Enterprise. | | `apiKey` secret | API key for LanceDB Cloud or Enterprise. | | `region` default `'us-east-1'` | LanceDB Cloud region of a `db://` database; ignored for other URIs. | | `hostOverride` | Endpoint of a LanceDB Enterprise deployment for a `db://` URI; ignored for other URIs. | | `storageOptions` | Options passed to LanceDB's object-store layer, such as credentials or an endpoint for an `s3://` URI. | | `table` | Table the mount root shows; unset lists every table as a top-level folder. | | `groupBy` default `[]` | Columns that become folder levels, one per column in order; unset puts every row's files directly under the table. | | `idColumn` default `'id'` | Column whose value names each row's files (`<id>.md`, `<id>.<blobExt>`). | | `titleColumn` | Column whose value heads a row's card as a `# ` title; unset leaves the card without one. | | `blobColumn` | Column of raw or base64 bytes served as `<id>.<blobExt>` and left out of the card; unset adds no blob file. | | `blobExt` default `'bin'` | File extension of the blob file, without the dot. | | `vectorColumn` | Embedding column left out of cards and listings. | | `searchLimit` default `10` | Results `search` returns when `--top-k` is not given. | | `maxRows` default `1000` | Most rows one folder listing reads; rows past it are left out, and a group folder lists only the values those rows carry. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with LanceDB mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `lancedb`, read | > > #### VFS Layout > > ##### `/<path>` > > * A LanceDB table, exposed as a filesystem. > * Directories are the configured group-by columns; descending one narrows > a filter. > * Each matching row is a `<id>.md` card plus a `<id>.<ext>` blob file. > * `ls`, `cd`, `cat`, `tree`, `find`, `wc`, `grep` and `rg` work as > usual. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `lancedb` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `lancedb` answers only for `*/*.md`; `grep -r` and `rg` read every other 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>` | `lancedb`, read | > > ## VFS Layout > > ### `/<path>` > > - A LanceDB table, exposed as a filesystem. > - Directories are the configured group-by columns; descending one narrows > a filter. > - Each matching row is a `<id>.md` card plus a `<id>.<ext>` blob file. > - `ls`, `cd`, `cat`, `tree`, `find`, `wc`, `grep` and `rg` work as > usual. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `lancedb` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `lancedb` answers only for `*/*.md`; `grep -r` and `rg` read every other 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. > ``` ```text theme={null} /fashion/<gender>/<articleType>/<baseColour>/<id>.md # row card /fashion/<gender>/<articleType>/<baseColour>/<id>.jpg # raw blob bytes ``` A `groupBy` value holding `/` renders as `∕`, and a blank or dot-led value is led by `⁄`, so every value keeps its own directory that lists and opens, and descending into it filters for exactly that value. Semantic search is the `search` command, not a path: it returns ranked rows as the canonical `<id>.md` paths above, annotated with the vector distance. ## Cloud and Enterprise `db://` URIs connect to LanceDB Cloud (`apiKey` + `region`) or Enterprise (`apiKey` + `hostOverride`): ```ts theme={null} const fashion = new LanceDBVFS({ config: { uri: 'db://my-database', apiKey: process.env.LANCEDB_API_KEY, region: 'us-east-1', hostOverride: 'https://my-database.us-east-1.api.lancedb.com', // Enterprise only table: 'fashion', groupBy: ['gender'], idColumn: 'id', vectorColumn: 'vector', }, }) ``` ## Integration What LanceDB answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On LanceDB | | - | - | | `grep -r`, `rg` | The string columns of each row, for any text; a table with list, struct or bytes columns reads every card. It misses nothing. | The [Python LanceDB docs](/python/vfs/lancedb#integration) list when each search answers and what it can miss. ## Supported commands `ls`, `cd`, `tree`, `cat`, `stat`, `find` and `wc`. `grep`/`rg` stay lexical; the `search` CLI's `search "<query>" <path>` is the semantic path, returning ranked rows as canonical `<id>.md` paths plus a score, so results compose with `cat`, `wc`, and pipes. Flags: `--top-k`, `--threshold`, `--method semantic`. Search requires a table built with an embedding function on a source field, so `tbl.search(text)` auto-embeds the query. The Node example under `examples/typescript/vfs/lancedb/` builds such a table and produces the same output as the Python example, including identical similarity scores (0.2679). # Langfuse Source: https://docs.mirage.strukto.ai/typescript/setup/langfuse Mount Langfuse traces and observations as a Mirage filesystem. `LangfuseVFS` exposes Langfuse projects and traces as a read-only tree. Setup steps for the public/secret keys live at [Langfuse Credentials](/home/setup/langfuse). ## Node ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { LangfuseVFS, MountMode, Workspace } from '@struktoai/mirage-node' const lf = new LangfuseVFS({ publicKey: process.env.LANGFUSE_PUBLIC_KEY!, secretKey: process.env.LANGFUSE_SECRET_KEY!, host: process.env.LANGFUSE_HOST, }) const ws = new Workspace({ '/lf': lf }, { mode: MountMode.READ }) await ws.shell('ls /lf/traces/') ``` ## Browser ```bash theme={null} pnpm add @struktoai/mirage-browser ``` ```ts theme={null} import { LangfuseVFS, MountMode, Workspace } from '@struktoai/mirage-browser' const lf = new LangfuseVFS({ publicKey: LANGFUSE_PUBLIC_KEY, secretKey: LANGFUSE_SECRET_KEY, }) ``` ## Config | Field | Description | | - | - | | `timeout` 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. | | `publicKey` required | Langfuse project public key. | | `secretKey` required, secret | Langfuse project secret key. | | `host` default `'https://cloud.langfuse.com'` | Langfuse API host; override for a self-hosted or regional instance. | | `defaultTraceLimit` default `100` | The most traces one trace listing (`traces/` or a session's traces) shows. An older trace is still readable by its id. | | `defaultFromTimestamp` | List only traces from this ISO 8601 timestamp on. Unset lists whatever the project holds, up to `defaultTraceLimit`. | Fields marked secret are redacted in snapshots. ## Mount mode `read`. For the layout and search behavior see the [Python Langfuse docs](/python/vfs/langfuse). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Langfuse mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `langfuse`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > traces/ > <trace-id>.json > sessions/ > <session-id>/ > <trace-id>.json > prompts/ > <prompt-name>/ > <version>.json > datasets/ > <dataset-name>/ > items.jsonl > runs/ > <run-name>.jsonl > ``` > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `langfuse`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > traces/ > <trace-id>.json > sessions/ > <session-id>/ > <trace-id>.json > prompts/ > <prompt-name>/ > <version>.json > datasets/ > <dataset-name>/ > items.jsonl > runs/ > <run-name>.jsonl > ``` > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ```` # Linear Source: https://docs.mirage.strukto.ai/typescript/setup/linear Mount Linear teams, projects, and issues as a Mirage filesystem. `LinearVFS` exposes a Linear workspace as a tree of teams, projects, and issues. Reads route through the Linear GraphQL API. Setup steps for the API key live at [Linear Credentials](/home/setup/linear). ## Node ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { LinearVFS, MountMode, Workspace } from '@struktoai/mirage-node' const linear = new LinearVFS({ apiKey: process.env.LINEAR_API_KEY!, }) const ws = new Workspace({ '/linear': linear }, { mode: MountMode.READ }) await ws.shell('ls /linear/teams/') ``` ## Browser ```bash theme={null} pnpm add @struktoai/mirage-browser ``` ```ts theme={null} import { LinearVFS, MountMode, Workspace } from '@struktoai/mirage-browser' const linear = new LinearVFS({ apiKey: LINEAR_API_KEY, }) ``` ## Config | Field | Description | | - | - | | `timeout` 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. | | `apiKey` required, secret | Linear personal API key. | | `workspace` | Accepted for compatibility; not read. | | `teamIds` | Only these teams are listed or readable. Unset shows every team the key can reach. | | `baseUrl` default `'https://api.linear.app/graphql'` | Linear GraphQL endpoint; override to point at a fake or proxy. | Fields marked secret are redacted in snapshots. ## Mount mode `read`. For the mounted layout (`teams/`, `projects/`, `issues/`) see the [Python Linear docs](/python/vfs/linear). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Linear mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `linear`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > teams/ > <team-key>__<team-name>__<team-id>/ > team.json > members/ > <display-name>__<user-id>.json > issues/ > <issue-key>__<issue-id>/ > issue.json > comments.jsonl > projects/ > <name>__<project-id>.json > cycles/ > <name>__<cycle-id>.json > documents/ > <title>__<document-id>.json > ``` > > * `ls` directories first to discover exact names. > * Every entity-named segment is `<sanitized-human-readable>__<id>`. The > human-readable part is sanitized, so don't construct it; `ls` the > parent directory instead. > * The id is the last `__`-separated segment: > > ```text theme={null} > /<path>/teams/STR__Strukto-ai__<team-id>/ -> <team-id> > /<path>/teams/.../issues/STR-42__<issue-id>/ -> <issue-id> > /<path>/teams/.../members/Alice__<user-id>.json -> <user-id> > ``` > > All `cat` output is normalized by Mirage (snake\_case keys), not the raw > Linear GraphQL response. The shapes: > > `team.json`: > > ```jsonc theme={null} > { > "team_id": "...", "team_key": "STR", "team_name": "Strukto", > "name": "...", "description": "...", "timezone": "...", > "updated_at": "...", > "states": [ > { "state_id": "...", "state_name": "Todo", "type": "unstarted" }, > ... // one element per workflow state > ] > } > ``` > > `issue.json`: > > ```jsonc theme={null} > { > "issue_id": "...", "issue_key": "STR-42", > "title": "...", "description": "...", > "team_id": "...", "team_key": "...", "team_name": "...", > "project_id": "...", "project_name": "...", > "cycle_id": "...", "cycle_name": "...", "cycle_number": 7, > "state_id": "...", "state_name": "In Progress", > "assignee_id": "...", "assignee_email": "...", "assignee_name": "...", > "creator_id": "...", "creator_email": "...", "creator_name": "...", > "priority": 2, // 0=none 1=urgent 2=high 3=medium 4=low > "label_ids": ["..."], > "label_names": ["bug", "frontend"], > "created_at": "...", "updated_at": "...", "url": "..." > } > ``` > > `comments.jsonl`, one normalized comment per line: > > ```jsonc theme={null} > { "comment_id": "...", "issue_id": "...", "issue_key": "STR-42", > "user_id": "...", "user_email": "...", "user_name": "...", > "body": "...", "created_at": "...", "updated_at": "...", > "url": "..." } > ``` > > A project (`projects/<name>__<project-id>.json`): > > ```jsonc theme={null} > { > "project_id": "...", "team_id": "...", > "name": "...", "description": "...", "state": "started", > "lead_id": "...", "updated_at": "...", "url": "...", > "issue_count": 12, > "issues": [ > { "issue_id": "...", "issue_key": "STR-42", "title": "...", > "state_id": "...", "state_name": "In Progress", "url": "..." } > ] > } > ``` > > A cycle (`cycles/<name>__<cycle-id>.json`): > > ```jsonc theme={null} > { > "cycle_id": "...", "team_id": "...", > "name": "...", "number": 7, > "starts_at": "...", "ends_at": "...", > "updated_at": "...", "url": "..." > } > ``` > > A member (`members/<display-name>__<user-id>.json`): > > ```jsonc theme={null} > { > "user_id": "...", "name": "...", "display_name": "...", > "email": "...", "is_active": true, "is_admin": false, > "updated_at": "...", "url": "..." > } > ``` > > A document (`documents/<title>__<document-id>.json`): > > ```jsonc theme={null} > { > "document_id": "...", "title": "...", "content": "...", > "project_id": "...", "project_name": "...", > "creator_id": "...", "creator_name": "...", "creator_email": "...", > "created_at": "...", "updated_at": "...", "url": "..." > } > ``` > > Useful `jq` paths: > > ```jq theme={null} > .issue_key # issue.json > .state_name # issue.json > .assignee_email # issue.json > .label_names[] # issue.json > .issues[] | select(.state_name == "In Progress") # a project > .states[].state_name # team.json > [inputs] | length # comments.jsonl: count > [inputs | select(.user_email == "x")] | length # comments.jsonl > ``` > > To act on issues (list, get, create, update, assign, transition, > comments, projects, cycles, labels, users, documents, search), use the > `linear` CLI if installed (`linear --help`). > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `linear` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `linear` answers only for `teams/*/issues/*/issue.json`, `teams/*/members/*`, `teams/*/projects/*`, `teams/*/cycles/*` and `teams/*/documents/*`; `grep -r` and `rg` read every other 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>` | `linear`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > teams/ > <team-key>__<team-name>__<team-id>/ > team.json > members/ > <display-name>__<user-id>.json > issues/ > <issue-key>__<issue-id>/ > issue.json > comments.jsonl > projects/ > <name>__<project-id>.json > cycles/ > <name>__<cycle-id>.json > documents/ > <title>__<document-id>.json > ``` > > - `ls` directories first to discover exact names. > - Every entity-named segment is `<sanitized-human-readable>__<id>`. The > human-readable part is sanitized, so don't construct it; `ls` the > parent directory instead. > - The id is the last `__`-separated segment: > > ```text > /<path>/teams/STR__Strukto-ai__<team-id>/ -> <team-id> > /<path>/teams/.../issues/STR-42__<issue-id>/ -> <issue-id> > /<path>/teams/.../members/Alice__<user-id>.json -> <user-id> > ``` > > All `cat` output is normalized by Mirage (snake_case keys), not the raw > Linear GraphQL response. The shapes: > > `team.json`: > > ```jsonc > { > "team_id": "...", "team_key": "STR", "team_name": "Strukto", > "name": "...", "description": "...", "timezone": "...", > "updated_at": "...", > "states": [ > { "state_id": "...", "state_name": "Todo", "type": "unstarted" }, > ... // one element per workflow state > ] > } > ``` > > `issue.json`: > > ```jsonc > { > "issue_id": "...", "issue_key": "STR-42", > "title": "...", "description": "...", > "team_id": "...", "team_key": "...", "team_name": "...", > "project_id": "...", "project_name": "...", > "cycle_id": "...", "cycle_name": "...", "cycle_number": 7, > "state_id": "...", "state_name": "In Progress", > "assignee_id": "...", "assignee_email": "...", "assignee_name": "...", > "creator_id": "...", "creator_email": "...", "creator_name": "...", > "priority": 2, // 0=none 1=urgent 2=high 3=medium 4=low > "label_ids": ["..."], > "label_names": ["bug", "frontend"], > "created_at": "...", "updated_at": "...", "url": "..." > } > ``` > > `comments.jsonl`, one normalized comment per line: > > ```jsonc > { "comment_id": "...", "issue_id": "...", "issue_key": "STR-42", > "user_id": "...", "user_email": "...", "user_name": "...", > "body": "...", "created_at": "...", "updated_at": "...", > "url": "..." } > ``` > > A project (`projects/<name>__<project-id>.json`): > > ```jsonc > { > "project_id": "...", "team_id": "...", > "name": "...", "description": "...", "state": "started", > "lead_id": "...", "updated_at": "...", "url": "...", > "issue_count": 12, > "issues": [ > { "issue_id": "...", "issue_key": "STR-42", "title": "...", > "state_id": "...", "state_name": "In Progress", "url": "..." } > ] > } > ``` > > A cycle (`cycles/<name>__<cycle-id>.json`): > > ```jsonc > { > "cycle_id": "...", "team_id": "...", > "name": "...", "number": 7, > "starts_at": "...", "ends_at": "...", > "updated_at": "...", "url": "..." > } > ``` > > A member (`members/<display-name>__<user-id>.json`): > > ```jsonc > { > "user_id": "...", "name": "...", "display_name": "...", > "email": "...", "is_active": true, "is_admin": false, > "updated_at": "...", "url": "..." > } > ``` > > A document (`documents/<title>__<document-id>.json`): > > ```jsonc > { > "document_id": "...", "title": "...", "content": "...", > "project_id": "...", "project_name": "...", > "creator_id": "...", "creator_name": "...", "creator_email": "...", > "created_at": "...", "updated_at": "...", "url": "..." > } > ``` > > Useful `jq` paths: > > ```jq > .issue_key # issue.json > .state_name # issue.json > .assignee_email # issue.json > .label_names[] # issue.json > .issues[] | select(.state_name == "In Progress") # a project > .states[].state_name # team.json > [inputs] | length # comments.jsonl: count > [inputs | select(.user_email == "x")] | length # comments.jsonl > ``` > > To act on issues (list, get, create, update, assign, transition, > comments, projects, cycles, labels, users, documents, search), use the > `linear` CLI if installed (`linear --help`). > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `linear` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `linear` answers only for `teams/*/issues/*/issue.json`, `teams/*/members/*`, `teams/*/projects/*`, `teams/*/cycles/*` and `teams/*/documents/*`; `grep -r` and `rg` read every other 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. > ```` ## Integration What Linear answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Linear | | - | - | | `grep -r`, `rg` | Issues: Linear search, for whole words. Other files: the text the listing keeps. It can miss recent issue writes. | The [Python Linear docs](/python/vfs/linear#integration) list when each search answers and what it can miss. # Mem0 Source: https://docs.mirage.strukto.ai/typescript/setup/mem0 Mount scoped Mem0 Platform memories as JSON files from Node or the browser. `Mem0VFS` is a browser-safe, read-only view of one Mem0 user, agent, or run scope. Every memory is rendered as `<memory-id>.json`; the [`search` CLI](/typescript/cli/search) performs semantic search in that same scope. > [!WARNING] > > Mem0 API keys are secrets. Use this VFS from Node or another trusted runtime; do not embed a Platform API key in a public browser bundle. Browser applications should call a server-side proxy instead. ```ts theme={null} import { Mem0VFS, MountMode, SEARCH, Workspace } from '@struktoai/mirage-node' const memories = new Mem0VFS({ apiKey: process.env.MEM0_API_KEY!, userId: 'alex', }) const ws = new Workspace({ '/memories': memories }, { mode: MountMode.READ }) ws.registerCli('search', SEARCH) await ws.shell('ls /memories/') await ws.shell('search --top-k 5 "quarterly planning" /memories/') ``` Exactly one of `userId`, `agentId`, or `runId` is required. | Field | Description | | - | - | | `timeout` 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. | | `apiKey` required, secret | Mem0 Platform API key. | | `host` default `'https://api.mem0.ai'` | Mem0 API base URL. | | `userId` | Mount this user's memories. Set exactly one of `userId`, `agentId` and `runId`. | | `agentId` | Mount this agent's memories. Set exactly one of `userId`, `agentId` and `runId`. | | `runId` | Mount this run's memories. Set exactly one of `userId`, `agentId` and `runId`. | | `defaultPageSize` default `100` | Memories fetched per request while listing the scope. | | `defaultSearchLimit` default `10` | How many results `search` returns unless the line sets `top_k`. | Fields marked secret are redacted in snapshots. The TypeScript VFS mirrors the [Python Mem0 VFS](/python/vfs/mem0), including pagination, JSON rendering, score formatting, path-limited search, and `--threshold`. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Mem0 mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `mem0`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > <memory-id>.json > ``` > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `mem0`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > <memory-id>.json > ``` > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ```` # MinIO Source: https://docs.mirage.strukto.ai/typescript/setup/minio Set up MinIO as a MIRAGE VFS from Node or the browser. MinIO speaks the S3 API with AWS Signature V4 against your own server endpoint (e.g. `http://localhost:9000`). MinIO is self-hosted, so the endpoint is required and path-style addressing is used by default. MinIO ignores copy and delete conditions, so under `write: conditional` mirage refuses what would copy or delete on a MinIO mount (such as a `cp` or `mv` within the mount, a `mv` out of it, `rm`, or `find -delete`); a `cp` or `mv` into it from another mount is a write, and goes through. Credentials (access key + secret key from the MinIO Console) are created the same way in both runtimes, see [MinIO Credentials](/home/setup/minio). ## Node (server-side) ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { MinIOVFS, MountMode, Workspace } from '@struktoai/mirage-node' const minio = new MinIOVFS({ bucket: process.env.MINIO_BUCKET!, endpoint: process.env.MINIO_ENDPOINT!, accessKeyId: process.env.MINIO_ACCESS_KEY!, secretAccessKey: process.env.MINIO_SECRET_KEY!, }) const ws = new Workspace({ '/bucket/': minio }, { mode: MountMode.READ }) const res = await ws.shell('ls /bucket/') console.log(res.stdoutText) ``` ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `accessKeyId` secret | Access key ID; set it with `secretAccessKey`. Unset uses the AWS SDK credential chain. | | `secretAccessKey` secret | Secret access key paired with `accessKeyId`. | | `sessionToken` secret | Session token for temporary credentials, sent with the access key pair. | | `profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `forcePathStyle` default `true` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `keyPrefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `timeout` 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. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | | `region` default `'us-east-1'` | Region requests are signed for; the gateway's endpoint does not depend on it. | | `endpoint` required | URL of the self-hosted S3 gateway, such as `http://localhost:9000`. | Fields marked secret are redacted in snapshots. ## Browser (presigned URLs) ```bash theme={null} pnpm add @struktoai/mirage-browser ``` The browser `MinIOVFS` is secret-free, your backend signs each operation using your MinIO keys and returns a URL. MinIO accepts AWS Signature V4, so `@aws-sdk/s3-request-presigner` works, pointed at your MinIO endpoint. ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `presignedUrlProvider` required, secret | Function `(path, operation, options)` that returns a signed URL for each S3 operation; your server signs it, so the browser holds no keys. | | `region` | Region of the bucket. Most providers derive the endpoint from it; requests go to the host each presigned URL names. | | `endpoint` | Endpoint URL that replaces the one the provider derives. Requests go to the host each presigned URL names; the mount uses it to name its storage location. | | `defaultContentType` default `'application/octet-stream'` | `Content-Type` stored with every object the mount writes. | | `keyPrefix` | Key prefix the mount treats as its root. The browser can change it before a URL is signed, so enforce the prefix on the signing server. | | `timeout` 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. | Fields marked secret are redacted in snapshots. ### 1. Server: sign URLs with the MinIO endpoint ```ts theme={null} import { CopyObjectCommand, DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client, } from '@aws-sdk/client-s3' import { getSignedUrl } from '@aws-sdk/s3-request-presigner' const client = new S3Client({ region: 'us-east-1', endpoint: process.env.MINIO_ENDPOINT, forcePathStyle: true, credentials: { accessKeyId: process.env.MINIO_ACCESS_KEY!, secretAccessKey: process.env.MINIO_SECRET_KEY!, }, }) const BUCKET = process.env.MINIO_BUCKET! app.post('/presign/minio', async (req, res) => { const { path, op, opts } = req.body const key = path.replace(/^\/+/, '') const ttl = typeof opts?.ttlSec === 'number' ? opts.ttlSec : 300 let cmd switch (op) { case 'GET': cmd = new GetObjectCommand({ Bucket: BUCKET, Key: key }); break case 'PUT': cmd = new PutObjectCommand({ Bucket: BUCKET, Key: key, ContentType: opts?.contentType }); break case 'HEAD': cmd = new HeadObjectCommand({ Bucket: BUCKET, Key: key }); break case 'DELETE': cmd = new DeleteObjectCommand({ Bucket: BUCKET, Key: key }); break case 'LIST': cmd = new ListObjectsV2Command({ Bucket: BUCKET, Prefix: opts?.listPrefix, Delimiter: opts?.listDelimiter, ContinuationToken: opts?.listContinuationToken, }); break case 'COPY': cmd = new CopyObjectCommand({ Bucket: BUCKET, Key: key, CopySource: `${BUCKET}/${opts?.copySource}`, }); break } res.json({ url: await getSignedUrl(client, cmd, { expiresIn: ttl }) }) }) ``` > [!WARNING] > > MinIO uses **path-style** URLs (`forcePathStyle: true`), virtual-hosted style requires extra DNS setup on a self-hosted server. ### 2. Browser: wire it up ```ts theme={null} import { MinIOVFS, MountMode, Workspace } from '@struktoai/mirage-browser' const minio = new MinIOVFS({ bucket: 'my-bucket', endpoint: 'http://localhost:9000', presignedUrlProvider: async (path, op, opts) => { const r = await fetch('/presign/minio', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path, op, opts }), }) const { url } = await r.json() return url }, }) const ws = new Workspace({ '/bucket/': minio }, { mode: MountMode.READ }) ``` > [!TIP] > > `endpoint` on the browser config is only used for display/logging; the actual endpoint is baked into the presigned URLs your backend returns. ### 3. CORS MinIO answers CORS preflights for **all origins by default**, so local dev typically works without configuration. To restrict origins, set the server environment variable and restart MinIO: ```bash theme={null} MINIO_API_CORS_ALLOW_ORIGIN=http://localhost:5173,https://app.example.com ``` See the [MinIO VFS](/python/vfs/minio) docs for the equivalent Python wiring. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with MinIO mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Integration What MinIO answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On MinIO | | - | - | | `md5sum` | The object's ETag, when it is the MD5: a single-part upload, unencrypted or under SSE-S3 | | `find`, `du`, `ls -R`, `tree` | One recursive listing | # MongoDB Source: https://docs.mirage.strukto.ai/typescript/setup/mongodb Mount a MongoDB cluster as a Mirage filesystem of databases, collections, and documents. `MongoDBVFS` exposes databases containing `collections/` and `views/` directories. Each collection or view contains `schema.json` and `documents.jsonl`. Setup steps for the connection URI live at [MongoDB Credentials](/home/setup/mongodb). ## Node ```bash theme={null} pnpm add @struktoai/mirage-node mongodb ``` ```ts theme={null} import { MongoDBVFS, MountMode, Workspace } from '@struktoai/mirage-node' const mongo = new MongoDBVFS({ uri: process.env.MONGODB_URI!, databases: ['app', 'analytics'], }) const ws = new Workspace({ '/mongo': mongo }, { mode: MountMode.READ }) try { const result = await ws.shell('ls /mongo/app/collections/users/') console.log(result.stdoutText) } finally { await ws.close() } ``` ## Browser ```bash theme={null} pnpm add @struktoai/mirage-browser ``` The browser VFS sends HTTP requests to a backend route, which keeps the MongoDB connection URI on the server. This example expects `/api/mongo` on the same origin. The repository's [Vite middleware](https://github.com/strukto-ai/mirage/blob/main/examples/browser/scripts/mongo_proxy.ts) supports the database listing below for local development. ```ts theme={null} import { MongoDBVFS, MountMode, Workspace } from '@struktoai/mirage-browser' const mongo = new MongoDBVFS({ uri: '/api/mongo' }) const ws = new Workspace({ '/mongo': mongo }, { mode: MountMode.READ }) try { const result = await ws.shell('ls /mongo/') console.log(result.stdoutText) } finally { await ws.close() } ``` The development proxy does not yet support document streaming or schema reads. ## Config | Field | Description | | - | - | | `timeout` 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. | | `uri` required, secret | MongoDB connection URI in Node; in the browser, the URL of a backend route that holds the connection URI. | | `databases` | Databases to mount; others are hidden. Unset or empty mounts every database except `admin`, `config` and `local`. | | `maxDocLimit` default `5000` | Most documents one `tail -n` read of `documents.jsonl` fetches; a larger count on a collection that holds more is refused (`File too large`). | | `elideFields` default `{}` | Fields dropped from `documents.jsonl`, keyed by `<database>.<collection>` (a view's name works too); a dotted path such as `nested.path` drops a nested field. | Fields marked secret are redacted in snapshots. ## Mount mode `read`. For the database/collection/document layout see the [Python MongoDB docs](/python/vfs/mongodb). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with MongoDB mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `mongodb`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > <database>/ > database.json # collection and view names > collections/<collection>/ > schema.json # sampled field types, validator, indexes > documents.jsonl # streamed BSON Extended JSON documents > views/<view>/ > schema.json > documents.jsonl > ``` > > * Read `database.json` first to discover entities, and `schema.json` > before reading a large document stream. > * `head`, `tail`, `wc`, `grep`, `rg` and `jq` understand > `documents.jsonl`; `grep` and `rg` fetch only the documents that may > match. > * An unknown size displays as `-`; `wc -c` measures bytes and `wc -l` > counts documents on demand. These counts may scan the collection. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep` and `rg` ask `mongodb` for the matching lines. `tail` and `wc -l` ask `mongodb` instead of reading a file. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `mongodb`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > <database>/ > database.json # collection and view names > collections/<collection>/ > schema.json # sampled field types, validator, indexes > documents.jsonl # streamed BSON Extended JSON documents > views/<view>/ > schema.json > documents.jsonl > ``` > > - Read `database.json` first to discover entities, and `schema.json` > before reading a large document stream. > - `head`, `tail`, `wc`, `grep`, `rg` and `jq` understand > `documents.jsonl`; `grep` and `rg` fetch only the documents that may > match. > - An unknown size displays as `-`; `wc -c` measures bytes and `wc -l` > counts documents on demand. These counts may scan the collection. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep` and `rg` ask `mongodb` for the matching lines. `tail` and `wc -l` ask `mongodb` instead of reading a file. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ```` ## Integration What MongoDB answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On MongoDB | | - | - | | `grep`, `rg` on one file | A filter on the server sends only the documents that may match | | `tail -n N` | The last N documents by `_id` | | `wc -l` | `countDocuments()` on the server | | `tail -f` | A change stream yields each new insert | The [Python MongoDB docs](/python/vfs/mongodb#integration) list when each search answers and what it can miss. # Nextcloud Source: https://docs.mirage.strukto.ai/typescript/setup/nextcloud Mount Nextcloud over WebDAV as a filesystem and read or write your files with shell commands. The Nextcloud VFS mounts a [WebDAV](http://www.webdav.org/specs/rfc4918.html) server (Nextcloud, ownCloud, Hetzner Storage Share, or any generic WebDAV endpoint) at a prefix such as `/nc/`. Reads are streaming, with HTTP `Range` requests for partial reads. For credential and server setup, see [Nextcloud Setup](/home/setup/nextcloud). For Python, see the [Nextcloud (Python)](/python/vfs/nextcloud) reference. ## Install Nextcloud requires the optional `opendal` peer dependency: ```bash theme={null} pnpm add opendal ``` ## Config ```typescript theme={null} import { buildVfs, MountMode, Workspace } from '@struktoai/mirage-node' const vfs = await buildVfs('nextcloud', { url: process.env.NEXTCLOUD_URL!, username: process.env.NEXTCLOUD_USERNAME, password: process.env.NEXTCLOUD_PASSWORD, // Optional: // timeout: 30, }) const ws = new Workspace({ '/nc/': vfs }, { mode: MountMode.WRITE }) ``` `NextcloudVFS` accepts a configuration object with the WebDAV URL and optional Basic Auth credentials. Both `READ` and `WRITE` mount modes are supported. Use an **app password** (Settings → Security in Nextcloud) rather than your account password. | Field | Description | | - | - | | `url` required | WebDAV URL of the user's files, such as `https://cloud.example.com/remote.php/dav/files/alice/`. | | `username` | Basic Auth user name; unset sends requests without credentials. | | `password` secret | Basic Auth password; use an app password (Settings → Security) rather than the account password. | | `verifySsl` | Accepted but not applied: every request verifies the server's TLS certificate. | | `timeout` default `30` | Seconds one WebDAV request mirage sends itself (copy, checksum, quota, properties, search, the chunks of a large write) may take; reads, other writes and listings go through OpenDAL and its own timeouts. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Nextcloud mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` WebDAV resources map directly to virtual paths under the mount prefix. For example, virtual `/nc/Documents/notes.md` issues HTTP WebDAV requests against `<NEXTCLOUD_URL>/Documents/notes.md`. ## Cache The Nextcloud VFS caches directory listings in Mirage's index cache. A listing usually needs one `PROPFIND Depth: 1`; each file missing a size needs an extra `stat` request. Cached child entries include sizes, types, and modification times, but not ETags. Subsequent `stat` operations can reuse those entries. ## Example ```typescript theme={null} import { buildVfs, MountMode, Workspace } from '@struktoai/mirage-node' const vfs = await buildVfs('nextcloud', { url: process.env.NEXTCLOUD_URL!, username: process.env.NEXTCLOUD_USERNAME, password: process.env.NEXTCLOUD_PASSWORD, }) const ws = new Workspace({ '/nc/': vfs }, { mode: MountMode.WRITE }) // List files const ls = await ws.shell('ls -la /nc/') console.log(await ls.stdoutStr()) // Read a remote document const doc = await ws.shell('cat /nc/Documents/notes.md') console.log(await doc.stdoutStr()) // Search document contents const search = await ws.shell('grep -i "meeting" /nc/Documents/*.md') console.log(await search.stdoutStr()) ``` # Notion Source: https://docs.mirage.strukto.ai/typescript/setup/notion Mount Notion pages and databases as a Mirage filesystem. `NotionVFS` exposes a Notion workspace as a filesystem. The Node SDK talks to the Notion REST API with an integration token; the Browser SDK talks to Notion's MCP server with an OAuth client provider so secrets stay off the page. ## Node ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { MountMode, NotionVFS, Workspace } from '@struktoai/mirage-node' const notion = new NotionVFS({ apiKey: process.env.NOTION_API_KEY! }) const ws = new Workspace({ '/notion': notion }, { mode: MountMode.READ }) await ws.shell('ls /notion/pages/') ``` | Field | Description | | - | - | | `timeout` 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. | | `apiKey` required, secret | Notion integration token. | | `baseUrl` default `'https://api.notion.com/v1'` | Notion API root; override to point at a fake or proxy. | | `apiVersion` default `'2025-09-03'` | `Notion-Version` header sent with every request; `ntn --notion-version` overrides it per line. | Fields marked secret are redacted in snapshots. ## Browser ```bash theme={null} pnpm add @struktoai/mirage-browser @modelcontextprotocol/client ``` ```ts theme={null} import { MountMode, NotionVFS, Workspace } from '@struktoai/mirage-browser' const notion = new NotionVFS({ authProvider, // OAuthClientProvider from @modelcontextprotocol/client }) const ws = new Workspace({ '/notion': notion }, { mode: MountMode.READ }) await ws.shell('ls /notion/') ``` | Field | Description | | - | - | | `authProvider` required, secret | `OAuthClientProvider` from `@modelcontextprotocol/client` that authorizes the browser with Notion's MCP server. | | `serverUrl` default `'https://mcp.notion.com/mcp'` | Notion MCP endpoint; override to route MCP through your own URL. | Fields marked secret are redacted in snapshots. ## Mount mode `read`. Edit pages through the [ntn CLI](/typescript/cli/ntn). ## Acting on Notion Acting on Notion (creating, editing and trashing pages, querying data sources, and every route that has no typed verb) goes through the [ntn CLI](/typescript/cli/ntn) when installed. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Notion mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `notion`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > pages/ # the page tree > <page-title>__<page-id>/ > page.json > <child-page-title>__<child-id>/ > page.json > databases/ # shared databases > <database-title>__<database-id>/ > database.json > <data-source-title>__<data-source-id>/ > data_source.json > rows.jsonl > ``` > > * `page.json` holds the page's metadata, its body rendered as Markdown > and its raw blocks (nested blocks under `children`). > * A database is a container plus one or more data sources. > `database.json` holds the container's identity and its `data_sources` > stubs, `data_source.json` the typed property schema, and `rows.jsonl` > the rows, one JSON line each: the row page's `page.json` without the > body, plus `path`, that `page.json`'s path below the data source > directory. Row directories are not listed; open one by its path. > * Titles are sanitized. Don't construct paths: `ls` the parent > directory, or take a row's `path` from `rows.jsonl`. > * `ntn` takes ids as positional operands, not flags: > `ntn pages get <page-id>`, `ntn datasources query <data-source-id>`, > `ntn datasources resolve <database-id>`. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `head` asks `notion` instead of reading a file. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `notion`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > pages/ # the page tree > <page-title>__<page-id>/ > page.json > <child-page-title>__<child-id>/ > page.json > databases/ # shared databases > <database-title>__<database-id>/ > database.json > <data-source-title>__<data-source-id>/ > data_source.json > rows.jsonl > ``` > > - `page.json` holds the page's metadata, its body rendered as Markdown > and its raw blocks (nested blocks under `children`). > - A database is a container plus one or more data sources. > `database.json` holds the container's identity and its `data_sources` > stubs, `data_source.json` the typed property schema, and `rows.jsonl` > the rows, one JSON line each: the row page's `page.json` without the > body, plus `path`, that `page.json`'s path below the data source > directory. Row directories are not listed; open one by its path. > - Titles are sanitized. Don't construct paths: `ls` the parent > directory, or take a row's `path` from `rows.jsonl`. > - `ntn` takes ids as positional operands, not flags: > `ntn pages get <page-id>`, `ntn datasources query <data-source-id>`, > `ntn datasources resolve <database-id>`. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `head` asks `notion` instead of reading a file. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ```` Since the `2025-09-03` API generation a database is a container of **data sources**, and both the column schema and the rows live on the data source: `data_source.json` and `rows.jsonl`. `database.json` is the container's identity plus the `data_sources` stubs that name the directories beneath it, and carries **no** `properties`. The shape is identical to the Python connector: ```json theme={null} { "database_id": "eeee1111-2222-3333-4444-555566667777", "title": "Tasks", "url": "https://www.notion.so/eeee1111222233334444555566667777", "created_time": "2026-01-01T00:00:00.000Z", "last_edited_time": "2026-01-02T00:00:00.000Z", "parent": { "type": "workspace", "workspace": true }, "archived": false, "is_inline": false, "data_sources": [ { "id": "d5000000-2222-3333-4444-555566667777", "name": "Tasks" } ] } ``` `data_source.json` holds the typed column schema under `properties`, and `rows.jsonl` holds every row, one JSON object per line: the row's `page.json` without the body, plus `path`, where that `page.json` is below the data source directory. The rows are one file rather than a directory each, because a query answers a hundred rows' cells in one call while every row directory costs calls of its own to enter. A database row is itself a page: its `page.json` reports `parent_type` of `data_source_id`, and its cell values ride in the same file under `properties`. Row directories are not listed; open one by the `path` on its line. For full `rows.jsonl` and `page.json` field details and supported edits see the [Python Notion docs](/python/vfs/notion). ## Integration What Notion answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Notion | | - | - | | `head -n N` | Renders only the first N rows | # OCI Object Storage Source: https://docs.mirage.strukto.ai/typescript/setup/oci Set up Oracle Cloud Object Storage as a MIRAGE VFS from Node or the browser. OCI's S3 Compatibility API accepts AWS Signature V4 against `https://<namespace>.compat.objectstorage.<region>.oci.customer-oci.com`. MIRAGE derives this endpoint from your namespace + region automatically. Credentials (bucket, namespace, region, customer secret key pair) are created the same way in both runtimes, see [OCI Credentials](/home/setup/oci). ## Node (server-side) ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { MountMode, OCIVFS, Workspace } from '@struktoai/mirage-node' const oci = new OCIVFS({ bucket: process.env.OCI_BUCKET!, namespace: process.env.OCI_NAMESPACE!, region: process.env.OCI_REGION!, accessKeyId: process.env.OCI_ACCESS_KEY_ID!, secretAccessKey: process.env.OCI_SECRET_ACCESS_KEY!, }) const ws = new Workspace({ '/bucket/': oci }, { mode: MountMode.READ }) const res = await ws.shell('ls /bucket/') console.log(res.stdoutText) ``` ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `accessKeyId` secret | Access key ID; set it with `secretAccessKey`. Unset uses the AWS SDK credential chain. | | `secretAccessKey` secret | Secret access key paired with `accessKeyId`. | | `sessionToken` secret | Session token for temporary credentials, sent with the access key pair. | | `profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `forcePathStyle` default `true` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `keyPrefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `timeout` 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. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | | `region` required | Provider region every request is signed for. Most providers also build their endpoint URL from it unless `endpoint` is set. | | `endpoint` | Endpoint URL that replaces the one the provider derives. | | `namespace` required | Object Storage namespace of the tenancy. With `region` it builds the endpoint `https://<namespace>.compat.objectstorage.<region>.oci.customer-oci.com` unless `endpoint` is set. | Fields marked secret are redacted in snapshots. ## Browser (presigned URLs) ```bash theme={null} pnpm add @struktoai/mirage-browser ``` The browser `OCIVFS` is secret-free, your backend signs each operation using your OCI customer secret keys and returns a URL. OCI's S3-compat endpoint accepts AWS Signature V4, so `@aws-sdk/s3-request-presigner` works, pointed at the OCI endpoint. ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `presignedUrlProvider` required, secret | Function `(path, operation, options)` that returns a signed URL for each S3 operation; your server signs it, so the browser holds no keys. | | `region` | Region of the bucket. Most providers derive the endpoint from it; requests go to the host each presigned URL names. | | `endpoint` | Endpoint URL that replaces the one the provider derives. Requests go to the host each presigned URL names; the mount uses it to name its storage location. | | `defaultContentType` default `'application/octet-stream'` | `Content-Type` stored with every object the mount writes. | | `keyPrefix` | Key prefix the mount treats as its root. The browser can change it before a URL is signed, so enforce the prefix on the signing server. | | `timeout` 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. | | `namespace` | Object Storage namespace of the tenancy. With `region` it builds the endpoint `https://<namespace>.compat.objectstorage.<region>.oci.customer-oci.com` unless `endpoint` is set. | Fields marked secret are redacted in snapshots. ### 1. Server: sign URLs with the OCI endpoint ```ts theme={null} import { CopyObjectCommand, DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client, } from '@aws-sdk/client-s3' import { getSignedUrl } from '@aws-sdk/s3-request-presigner' const NAMESPACE = process.env.OCI_NAMESPACE! const REGION = process.env.OCI_REGION! const client = new S3Client({ region: REGION, endpoint: `https://${NAMESPACE}.compat.objectstorage.${REGION}.oci.customer-oci.com`, forcePathStyle: true, credentials: { accessKeyId: process.env.OCI_ACCESS_KEY_ID!, secretAccessKey: process.env.OCI_SECRET_ACCESS_KEY!, }, }) const BUCKET = process.env.OCI_BUCKET! app.post('/presign/oci', async (req, res) => { const { path, op, opts } = req.body const key = path.replace(/^\/+/, '') const ttl = typeof opts?.ttlSec === 'number' ? opts.ttlSec : 300 let cmd switch (op) { case 'GET': cmd = new GetObjectCommand({ Bucket: BUCKET, Key: key }); break case 'PUT': cmd = new PutObjectCommand({ Bucket: BUCKET, Key: key, ContentType: opts?.contentType }); break case 'HEAD': cmd = new HeadObjectCommand({ Bucket: BUCKET, Key: key }); break case 'DELETE': cmd = new DeleteObjectCommand({ Bucket: BUCKET, Key: key }); break case 'LIST': cmd = new ListObjectsV2Command({ Bucket: BUCKET, Prefix: opts?.listPrefix, Delimiter: opts?.listDelimiter, ContinuationToken: opts?.listContinuationToken, }); break case 'COPY': cmd = new CopyObjectCommand({ Bucket: BUCKET, Key: key, CopySource: `${BUCKET}/${opts?.copySource}`, }); break } res.json({ url: await getSignedUrl(client, cmd, { expiresIn: ttl }) }) }) ``` > [!WARNING] > > OCI requires **path-style** URLs (`forcePathStyle: true`), virtual-hosted style is not supported on the S3 Compatibility API. ### 2. Browser: wire it up ```ts theme={null} import { MountMode, OCIVFS, Workspace } from '@struktoai/mirage-browser' const oci = new OCIVFS({ bucket: 'my-oci-bucket', namespace: 'idsiqbdbcr4i', region: 'us-ashburn-1', presignedUrlProvider: async (path, op, opts) => { const r = await fetch('/presign/oci', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path, op, opts }), }) const { url } = await r.json() return url }, }) const ws = new Workspace({ '/bucket/': oci }, { mode: MountMode.READ }) ``` ### 3. CORS OCI's S3-compatibility endpoint ships with **permissive default CORS rules** that echo back whatever `Origin` the browser sends, so local dev typically "just works" without any bucket configuration. For production origins you can tighten the policy through the OCI Console (Bucket → Pre-Authenticated Requests / CORS) or via the native OCI CLI: ```bash theme={null} oci os bucket update --bucket-name $OCI_BUCKET \ --namespace $OCI_NAMESPACE \ --cors-rules '[{"allowedOrigins":["https://app.example.com"],"allowedMethods":["GET","PUT","HEAD","DELETE","POST"],"allowedHeaders":["*"],"exposedHeaders":["ETag","Content-Length","Content-Type","Last-Modified"],"maxAgeInSeconds":3000}]' ``` > [!NOTE] > > OCI's CORS is **not** configurable via the S3-compat `PutBucketCors` call, the schema differs. Use the native OCI Console or CLI. See the [OCI VFS](/python/vfs/oci) docs for the equivalent Python wiring. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with OCI Object Storage mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Integration What OCI answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On OCI | | - | - | | `find`, `du`, `ls -R`, `tree` | One recursive listing | # OneDrive Source: https://docs.mirage.strukto.ai/typescript/setup/onedrive Mount OneDrive through Microsoft Graph from Node or the browser. `OneDriveVFS` exposes one Microsoft Graph drive as a read-write filesystem. It uses the same browser-safe core in the Node and browser packages. ```ts theme={null} import { MountMode, OneDriveVFS, Workspace } from '@struktoai/mirage-node' const drive = new OneDriveVFS({ accessToken: () => getMicrosoftGraphToken(), // Name at most one drive; none means /me/drive. // driveId: '...', // explicit Graph drive ID // siteId: '...', // a SharePoint site's default drive // groupId: '...', // a Teams / Microsoft 365 group's library // userId: '...', // another user's drive (app-only auth) // graphBaseUrl: 'https://graph.microsoft.us/v1.0', // non-worldwide root // keyPrefix: 'Reports', // optional folder-scoped mount }) const ws = new Workspace({ '/onedrive': drive }, { mode: MountMode.WRITE }) await ws.shell('ls /onedrive/') ``` Use `@struktoai/mirage-browser` for the same API in a browser. An access-token callback is recommended so a `401` can refresh the token and retry once. | Field | Description | | - | - | | `accessToken` required, secret | Microsoft Graph bearer token, or a function (sync or async) that returns one; it is called for each request and again after a `401`. | | `graphBaseUrl` | Full Graph service root, version segment included, for any deployment but the worldwide one: a sovereign cloud, a private endpoint or a test server. Unset uses `https://graph.microsoft.com/v1.0`. | | `timeout` default `DEFAULT_TIMEOUT` | Seconds a Graph request may wait to connect, or between two reads of its answer, before it fails; also how long a server-side copy is polled before it fails as unconfirmed. | | `maxRetries` default `5` | Times a request is retried after a `429`, `503` or `504` response. Each retry waits what `Retry-After` asks or an exponential backoff, at most 30 seconds. | | `driveId` | Graph drive ID of the drive to mount. Set at most one of `driveId`, `siteId`, `groupId` and `userId`; with none the mount uses the signed-in user's drive. | | `siteId` | Graph site ID whose default document library the mount uses. | | `groupId` | Microsoft 365 or Teams group ID whose document library the mount uses. | | `userId` | User ID or UPN whose drive the mount uses, under app-only auth. | | `keyPrefix` | Folder path from the drive root that the mount uses as its root. | Fields marked secret are redacted in snapshots. `driveId`, `siteId`, `groupId` and `userId` are four ways of saying which drive the mount is, so set at most one: setting two throws at construction rather than silently addressing whichever came first. Setting none means `/me/drive`, which is the only form an app-only token cannot use. Mounts address `https://graph.microsoft.com/v1.0` unless `graphBaseUrl` says otherwise. Set it to reach anything else: a sovereign cloud, a private endpoint, or a test server, given in full including the version segment. The sovereign deployments are network-isolated instances rather than regions, so a token minted for one is rejected by the others and a mount pointed at the wrong root fails outright. mirage ships no table of their hostnames, having no way to verify one; take the root from Microsoft's national cloud documentation for your tenant. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with OneDrive mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `onedrive`, write | > > #### 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 `onedrive` 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>` | `onedrive`, write | > > ## 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 `onedrive` 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. > ``` ## Integration What OneDrive answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On OneDrive | | - | - | | `grep -r`, `rg` | Microsoft Graph search, for whole words. It can miss Office files, PDFs, archives, the end of large files, words Graph splits differently (`foo.bar`) and recent writes. | | `find`, `du`, `ls -R`, `tree` | One recursive listing | The [Python OneDrive docs](/python/vfs/onedrive#integration) list when each search answers and what it can miss. # OPFS Source: https://docs.mirage.strukto.ai/typescript/setup/opfs Persistent in-browser filesystem backed by the Origin Private File System. `OPFSVFS` mounts the [Origin Private File System](https://web.dev/articles/origin-private-file-system) as a Mirage VFS. Files persist across page reloads but stay scoped to the current origin. > [!NOTE] > > Browser only. There is no OPFS in Node; for local persistence in Node, use [Disk](/typescript/setup/disk). ## Install ```bash theme={null} pnpm add @struktoai/mirage-browser ``` ## Config ```ts theme={null} import { MountMode, OPFSVFS, Workspace } from '@struktoai/mirage-browser' const opfs = new OPFSVFS({ root: 'mirage' }) const ws = new Workspace({ '/data': opfs }, { mode: MountMode.WRITE }) await ws.shell('echo persistent | tee /data/note.txt') ``` | Field | Default | Notes | | - | - | - | | `root` | `''` | Subdirectory under the OPFS root. Useful to namespace multiple workspaces. | ## Mount mode `read`, `write`, `exec`. ## Storage and quotas The browser sets per-origin quotas (typically a fraction of free disk, single-digit GB on most setups). Hitting it raises `QuotaExceededError`. ```ts theme={null} const { quota, usage } = await navigator.storage.estimate() console.log(`${usage} / ${quota} bytes`) ``` For long-lived workspaces, request persistent storage early so the browser doesn't evict your data under storage pressure: ```ts theme={null} await navigator.storage.persist() ``` See [TypeScript Limitations: Browser](/typescript/limitations#browser) for the full set of browser constraints. # Postgres Source: https://docs.mirage.strukto.ai/typescript/setup/postgres Mount a Postgres database as a read-only filesystem of schemas, tables, and rows. `PostgresVFS` connects to Postgres via a DSN and exposes its schemas and tables as a tree. Setup steps for the DSN and required permissions live at [Postgres Credentials](/home/setup/postgres). ## Node ```bash theme={null} pnpm add @struktoai/mirage-node pg ``` ```ts theme={null} import { MountMode, PostgresVFS, Workspace } from '@struktoai/mirage-node' const pg = new PostgresVFS({ dsn: process.env.DATABASE_URL!, schemas: ['public', 'analytics'], }) const ws = new Workspace({ '/pg': pg }, { mode: MountMode.READ }) try { const result = await ws.shell('ls /pg/public/') console.log(result.stdoutText) } finally { await ws.close() } ``` ## Browser ```bash theme={null} pnpm add @struktoai/mirage-browser ``` The default browser driver uses Neon's HTTP transport. Replace the connection string below with one for a read-only demo role on Neon. Browser users can inspect this credential. Keep private database credentials in a Node backend. ```ts theme={null} import { MountMode, PostgresVFS, Workspace } from '@struktoai/mirage-browser' const pg = new PostgresVFS({ dsn: 'postgresql://mirage_reader:password@your-endpoint.neon.tech/app?sslmode=require', schemas: ['public'], }) const ws = new Workspace({ '/pg': pg }, { mode: MountMode.READ }) try { const result = await ws.shell('ls /pg/public/') console.log(result.stdoutText) } finally { await ws.close() } ``` ## Config | Field | Description | | - | - | | `timeout` 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. | | `dsn` required, secret | Postgres connection string. The default browser driver connects over Neon's HTTP transport, so a browser mount needs a Neon connection string. | | `schemas` | Schemas to show in the tree; others are hidden. Unset shows every schema except `pg_catalog`, `information_schema` and `pg_*`. | | `defaultRowLimit` default `1000` | Rows a windowed read returns when it passes an offset but no limit, and the rows one page of a streamed `rows.jsonl` fetches. | | `maxReadRows` default `10000` | Most rows one read returns. A whole read past it is refused, and so is a `head -n` / `tail -n` count past it on a table that long (`File too large`); `wc -l` counts past it. | | `maxReadBytes` default `10485760` (10 MiB) | Most bytes of `rows.jsonl` one read returns; a whole read past it is refused (`File too large`). | Fields marked secret are redacted in snapshots. ## Mount mode `read` only. Postgres mounts are read-only at the VFS level. ## Snapshot behavior The DSN is redacted on snapshot. Hand the mount back at load (the third argument of `Workspace.load`, or a config over the server and CLI). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Postgres mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `postgres`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > database.json # cross-schema graph and sizes > <schema>/ # a Postgres schema (namespace) > tables/<table>/ > schema.json # column types, PK/FK, indexes > semantic.json # descriptions, roles, sample values > rows.jsonl # data (size-guarded) > views/<view>/ > schema.json > semantic.json > rows.jsonl > ``` > > * Read `database.json` first to plan joins. > * Read `semantic.json` to learn what a table means: it splits columns > into dimensions (group by), time\_dimensions and facts (aggregate), and > carries COMMENTs, enum domains and example values. > * Reading `rows.jsonl` is refused for a table above the configured row > or byte threshold. Use `head`, `tail` or `wc`, which ask SQL for only > what they need, or `grep`, which fetches only the matching rows when > SQL can find every match. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep` and `rg` ask `postgres` for the matching lines. `head`, `tail` and `wc -l` ask `postgres` instead of reading a file. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `postgres`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > database.json # cross-schema graph and sizes > <schema>/ # a Postgres schema (namespace) > tables/<table>/ > schema.json # column types, PK/FK, indexes > semantic.json # descriptions, roles, sample values > rows.jsonl # data (size-guarded) > views/<view>/ > schema.json > semantic.json > rows.jsonl > ``` > > - Read `database.json` first to plan joins. > - Read `semantic.json` to learn what a table means: it splits columns > into dimensions (group by), time_dimensions and facts (aggregate), and > carries COMMENTs, enum domains and example values. > - Reading `rows.jsonl` is refused for a table above the configured row > or byte threshold. Use `head`, `tail` or `wc`, which ask SQL for only > what they need, or `grep`, which fetches only the matching rows when > SQL can find every match. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep` and `rg` ask `postgres` for the matching lines. `head`, `tail` and `wc -l` ask `postgres` instead of reading a file. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ```` ## Integration What PostgreSQL answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On PostgreSQL | | - | - | | `grep`, `rg` on one file | `LIKE` (`ILIKE` for `-i`) fetches only the rows that may match | | `head -n N` | `LIMIT N` | | `tail -n N` | The last N rows by one query | | `wc -l` | `COUNT(*)` | | `tail -f` | Polls for rows past the last key, on a table with a primary key | The [Python PostgreSQL docs](/python/vfs/postgres#integration) list when each search answers and what it can miss. # Qdrant Source: https://docs.mirage.strukto.ai/typescript/setup/qdrant Mount a Qdrant collection as a Mirage filesystem in TypeScript, with payload folders and semantic search through the search CLI. `QdrantVFS` exposes a [Qdrant](https://qdrant.tech/) collection as a read-only filesystem: group-by payload fields become nested folders, each point is a `.json` payload file (plus a `.txt` text file and an optional blob), and semantic search is the [`search` CLI](/typescript/cli/search). The TypeScript backend mirrors the [Python one](/python/vfs/qdrant) and returns identical results. ## Install The client is browser-safe, so the VFS ships in `core` and is available from both the Node and browser packages: ```bash theme={null} pnpm add @struktoai/mirage-node @qdrant/js-client-rest ``` ```ts theme={null} import { QdrantVFS, MountMode, Workspace } from "@struktoai/mirage-node"; const fashion = new QdrantVFS({ config: { url: "https://xyz.cloud.qdrant.io", apiKey: process.env.QDRANT_API_KEY, collection: "fashion", groupBy: ["gender", "articleType", "baseColour"], idField: "id", textField: "productDisplayName", blobField: "image_b64", blobExt: "jpg", searchLimit: 5, }, }); const ws = new Workspace({ "/fashion/": fashion }, { mode: MountMode.READ }); await ws.shell("ls /fashion/Men/Shoes/White"); ``` This first setup supports filesystem browsing. Configure query embedding in [Search embedding](#search-embedding) and register the [`search` CLI](/typescript/cli/search) with `ws.registerCli('search', SEARCH)` before running `search`. ## Config | Field | Description | | - | - | | `timeout` 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. | | `url` | Full URL of the Qdrant server, such as a Qdrant Cloud cluster URL; when set, `host`, `port` and `https` are ignored. | | `host` default `'localhost'` | Host name of the Qdrant server when `url` is unset. | | `port` default `6333` | Port of the Qdrant server when `url` is unset. | | `https` default `false` | Connect to `host` over HTTPS when `url` is unset. | | `apiKey` secret | Qdrant API key, required by Qdrant Cloud. | | `collection` | Collection the mount root shows; unset lists every collection as a top-level folder. | | `groupBy` default `[]` | Payload fields that become folder levels, one per field in order; dotted paths reach nested keys. Unset puts every point's files directly under the collection. | | `basenameFields` default `[]` | `groupBy` fields whose folder names keep only the last path or URL segment of the value; two values with one basename under the same parent are refused as a collision. | | `idField` default `'id'` | Key the point id is written under in a point's `.json`; it replaces a payload field of that name. | | `nameField` | Payload field whose value prefixes each point's file stem as `<name>__<id>`; unset names files by point id alone. | | `textField` | Payload field served as the point's `.txt` file and printed by `search`; unset leaves no `.txt`, and `search` returns the `.json`. | | `blobField` | Payload field of raw or base64 bytes served as `<id>.<blobExt>` and left out of the `.json`; unset adds no blob file. | | `blobExt` default `'bin'` | File extension of the blob file, without the dot. | | `vectorField` | Payload field holding a copy of the vector, left out of the `.json`. | | `searchLimit` default `10` | Results `search` returns when `--top-k` is not given. | | `maxRows` default `1000` | Most points one folder listing scrolls; points past it are left out, and a group folder lists only the values those points carry. | | `embeddingModel` default `'sentence-transformers/all-MiniLM-L6-v2'` | Model the server embeds a `search` query with under `cloudInference`; it must match the model the stored vectors came from. | | `cloudInference` default `false` | Send the `search` query text to the server to embed, which needs a cluster with inference enabled (Qdrant Cloud). `embed` takes precedence; with neither, `search` refuses the query. | | `embed` secret | Async function that turns a `search` query into a vector in-process, `(text: string) => Promise<number[]>`. | Fields marked secret are redacted in snapshots. ### Document and chunk lineage Config fields accept Qdrant's dotted nested-key syntax. A LangChain-style payload with `page_content` and `metadata: { source, page }` can therefore use: ```ts theme={null} const docs = new QdrantVFS({ config: { collection: "company_docs", groupBy: ["metadata.source"], basenameFields: ["metadata.source"], nameField: "metadata.page", textField: "page_content", }, }); ``` For a source value `s3://docs/policies/refund-2026.pdf` and page value `004`, the chunk text is exposed as `refund-2026.pdf/004__<point-id>.txt`. The point id remains as a stable suffix, so duplicate labels cannot collide and direct reads work without a warm cache. Only the stem the listing publishes opens: another label in front of the same id reads as absent. A label that is not a string spells as compact JSON (`true`, `1`, `1e-7`), the same in TypeScript and Python. `basenameFields` strips URL/path parents from the named `groupBy` fields; omit a field to preserve its complete value in one path-safe segment: `/` renders as `∕`, and a blank or dot-led value is led by `⁄`, so every value has its own segment that lists and opens. A basename longer than 255 bytes, which ext4 and APFS refuse, is cut to fit and ends in `__` plus the md5 of the whole name, so two long leaves stay two directories. Basenames must be unique within a parent group; ambiguous listings are refused, and opening a basename directory checks every point of its parent group, so a second source past `maxRows` is refused rather than hidden. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Qdrant mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `qdrant`, read | > > #### VFS Layout > > ##### `/<path>` > > * A Qdrant vector database, exposed as a filesystem. > * At the root each directory is a collection, unless config pins a > single collection. > * Inside a collection, directories are the configured group-by payload > fields; descending one narrows a filter. > * Each matching point appears as files named by its Qdrant point id: > `<id>.json` (the full payload), `<id>.txt` (the embedded source text) > when a text field is configured, and `<id>.<ext>` (raw blob bytes) > when a blob field is configured. The embedding vector is never shown. > * `ls`, `cd`, `cat`, `tree`, `find`, `wc`, `grep` and `rg` work as > usual. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `qdrant` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `qdrant`, read | > > ## VFS Layout > > ### `/<path>` > > - A Qdrant vector database, exposed as a filesystem. > - At the root each directory is a collection, unless config pins a > single collection. > - Inside a collection, directories are the configured group-by payload > fields; descending one narrows a filter. > - Each matching point appears as files named by its Qdrant point id: > `<id>.json` (the full payload), `<id>.txt` (the embedded source text) > when a text field is configured, and `<id>.<ext>` (raw blob bytes) > when a blob field is configured. The embedding vector is never shown. > - `ls`, `cd`, `cat`, `tree`, `find`, `wc`, `grep` and `rg` work as > usual. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` ask `qdrant` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ``` ```text theme={null} /fashion/<gender>/<articleType>/<baseColour>/<id>.json # full payload (metadata) /fashion/<gender>/<articleType>/<baseColour>/<id>.txt # embedded source text /fashion/<gender>/<articleType>/<baseColour>/<id>.jpg # raw blob bytes ``` `<id>` is the Qdrant point id. With `nameField`, leaf stems use `<name>__<id>`. Semantic search is the `search` command, not a path: it returns ranked points as the canonical `.txt` (or `.json`) paths above, annotated with the similarity score. ## Search embedding `search` needs a vector for the query, and the config decides where it comes from. With `embed` set, a `(text: string) => Promise<number[]>` the caller brings, the query is vectorized in-process, so a self-hosted Qdrant works and mirage depends on no model runtime; `examples/typescript/vfs/qdrant/qdrant_vfs.ts` feeds it a dependency-free hashed bag of words, and any model that returns a vector plugs in the same way. Without it, `cloudInference: true` sends the query text to the server, so the cluster must have inference enabled (Qdrant Cloud) and store vectors from the same `embeddingModel` (default `sentence-transformers/all-MiniLM-L6-v2`). With neither, `search` refuses the query. The hook never lands in a snapshot: a restored mount asks for a fresh VFS. Browsing (`ls`/`cat`/`find`/`grep`) needs no embedding. ## Integration What Qdrant answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Qdrant | | - | - | | `grep -r`, `rg` | The payload text the listing keeps, for ASCII text. It misses nothing. | The [Python Qdrant docs](/python/vfs/qdrant#integration) list when each search answers and what it can miss. ## Supported commands `ls`, `cd`, `tree`, `cat`, `stat`, `find`, `wc`, `head` and `tail`. `grep`/`rg` stay lexical; the `search` CLI's `search "<query>" <path>` is the semantic path, returning ranked points as canonical `<id>.txt` (or `<id>.json`) paths plus a score, so results compose with `cat`, `wc`, and pipes. Flags: `--top-k`, `--threshold`, `--method semantic`. Folder listings filter on payload fields. A filtered listing scrolls first and only creates keyword payload indexes for the `groupBy` fields if Qdrant reports one is required. `maxRows` caps how many points are scanned per folder. # QingStor Source: https://docs.mirage.strukto.ai/typescript/setup/qingstor Set up QingStor as a MIRAGE VFS from Node or the browser. QingStor (QingCloud Object Storage) exposes an S3-compatible API with AWS Signature V4 against `https://s3.<zone>.qingstor.com`. MIRAGE derives this endpoint from your zone automatically (the zone is passed as `region`). Credentials (QingCloud API access key pair) are created the same way in both runtimes, see [QingStor Credentials](/home/setup/qingstor). ## Node (server-side) ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { MountMode, QingStorVFS, Workspace } from '@struktoai/mirage-node' const qs = new QingStorVFS({ bucket: process.env.QINGSTOR_BUCKET!, region: process.env.QINGSTOR_ZONE!, accessKeyId: process.env.QINGSTOR_ACCESS_KEY_ID!, secretAccessKey: process.env.QINGSTOR_SECRET_ACCESS_KEY!, }) const ws = new Workspace({ '/bucket/': qs }, { mode: MountMode.READ }) const res = await ws.shell('ls /bucket/') console.log(res.stdoutText) ``` ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `accessKeyId` secret | Access key ID; set it with `secretAccessKey`. Unset uses the AWS SDK credential chain. | | `secretAccessKey` secret | Secret access key paired with `accessKeyId`. | | `sessionToken` secret | Session token for temporary credentials, sent with the access key pair. | | `profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `forcePathStyle` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `keyPrefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `timeout` 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. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | | `region` required | Provider region every request is signed for. Most providers also build their endpoint URL from it unless `endpoint` is set. | | `endpoint` | Endpoint URL that replaces the one the provider derives. | Fields marked secret are redacted in snapshots. ## Browser (presigned URLs) ```bash theme={null} pnpm add @struktoai/mirage-browser ``` The browser `QingStorVFS` is secret-free, your backend signs each operation using your QingStor keys and returns a URL. QingStor accepts AWS Signature V4, so `@aws-sdk/s3-request-presigner` works, pointed at the QingStor endpoint. ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `presignedUrlProvider` required, secret | Function `(path, operation, options)` that returns a signed URL for each S3 operation; your server signs it, so the browser holds no keys. | | `region` | Region of the bucket. Most providers derive the endpoint from it; requests go to the host each presigned URL names. | | `endpoint` | Endpoint URL that replaces the one the provider derives. Requests go to the host each presigned URL names; the mount uses it to name its storage location. | | `defaultContentType` default `'application/octet-stream'` | `Content-Type` stored with every object the mount writes. | | `keyPrefix` | Key prefix the mount treats as its root. The browser can change it before a URL is signed, so enforce the prefix on the signing server. | | `timeout` 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. | Fields marked secret are redacted in snapshots. ### 1. Server: sign URLs with the QingStor endpoint ```ts theme={null} import { CopyObjectCommand, DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client, } from '@aws-sdk/client-s3' import { getSignedUrl } from '@aws-sdk/s3-request-presigner' const ZONE = process.env.QINGSTOR_ZONE! const client = new S3Client({ region: ZONE, endpoint: `https://s3.${ZONE}.qingstor.com`, credentials: { accessKeyId: process.env.QINGSTOR_ACCESS_KEY_ID!, secretAccessKey: process.env.QINGSTOR_SECRET_ACCESS_KEY!, }, }) const BUCKET = process.env.QINGSTOR_BUCKET! app.post('/presign/qingstor', async (req, res) => { const { path, op, opts } = req.body const key = path.replace(/^\/+/, '') const ttl = typeof opts?.ttlSec === 'number' ? opts.ttlSec : 300 let cmd switch (op) { case 'GET': cmd = new GetObjectCommand({ Bucket: BUCKET, Key: key }); break case 'PUT': cmd = new PutObjectCommand({ Bucket: BUCKET, Key: key, ContentType: opts?.contentType }); break case 'HEAD': cmd = new HeadObjectCommand({ Bucket: BUCKET, Key: key }); break case 'DELETE': cmd = new DeleteObjectCommand({ Bucket: BUCKET, Key: key }); break case 'LIST': cmd = new ListObjectsV2Command({ Bucket: BUCKET, Prefix: opts?.listPrefix, Delimiter: opts?.listDelimiter, ContinuationToken: opts?.listContinuationToken, }); break case 'COPY': cmd = new CopyObjectCommand({ Bucket: BUCKET, Key: key, CopySource: `${BUCKET}/${opts?.copySource}`, }); break } res.json({ url: await getSignedUrl(client, cmd, { expiresIn: ttl }) }) }) ``` ### 2. Browser: wire it up ```ts theme={null} import { MountMode, QingStorVFS, Workspace } from '@struktoai/mirage-browser' const qs = new QingStorVFS({ bucket: 'my-bucket', region: 'pek3a', presignedUrlProvider: async (path, op, opts) => { const r = await fetch('/presign/qingstor', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path, op, opts }), }) const { url } = await r.json() return url }, }) const ws = new Workspace({ '/bucket/': qs }, { mode: MountMode.READ }) ``` > [!TIP] > > `region` on the browser config is only used for display/logging; the actual endpoint is baked into the presigned URLs your backend returns. ### 3. CORS Configure CORS rules in the QingCloud console: QingStor -> your bucket -> **Basic Settings** -> **CORS**. Allow your dev/production origins with methods `GET, PUT, HEAD, DELETE, POST`, allowed headers `*`, and expose headers `ETag, Content-Length, Content-Type, Last-Modified`. See the [QingStor VFS](/python/vfs/qingstor) docs for the equivalent Python wiring. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with QingStor mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Integration What QingStor answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On QingStor | | - | - | | `find`, `du`, `ls -R`, `tree` | One recursive listing | # Cloudflare R2 Source: https://docs.mirage.strukto.ai/typescript/setup/r2 Set up Cloudflare R2 as a MIRAGE VFS from Node or the browser. R2 uses the S3 API with AWS Signature V4 against `https://<account-id>.r2.cloudflarestorage.com`. MIRAGE derives this endpoint from your account ID automatically. Credentials (R2 API token with object read/write scopes) are created the same way in both runtimes, see [R2 Credentials](/home/setup/r2). ## Node (server-side) ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { MountMode, R2VFS, Workspace } from '@struktoai/mirage-node' const r2 = new R2VFS({ bucket: process.env.R2_BUCKET!, accountId: process.env.R2_ACCOUNT_ID!, accessKeyId: process.env.R2_ACCESS_KEY_ID!, secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!, }) const ws = new Workspace({ '/bucket/': r2 }, { mode: MountMode.READ }) const res = await ws.shell('ls /bucket/') console.log(res.stdoutText) ``` ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `accessKeyId` secret | Access key ID; set it with `secretAccessKey`. Unset uses the AWS SDK credential chain. | | `secretAccessKey` secret | Secret access key paired with `accessKeyId`. | | `sessionToken` secret | Session token for temporary credentials, sent with the access key pair. | | `profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `forcePathStyle` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `keyPrefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `timeout` 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. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | | `region` default `'auto'` | Region requests are signed for; R2 addresses a bucket by account, not by region. | | `endpoint` | Endpoint URL that replaces the one the provider derives. | | `accountId` | Cloudflare account ID. It builds the endpoint `https://<accountId>.r2.cloudflarestorage.com` unless `endpoint` is set; one of the two is required. | Fields marked secret are redacted in snapshots. ## Browser (presigned URLs) ```bash theme={null} pnpm add @struktoai/mirage-browser ``` The browser `R2VFS` is secret-free, your backend signs each operation using your R2 keys and returns a URL. R2 accepts AWS Signature V4, so `@aws-sdk/s3-request-presigner` works with `region: 'auto'` pointed at R2's endpoint. ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `presignedUrlProvider` required, secret | Function `(path, operation, options)` that returns a signed URL for each S3 operation; your server signs it, so the browser holds no keys. | | `region` default `'auto'` | Region of the bucket; R2 addresses a bucket by account, not by region. | | `endpoint` | Endpoint URL that replaces the one the provider derives. Requests go to the host each presigned URL names; the mount uses it to name its storage location. | | `defaultContentType` default `'application/octet-stream'` | `Content-Type` stored with every object the mount writes. | | `keyPrefix` | Key prefix the mount treats as its root. The browser can change it before a URL is signed, so enforce the prefix on the signing server. | | `timeout` 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. | | `accountId` | Cloudflare account ID. It builds the endpoint `https://<accountId>.r2.cloudflarestorage.com` unless `endpoint` is set. | Fields marked secret are redacted in snapshots. ### 1. Server: sign URLs with the R2 endpoint ```ts theme={null} import { CopyObjectCommand, DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client, } from '@aws-sdk/client-s3' import { getSignedUrl } from '@aws-sdk/s3-request-presigner' const client = new S3Client({ region: 'auto', endpoint: `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`, credentials: { accessKeyId: process.env.R2_ACCESS_KEY_ID!, secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!, }, }) const BUCKET = process.env.R2_BUCKET! app.post('/presign/r2', async (req, res) => { const { path, op, opts } = req.body const key = path.replace(/^\/+/, '') const ttl = typeof opts?.ttlSec === 'number' ? opts.ttlSec : 300 let cmd switch (op) { case 'GET': cmd = new GetObjectCommand({ Bucket: BUCKET, Key: key }); break case 'PUT': cmd = new PutObjectCommand({ Bucket: BUCKET, Key: key, ContentType: opts?.contentType }); break case 'HEAD': cmd = new HeadObjectCommand({ Bucket: BUCKET, Key: key }); break case 'DELETE': cmd = new DeleteObjectCommand({ Bucket: BUCKET, Key: key }); break case 'LIST': cmd = new ListObjectsV2Command({ Bucket: BUCKET, Prefix: opts?.listPrefix, Delimiter: opts?.listDelimiter, ContinuationToken: opts?.listContinuationToken, }); break case 'COPY': cmd = new CopyObjectCommand({ Bucket: BUCKET, Key: key, CopySource: `${BUCKET}/${opts?.copySource}`, }); break } res.json({ url: await getSignedUrl(client, cmd, { expiresIn: ttl }) }) }) ``` ### 2. Browser: wire it up ```ts theme={null} import { MountMode, R2VFS, Workspace } from '@struktoai/mirage-browser' const r2 = new R2VFS({ bucket: 'my-r2-bucket', accountId: 'abc123...', presignedUrlProvider: async (path, op, opts) => { const r = await fetch('/presign/r2', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path, op, opts }), }) const { url } = await r.json() return url }, }) const ws = new Workspace({ '/bucket/': r2 }, { mode: MountMode.READ }) ``` > [!TIP] > > `accountId` on the browser config is only used for display/logging; the actual endpoint is baked into the presigned URLs your backend returns. ### 3. Configure CORS on the bucket R2 does accept S3-flavored `PutBucketCors`, but your token needs **"Admin Read & Write"** permissions on the bucket, object-scoped tokens will get `Access Denied`. Two paths: **Option A, Cloudflare Dashboard (fastest, no new token):** 1. Open [https://dash.cloudflare.com](https://dash.cloudflare.com) → **R2** → your bucket 2. **Settings** tab → **CORS Policy** → **Add CORS policy** 3. Origin: `http://localhost:5173` (and any production origins), methods `GET,PUT,HEAD,DELETE,POST`, allowed headers `*` **Option B, admin-scoped R2 API token + the helper script:** 1. Cloudflare Dashboard → **R2** → **Manage R2 API Tokens** → **Create API token** 2. Permissions: **Admin Read & Write** on your bucket 3. Update `R2_ACCESS_KEY_ID` / `R2_SECRET_ACCESS_KEY` in `.env.development` 4. Run the same helper used for S3: ```bash theme={null} cd examples/browser npx tsx scripts/configure-cors.ts http://localhost:5173 https://app.example.com ``` > [!WARNING] > > Object-scoped tokens (`Object Read & Write`) cannot edit CORS. If the script returns `Access Denied` on R2, you're almost certainly using an object token. See the [R2 VFS](/python/vfs/r2) docs for the equivalent Python wiring. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Cloudflare R2 mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Integration What R2 answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On R2 | | - | - | | `md5sum` | The object's ETag, when it is the MD5: a single-part upload, unencrypted or under SSE-S3 | | `find`, `du`, `ls -R`, `tree` | One recursive listing | # RAM Source: https://docs.mirage.strukto.ai/typescript/setup/ram Use an in-memory Mirage filesystem for temporary files, tests, examples, and writable agent scratch space. The RAM VFS exposes an in-memory filesystem mounted at a path prefix such as `/data/`. All files live in process memory and are discarded when the process exits. Available across Node, browser, and edge runtimes via `@struktoai/mirage-node` and `@struktoai/mirage-browser`. No setup or credentials required. For Python, see the [RAM (Python)](/python/vfs/ram) documentation. ## Config ```typescript theme={null} import { MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node' const ws = new Workspace({ '/data': new RAMVFS(), }, { mode: MountMode.WRITE }) ``` `RAMVFS()` requires no configuration object. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with RAM mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `grep -r`, `find` and `du` stop after 10000 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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `grep -r`, `find` and `du` stop after 10000 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. > ``` The RAM filesystem starts empty. Files and directories are created on demand via shell commands such as `touch`, `mkdir`, `tee`, and `cp`. Paths are normalized with a leading `/`. The root directory `/` always exists. ## Cache The RAM VFS does not cache directory listings (`index_ttl = 0`): because data resides entirely in memory, every listing reads the live tree directly without network latency. A workspace or mount `index:` configuration still applies its `ttl` if specified. ## Integration Commands like `find`, `du`, `ls -R`, and `tree` execute directly in-process via a single recursive tree traversal. ## Example ```typescript theme={null} import { MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node' const ws = new Workspace({ '/data': new RAMVFS(), }, { mode: MountMode.WRITE }) // Create files and directories await ws.shell('echo "hello world" > /data/hello.txt') await ws.shell('mkdir -p /data/reports') await ws.shell('echo \'{"status": "ok"}\' > /data/reports/status.json') // Read file contents const hello = await ws.shell('cat /data/hello.txt') console.log(await hello.stdoutStr()) // Run shell pipelines const json = await ws.shell('jq -r .status /data/reports/status.json') console.log(await json.stdoutStr()) ``` # Redis Source: https://docs.mirage.strukto.ai/typescript/setup/redis Mount Redis keys as a Mirage filesystem. `RedisVFS` exposes Redis keys as files under a single mount. The base of every key is the configured `keyPrefix`. > [!NOTE] > > Node needs the `redis@^5` peer dependency and speaks the Redis protocol over a socket. On > [Cloudflare](#cloudflare) the mount speaks the same protocol over the Workers socket API. The > browser has no socket, so it reaches Redis through the [Upstash REST API](#browser) instead. ## Install ```bash theme={null} pnpm add @struktoai/mirage-node redis ``` ## Config ```ts theme={null} import { MountMode, RedisVFS, Workspace } from '@struktoai/mirage-node' const redis = new RedisVFS({ url: process.env.REDIS_URL ?? 'redis://localhost:6379', keyPrefix: 'mirage/', }) const ws = new Workspace({ '/r': redis }, { mode: MountMode.WRITE }) await ws.shell('echo "hello" | tee /r/greet') await ws.shell('cat /r/greet') ``` | Field | Default | Notes | | - | - | - | | `url` | `redis://localhost:6379/0` | Standard Redis connection URL. Redacted in snapshots. | | `keyPrefix` | `mirage:fs:` | Prefix prepended to every key. Useful for multi-tenant Redis instances. | ## Mount mode `read`, `write`, `exec`. ## Browser A page cannot open a TCP connection, and Redis has no HTTP listener of its own, so `@struktoai/mirage-browser` mounts Redis through the REST API that [Upstash](https://upstash.com/docs/redis/features/restapi) serves in front of its databases. The configuration is the one the Node mount takes: the redis URL the Upstash console prints. Its password is also the REST token, so the store reaches `https://<name>.upstash.io` with it and no second field is needed. [Upstash Redis](/typescript/setup/upstash) covers that database on its own page. ```ts theme={null} import { MountMode, RedisVFS, Workspace } from '@struktoai/mirage-browser' const redis = new RedisVFS({ url: 'rediss://default:<token>@<name>.upstash.io:6379', keyPrefix: 'mirage/', }) const ws = new Workspace({ '/r': redis }, { mode: MountMode.WRITE }) await ws.shell('echo "hello" | tee /r/greet') await ws.shell('cat /r/greet') ``` | Field | Default | Notes | | - | - | - | | `url` | required | The database's redis URL, password included; or its REST URL (`https://<name>.upstash.io`) with `token` beside it. Redacted in snapshots. | | `token` | from the URL | The REST token. Only needed with a REST URL, which is how a self-hosted [serverless-redis-http](https://github.com/hiett/serverless-redis-http) front is addressed, since its token is not a redis password. A read-only token cannot `SCAN`, which directory listings need, so use the full one. | | `keyPrefix` | `mirage:fs:` | Prefix prepended to every key. | | `maxRequestBytes` | `8388608` | Upstash caps a request at 10 MB; a larger file is written as one `SET` plus `APPEND`s of this size. | The key layout is the one the Node and Python mounts use, and the store keeps every value byte-identical (writes go out as raw request bodies, reads come back base64-encoded), so one Upstash database can be mounted from a page over REST and from a server over the Redis protocol at the same time. Upstash bills the free and pay-as-you-go tiers per command, and one shell command is several Redis commands (a directory listing costs a few per entry), which is worth knowing before pointing an agent at a metered database. Two examples exercise this path. [`examples/browser/vfs/redis/redis.html`](https://github.com/strukto-ai/mirage/blob/main/examples/browser/vfs/redis/redis.html) mounts a database from a page against Upstash itself, reading `UPSTASH_REDIS_URL` from `.env.development`. [`examples/browser/vfs/redis/main.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/browser/vfs/redis/main.ts) needs no account: it starts an in-process HTTP front that speaks the same REST shape over a local redis, mounts it through `@struktoai/mirage-browser`, and reads every key back through the Node mount to show the two stores agree byte for byte. ## Cloudflare `@struktoai/mirage-cloudflare` speaks the Redis protocol over the Workers TCP API (`connect()` from `cloudflare:sockets`), with a client of its own rather than `redis`. It takes the URL and key layout the Node and Python mounts take, so it reaches any Redis, Upstash included, at its `redis://` or `rediss://` URL, and the three runtimes on one server serve one filesystem. ```ts theme={null} import { MountMode, RedisVFS, Workspace } from '@struktoai/mirage-cloudflare' const redis = new RedisVFS({ url: env.REDIS_URL, keyPrefix: 'mirage/' }) const ws = new Workspace({ '/r': redis }, { mode: MountMode.WRITE }) ``` The fields are `url`, `keyPrefix` and `capacity`, as on Node, and the server API builds the mount from `vfs: redis`. A Worker cannot keep a socket past the request that opened it, so each request opens its own connection; a later command in the same request reuses it. Workers refuse connections to Cloudflare's own IP ranges. For the broader Redis semantics (binary keys, key patterns) see the [Python Redis docs](/python/vfs/redis). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Redis mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Integration What Redis answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Redis | | - | - | | `find`, `du`, `ls -R`, `tree` | One recursive listing | # S3 Source: https://docs.mirage.strukto.ai/typescript/setup/s3 Set up AWS S3 as a MIRAGE VFS from Node or the browser. MIRAGE ships `S3VFS` in **two runtimes**: * `@struktoai/mirage-node`, signs requests server-side using [@aws-sdk/client-s3](https://www.npmjs.com/package/@aws-sdk/client-s3). * `@struktoai/mirage-browser`, stays secret-free: your backend hands out **presigned URLs** and the browser fetches them with `fetch()`. Credentials (IAM user, access keys) are created the same way in both runtimes, see [AWS S3 Credentials](/home/setup/s3). ## Node (server-side) ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { MountMode, Workspace } from '@struktoai/mirage-node' import { S3VFS } from '@struktoai/mirage-node' const s3 = new S3VFS({ bucket: process.env.AWS_S3_BUCKET!, region: process.env.AWS_DEFAULT_REGION ?? 'us-east-1', accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, // Optional: // endpoint: 'http://localhost:9000', // MinIO // forcePathStyle: true, // For MinIO/R2 // timeout: 30, // proxy: 'http://proxy:8080', }) const ws = new Workspace({ '/bucket/': s3 }, { mode: MountMode.READ }) const res = await ws.shell('ls /bucket/') console.log(res.stdoutText) ``` If `~/.aws/credentials` is configured, you can omit `accessKeyId`/`secretAccessKey` and the AWS SDK picks up the default profile. Under `write: conditional` a write carries the version of the file mirage read, and S3 refuses it when the file has changed since. The endpoint decides which writes can be conditioned: AWS's conditions every write, copy and delete; any other `endpoint` (or `AWS_ENDPOINT_URL_S3`/`AWS_ENDPOINT_URL`) only a write, so mirage refuses what would copy or delete there. An endpoint set only in an AWS profile is not read: give a non-AWS server its `endpoint`. A browser mount signed by presigned URLs cannot carry a condition, so it cannot declare `write: conditional`. If the session last saw no file at the path, the write sends `If-None-Match: *` and fails if someone created the file in the meantime. A conditional single-file move attempts rollback when source deletion is refused. The move still fails and warns if the destination may remain. Cleanup uses the copy's S3 version or, for a new destination, its ETag. Unversioned overwrites, same-ETag replacements, retried versioned copies, and uncertain delete outcomes limit recovery; inspect both paths after a failure. An absent destination must remain absent until copying. This guard may add one metadata request; cleanup adds one delete and may require `s3:DeleteObjectVersion`. Directory and cross-mount moves do not use rollback. A directory `mv`, `rm -r` or `rmdir` looks at the directory again when it is done: a file written into it that the command never listed stays, and the command fails with `Directory not empty`. Under `write: conditional`, a directory `mv` that finds a file changed before it could copy it removes nothing from the source; the copies it made stay at the destination. An append or another rewrite that observes a missing file uses create-only commit under either write policy. S3 checks `If-None-Match: *` at PUT or final multipart completion, so a delayed creation cannot replace a competing writer's bytes. A lost condition returns an error without automatic retry. Existing-file appends under `unconditional` retain last-write-wins behavior. ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `region` | AWS region requests are signed for and sent to. Unset leaves it to the AWS SDK's environment variables and profile. | | `endpoint` | Endpoint URL of an S3-compatible server. Unset, the node mount uses `AWS_ENDPOINT_URL_S3` or `AWS_ENDPOINT_URL` when set, else AWS's endpoint for `region`; an endpoint set only in an AWS profile is not read. | | `accessKeyId` secret | Access key ID; set it with `secretAccessKey`. Unset uses the AWS SDK credential chain. | | `secretAccessKey` secret | Secret access key paired with `accessKeyId`. | | `sessionToken` secret | Session token for temporary credentials, sent with the access key pair. | | `forcePathStyle` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `timeout` 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. | | `presignedUrlProvider` secret | Function `(path, operation, options)` that returns a signed URL for each S3 operation. When set, the mount fetches those URLs and needs no credentials. | | `httpAgentProvider` secret | Function that returns the `httpAgent` and `httpsAgent` for one S3 client, called once per client. The node mount builds it from `proxy` when that is set. | | `defaultContentType` | `Content-Type` stored with every object the mount writes. Unset sends none, so the store applies its own default; a write through `presignedUrlProvider` sends `application/octet-stream`. | | `keyPrefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | Fields marked secret are redacted in snapshots. ## Browser (presigned URLs) ```bash theme={null} pnpm add @struktoai/mirage-browser ``` The browser `S3VFS` never sees AWS credentials. You implement one function, `presignedUrlProvider`, that your frontend calls to get a signed URL for each S3 operation. The actual signing happens on **your server**, using any S3-signing SDK you prefer. ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `region` | AWS region requests are signed for and sent to. Unset leaves it to the AWS SDK's environment variables and profile. | | `endpoint` | Endpoint URL of an S3-compatible server. Unset, the node mount uses `AWS_ENDPOINT_URL_S3` or `AWS_ENDPOINT_URL` when set, else AWS's endpoint for `region`; an endpoint set only in an AWS profile is not read. | | `timeout` 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. | | `presignedUrlProvider` secret | Function `(path, operation, options)` that returns a signed URL for each S3 operation. When set, the mount fetches those URLs and needs no credentials. | | `defaultContentType` | `Content-Type` stored with every object the mount writes. Unset sends none, so the store applies its own default; a write through `presignedUrlProvider` sends `application/octet-stream`. | | `keyPrefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | Fields marked secret are redacted in snapshots. The browser `S3VFS` can also sign requests itself, without `presignedUrlProvider`: it then takes the credential fields of the [Node config](#config), which puts the keys in the browser. ### 1. Server: sign URLs on demand Using [@aws-sdk/s3-request-presigner](https://www.npmjs.com/package/@aws-sdk/s3-request-presigner): ```ts theme={null} import { CopyObjectCommand, DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client, } from '@aws-sdk/client-s3' import { getSignedUrl } from '@aws-sdk/s3-request-presigner' const client = new S3Client({ region: process.env.AWS_DEFAULT_REGION }) const BUCKET = process.env.AWS_S3_BUCKET! app.post('/presign', async (req, res) => { const { path, op, opts } = req.body as { path: string op: 'GET' | 'PUT' | 'HEAD' | 'DELETE' | 'LIST' | 'COPY' opts?: Record<string, unknown> } const key = path.replace(/^\/+/, '') const ttl = typeof opts?.ttlSec === 'number' ? opts.ttlSec : 300 let cmd switch (op) { case 'GET': cmd = new GetObjectCommand({ Bucket: BUCKET, Key: key }); break case 'PUT': cmd = new PutObjectCommand({ Bucket: BUCKET, Key: key, ContentType: opts?.contentType as string | undefined }); break case 'HEAD': cmd = new HeadObjectCommand({ Bucket: BUCKET, Key: key }); break case 'DELETE': cmd = new DeleteObjectCommand({ Bucket: BUCKET, Key: key }); break case 'LIST': cmd = new ListObjectsV2Command({ Bucket: BUCKET, Prefix: opts?.listPrefix as string | undefined, Delimiter: opts?.listDelimiter as string | undefined, ContinuationToken: opts?.listContinuationToken as string | undefined, }); break case 'COPY': cmd = new CopyObjectCommand({ Bucket: BUCKET, Key: key, CopySource: `${BUCKET}/${opts?.copySource as string}`, }); break } const url = await getSignedUrl(client, cmd, { expiresIn: ttl }) res.json({ url }) }) ``` > [!TIP] > > Scope the presigner to the **minimal operations your app needs**. Read-only viewers only need `GET`/`HEAD`/`LIST`; a file manager needs the full set. ### 2. Browser: wire it up ```ts theme={null} import { MountMode, S3VFS, Workspace } from '@struktoai/mirage-browser' const s3 = new S3VFS({ bucket: 'my-bucket', presignedUrlProvider: async (path, op, opts) => { const r = await fetch('/presign', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path, op, opts }), }) const { url } = (await r.json()) as { url: string } return url }, }) const ws = new Workspace({ '/bucket/': s3 }, { mode: MountMode.READ }) const res = await ws.shell('cat /bucket/hello.txt') console.log(res.stdoutText) ``` ### Customize a builtin command The generic command definitions are available before a workspace is created. Copy the definition with the behavior you want to change, then register that copy on one mount: ```ts theme={null} import { generic } from '@struktoai/mirage-browser' const cat = generic('cat') ws.mount('/bucket/')?.register({ ...cat, fn: async (accessor, paths, texts, opts) => { console.log('reading', paths.map((path) => path.virtual)) return cat.fn(accessor, paths, texts, opts) }, }) ``` Use the same `generic` export from `@struktoai/mirage-node` for a Node workspace. The builtin definition and other mounts stay unchanged. Registration is a host application action; an agent can discover and run the resulting `cat` command, but cannot alter the command table. ### 3. Configure CORS on the bucket Presigned URLs reach the S3 host directly from the browser. Your bucket must allow cross-origin requests from your app's origin, otherwise every `fetch()` fails with `TypeError: Failed to fetch` (the browser drops the response at the CORS preflight). ```json theme={null} [ { "AllowedOrigins": ["http://localhost:5173", "https://app.example.com"], "AllowedMethods": ["GET", "PUT", "HEAD", "DELETE", "POST"], "AllowedHeaders": ["*"], "ExposeHeaders": ["ETag", "Content-Length", "Content-Type", "Last-Modified"], "MaxAgeSeconds": 3000 } ] ``` ```bash theme={null} aws s3api put-bucket-cors --bucket $AWS_S3_BUCKET --cors-configuration file://cors.json ``` **Or** use the helper in the browser example, it signs the `PutBucketCors` call with your existing env credentials and applies the same policy to all configured buckets in one shot: ```bash theme={null} cd examples/browser npx tsx scripts/configure-cors.ts http://localhost:5173 https://app.example.com ``` > [!WARNING] > > CORS is origin-exact. `http://localhost:5173` ≠ `http://localhost:5174` ≠ `https://app.example.com`. Include every origin you'll serve the page from. See [S3 Setup](/home/setup/s3) for credential setup. ## Refused keys When credentials cannot read an S3 object (S3 returns `AccessDenied`, or a bodiless HTTP 403 response on a `HEAD` request), Mirage reports `EACCES` (`Permission denied`) for that file operand. Shell commands follow standard POSIX conventions: * `cat a b c` prints the contents of `a` and `c`, writes a permission error for `b` to `stderr`, and exits with a non-zero status. * `grep -r` logs an error on inaccessible files and exits with status `2`. * `cp b x || fallback` triggers the fallback branch. * `test -e b` evaluates to false. ### IAM permissions and existence checks * **Scoped grants:** When access is granted below a specific prefix (for example, `s3:GetObject` on `bucket/dir/*` alongside `s3:ListBucket` on the bucket), Mirage treats `dir` as a directory during `stat`. * **Missing `ListBucket`:** Without `s3:ListBucket` permission, S3 returns HTTP 403 even for non-existent keys to avoid leaking existence. As a result, non-existent files report `Permission denied` (`EACCES`) instead of `No such file or directory` (`ENOENT`). * **Listed but unreadable keys:** If `ListObjectsV2` includes an object that your credentials cannot read, `stat` and `test -e` report that the file exists, while read attempts (`cat`) fail with `Permission denied`. * **Browser presigned URLs:** Mirage does not parse the HTTP error body when reading through presigned URLs in the browser. Any HTTP 403 status (including expired or misconfigured URLs) is handled as a permission refusal. ## Scoping a VFS to a key prefix Pass `keyPrefix` to scope every operation to a subpath of the bucket: ```ts theme={null} const s3 = new S3VFS({ bucket: 'app-data', region: 'eu-west-1', keyPrefix: `users/${userId}/`, }) ``` When set, every read/write/list/stat/copy/rename/delete operation is transparently scoped to that bucket subpath. Agents see clean paths like `/data/notes.md`; the underlying bucket key is `users/${userId}/data/notes.md`. Useful for multi-tenant systems. Pairs naturally with STS AssumeRole session policies for AWS-side enforcement. Unset behavior is unchanged. **Normalization:** leading slashes are stripped and a trailing slash is added automatically. Both `undefined` and an empty string are treated as "no prefix." In YAML-based configs the snake-case spelling `key_prefix` is also accepted and is automatically mapped to `keyPrefix` at construction. > [!WARNING] > > **Browser variant — security note** > > For `mirage-browser`'s `S3VFS` (which uses `presignedUrlProvider`), `keyPrefix` flows through the same core code path, but a client-controlled prefix is not a security boundary — a malicious client can ignore or alter it before signing. For real isolation, enforce the prefix inside your server-side `presignedUrlProvider` implementation (and in the IAM/STS session policy backing those credentials). Treat the client-side `keyPrefix` as ergonomics only. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with S3 mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Integration What S3 answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On S3 | | - | - | | `md5sum` | The object's ETag, when it is the MD5: a single-part upload, unencrypted or under SSE-S3 | | `find`, `du`, `ls -R`, `tree` | One recursive listing | # Scaleway Source: https://docs.mirage.strukto.ai/typescript/setup/scaleway Set up Scaleway Object Storage as a MIRAGE VFS from Node or the browser. Scaleway Object Storage uses the S3 API with AWS Signature V4 against `https://s3.<region>.scw.cloud`. MIRAGE derives this endpoint from your region automatically. Credentials (IAM API key, the access key + secret key pair) are created the same way in both runtimes, see [Scaleway Credentials](/home/setup/scaleway). ## Node (server-side) ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { MountMode, ScalewayVFS, Workspace } from '@struktoai/mirage-node' const scw = new ScalewayVFS({ bucket: process.env.SCW_BUCKET!, region: process.env.SCW_REGION!, accessKeyId: process.env.SCW_ACCESS_KEY!, secretAccessKey: process.env.SCW_SECRET_KEY!, }) const ws = new Workspace({ '/bucket/': scw }, { mode: MountMode.READ }) const res = await ws.shell('ls /bucket/') console.log(res.stdoutText) ``` ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `accessKeyId` secret | Access key ID; set it with `secretAccessKey`. Unset uses the AWS SDK credential chain. | | `secretAccessKey` secret | Secret access key paired with `accessKeyId`. | | `sessionToken` secret | Session token for temporary credentials, sent with the access key pair. | | `profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `forcePathStyle` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `keyPrefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `timeout` 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. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | | `region` required | Provider region every request is signed for. Most providers also build their endpoint URL from it unless `endpoint` is set. | | `endpoint` | Endpoint URL that replaces the one the provider derives. | Fields marked secret are redacted in snapshots. ## Browser (presigned URLs) ```bash theme={null} pnpm add @struktoai/mirage-browser ``` The browser `ScalewayVFS` is secret-free, your backend signs each operation using your Scaleway keys and returns a URL. Scaleway accepts AWS Signature V4, so `@aws-sdk/s3-request-presigner` works, pointed at the Scaleway endpoint. ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `presignedUrlProvider` required, secret | Function `(path, operation, options)` that returns a signed URL for each S3 operation; your server signs it, so the browser holds no keys. | | `region` | Region of the bucket. Most providers derive the endpoint from it; requests go to the host each presigned URL names. | | `endpoint` | Endpoint URL that replaces the one the provider derives. Requests go to the host each presigned URL names; the mount uses it to name its storage location. | | `defaultContentType` default `'application/octet-stream'` | `Content-Type` stored with every object the mount writes. | | `keyPrefix` | Key prefix the mount treats as its root. The browser can change it before a URL is signed, so enforce the prefix on the signing server. | | `timeout` 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. | Fields marked secret are redacted in snapshots. ### 1. Server: sign URLs with the Scaleway endpoint ```ts theme={null} import { CopyObjectCommand, DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client, } from '@aws-sdk/client-s3' import { getSignedUrl } from '@aws-sdk/s3-request-presigner' const REGION = process.env.SCW_REGION! const client = new S3Client({ region: REGION, endpoint: `https://s3.${REGION}.scw.cloud`, credentials: { accessKeyId: process.env.SCW_ACCESS_KEY!, secretAccessKey: process.env.SCW_SECRET_KEY!, }, }) const BUCKET = process.env.SCW_BUCKET! app.post('/presign/scw', async (req, res) => { const { path, op, opts } = req.body const key = path.replace(/^\/+/, '') const ttl = typeof opts?.ttlSec === 'number' ? opts.ttlSec : 300 let cmd switch (op) { case 'GET': cmd = new GetObjectCommand({ Bucket: BUCKET, Key: key }); break case 'PUT': cmd = new PutObjectCommand({ Bucket: BUCKET, Key: key, ContentType: opts?.contentType }); break case 'HEAD': cmd = new HeadObjectCommand({ Bucket: BUCKET, Key: key }); break case 'DELETE': cmd = new DeleteObjectCommand({ Bucket: BUCKET, Key: key }); break case 'LIST': cmd = new ListObjectsV2Command({ Bucket: BUCKET, Prefix: opts?.listPrefix, Delimiter: opts?.listDelimiter, ContinuationToken: opts?.listContinuationToken, }); break case 'COPY': cmd = new CopyObjectCommand({ Bucket: BUCKET, Key: key, CopySource: `${BUCKET}/${opts?.copySource}`, }); break } res.json({ url: await getSignedUrl(client, cmd, { expiresIn: ttl }) }) }) ``` ### 2. Browser: wire it up ```ts theme={null} import { MountMode, ScalewayVFS, Workspace } from '@struktoai/mirage-browser' const scw = new ScalewayVFS({ bucket: 'my-bucket', region: 'fr-par', presignedUrlProvider: async (path, op, opts) => { const r = await fetch('/presign/scw', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path, op, opts }), }) const { url } = await r.json() return url }, }) const ws = new Workspace({ '/bucket/': scw }, { mode: MountMode.READ }) ``` > [!TIP] > > `region` on the browser config is only used for display/logging; the actual endpoint is baked into the presigned URLs your backend returns. ### 3. CORS Scaleway supports the S3 `PutBucketCors` call, so the AWS CLI works against the Scaleway endpoint: ```bash theme={null} aws s3api put-bucket-cors --bucket "$SCW_BUCKET" \ --endpoint-url "https://s3.$SCW_REGION.scw.cloud" \ --cors-configuration '{"CORSRules":[{"AllowedOrigins":["http://localhost:5173","https://app.example.com"],"AllowedMethods":["GET","PUT","HEAD","DELETE","POST"],"AllowedHeaders":["*"],"ExposeHeaders":["ETag","Content-Length","Content-Type","Last-Modified"]}]}' ``` See the [Scaleway VFS](/python/vfs/scaleway) docs for the equivalent Python wiring. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Scaleway mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Integration What Scaleway answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Scaleway | | - | - | | `find`, `du`, `ls -R`, `tree` | One recursive listing | # SeaweedFS Source: https://docs.mirage.strukto.ai/typescript/setup/seaweedfs Set up SeaweedFS as a MIRAGE VFS from Node or the browser. SeaweedFS speaks the S3 API with AWS Signature V4 against its S3 gateway endpoint (e.g. `http://localhost:8333`). The gateway is self-hosted, so the endpoint is required and path-style addressing is used by default. Credentials (access key + secret key from the gateway's `-s3.config`) are created the same way in both runtimes, see [SeaweedFS Credentials](/home/setup/seaweedfs). ## Node (server-side) ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { SeaweedFSVFS, MountMode, Workspace } from '@struktoai/mirage-node' const seaweedfs = new SeaweedFSVFS({ bucket: process.env.SEAWEEDFS_BUCKET!, endpoint: process.env.SEAWEEDFS_ENDPOINT!, accessKeyId: process.env.SEAWEEDFS_ACCESS_KEY!, secretAccessKey: process.env.SEAWEEDFS_SECRET_KEY!, }) const ws = new Workspace({ '/bucket/': seaweedfs }, { mode: MountMode.READ }) const res = await ws.shell('ls /bucket/') console.log(res.stdoutText) ``` ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `accessKeyId` secret | Access key ID; set it with `secretAccessKey`. Unset uses the AWS SDK credential chain. | | `secretAccessKey` secret | Secret access key paired with `accessKeyId`. | | `sessionToken` secret | Session token for temporary credentials, sent with the access key pair. | | `profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `forcePathStyle` default `true` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `keyPrefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `timeout` 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. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | | `region` default `'us-east-1'` | Region requests are signed for; the gateway's endpoint does not depend on it. | | `endpoint` required | URL of the self-hosted S3 gateway, such as `http://localhost:9000`. | Fields marked secret are redacted in snapshots. ## Browser (presigned URLs) ```bash theme={null} pnpm add @struktoai/mirage-browser ``` The browser `SeaweedFSVFS` is secret-free, your backend signs each operation using your SeaweedFS keys and returns a URL. SeaweedFS accepts AWS Signature V4, so `@aws-sdk/s3-request-presigner` works, pointed at your gateway endpoint. ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `presignedUrlProvider` required, secret | Function `(path, operation, options)` that returns a signed URL for each S3 operation; your server signs it, so the browser holds no keys. | | `region` | Region of the bucket. Most providers derive the endpoint from it; requests go to the host each presigned URL names. | | `endpoint` | Endpoint URL that replaces the one the provider derives. Requests go to the host each presigned URL names; the mount uses it to name its storage location. | | `defaultContentType` default `'application/octet-stream'` | `Content-Type` stored with every object the mount writes. | | `keyPrefix` | Key prefix the mount treats as its root. The browser can change it before a URL is signed, so enforce the prefix on the signing server. | | `timeout` 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. | Fields marked secret are redacted in snapshots. ### 1. Server: sign URLs with the SeaweedFS endpoint ```ts theme={null} import { CopyObjectCommand, DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client, } from '@aws-sdk/client-s3' import { getSignedUrl } from '@aws-sdk/s3-request-presigner' const client = new S3Client({ region: 'us-east-1', endpoint: process.env.SEAWEEDFS_ENDPOINT, forcePathStyle: true, credentials: { accessKeyId: process.env.SEAWEEDFS_ACCESS_KEY!, secretAccessKey: process.env.SEAWEEDFS_SECRET_KEY!, }, }) const BUCKET = process.env.SEAWEEDFS_BUCKET! app.post('/presign/seaweedfs', async (req, res) => { const { path, op, opts } = req.body const key = path.replace(/^\/+/, '') const ttl = typeof opts?.ttlSec === 'number' ? opts.ttlSec : 300 let cmd switch (op) { case 'GET': cmd = new GetObjectCommand({ Bucket: BUCKET, Key: key }); break case 'PUT': cmd = new PutObjectCommand({ Bucket: BUCKET, Key: key, ContentType: opts?.contentType }); break case 'HEAD': cmd = new HeadObjectCommand({ Bucket: BUCKET, Key: key }); break case 'DELETE': cmd = new DeleteObjectCommand({ Bucket: BUCKET, Key: key }); break case 'LIST': cmd = new ListObjectsV2Command({ Bucket: BUCKET, Prefix: opts?.listPrefix, Delimiter: opts?.listDelimiter, ContinuationToken: opts?.listContinuationToken, }); break case 'COPY': cmd = new CopyObjectCommand({ Bucket: BUCKET, Key: key, CopySource: `${BUCKET}/${opts?.copySource}`, }); break } res.json({ url: await getSignedUrl(client, cmd, { expiresIn: ttl }) }) }) ``` > [!WARNING] > > SeaweedFS uses **path-style** URLs (`forcePathStyle: true`), virtual-hosted style requires extra DNS setup on a self-hosted gateway. ### 2. Browser: wire it up ```ts theme={null} import { SeaweedFSVFS, MountMode, Workspace } from '@struktoai/mirage-browser' const seaweedfs = new SeaweedFSVFS({ bucket: 'my-bucket', endpoint: 'http://localhost:8333', presignedUrlProvider: async (path, op, opts) => { const r = await fetch('/presign/seaweedfs', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path, op, opts }), }) const { url } = await r.json() return url }, }) const ws = new Workspace({ '/bucket/': seaweedfs }, { mode: MountMode.READ }) ``` > [!TIP] > > `endpoint` on the browser config is only used for display/logging; the actual endpoint is baked into the presigned URLs your backend returns. See the [SeaweedFS VFS](/python/vfs/seaweedfs) docs for the equivalent Python wiring. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with SeaweedFS mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Integration What SeaweedFS answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On SeaweedFS | | - | - | | `find`, `du`, `ls -R`, `tree` | One recursive listing | # SharePoint Source: https://docs.mirage.strukto.ai/typescript/setup/sharepoint Mount SharePoint sites and document libraries through Microsoft Graph from Node or the browser. `SharePointVFS` shares its file-operation backend with OneDrive. Its additional resolver maps SharePoint sites and document libraries onto the virtual tree. ```ts theme={null} import { MountMode, SharePointVFS, Workspace } from '@struktoai/mirage-node' const sharepoint = new SharePointVFS({ accessToken: () => getMicrosoftGraphToken(), tenantHost: 'contoso.sharepoint.com', }) const ws = new Workspace({ '/sharepoint': sharepoint }, { mode: MountMode.WRITE }) await ws.shell('ls /sharepoint/') await ws.shell('ls /sharepoint/Engineering/Documents/') ``` An unscoped mount uses `/site/library/path`. To hide the site and library levels, configure `site` and `drive` together; `keyPrefix` can narrow that drive further. ```ts theme={null} new SharePointVFS({ accessToken, site: 'Engineering', drive: 'Documents', keyPrefix: 'Reports/2026', }) ``` | Field | Description | | - | - | | `accessToken` required, secret | Microsoft Graph bearer token, or a function (sync or async) that returns one; it is called for each request and again after a `401`. | | `tenantHost` | SharePoint host, such as `contoso.sharepoint.com`; the `sharepoint` mount lists only the sites whose `webUrl` is on it. The `onedrive` mount ignores it. | | `graphBaseUrl` | Full Graph service root, version segment included, for any deployment but the worldwide one: a sovereign cloud, a private endpoint or a test server. Unset uses `https://graph.microsoft.com/v1.0`. | | `timeout` default `DEFAULT_TIMEOUT` | Seconds a Graph request may wait to connect, or between two reads of its answer, before it fails; also how long a server-side copy is polled before it fails as unconfirmed. | | `maxRetries` default `5` | Times a request is retried after a `429`, `503` or `504` response. Each retry waits what `Retry-After` asks or an exponential backoff, at most 30 seconds. | | `siteFilter` default `'*'` | Search term passed to Graph's `/sites?search=` to choose which sites the mount lists. | | `site` | Site, by display name or internal name, that scopes the mount to one document library together with `drive`. With either unset the mount lists every site as `/<site>/<library>/...`. | | `drive` | Document library in `site` that the mount uses as its root; takes effect only with `site` set. | | `keyPrefix` | Folder path inside the scoped library that the mount uses as its root; takes effect only with `site` and `drive` set. `..` segments are rejected. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with SharePoint mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `sharepoint`, write | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > <site>/ # every SharePoint site you can reach > <library>/ # its document libraries (drives) > <path> # the drive's files and folders > ``` > > * SharePoint document libraries, discovered across sites and drives. An > unscoped mount reads `/{site_name}/{library_name}/{path_to_file}`: > `ls /` lists the sites, `ls /site/` a site's libraries, and > `ls /site/lib/...` a drive's files and folders. > * This is a remote mount: prefer targeted reads (`grep`, `head`) over > full scans, and pipe a large file to `head` or `tail` rather than > `cat` it whole. > * File versions are retained; a snapshot pins and reads prior > versions. > > #### 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 `sharepoint` 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>` | `sharepoint`, write | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > <site>/ # every SharePoint site you can reach > <library>/ # its document libraries (drives) > <path> # the drive's files and folders > ``` > > - SharePoint document libraries, discovered across sites and drives. An > unscoped mount reads `/{site_name}/{library_name}/{path_to_file}`: > `ls /` lists the sites, `ls /site/` a site's libraries, and > `ls /site/lib/...` a drive's files and folders. > - This is a remote mount: prefer targeted reads (`grep`, `head`) over > full scans, and pipe a large file to `head` or `tail` rather than > `cat` it whole. > - File versions are retained; a snapshot pins and reads prior > versions. > > ## 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 `sharepoint` 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. > ```` ## Integration What SharePoint answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On SharePoint | | - | - | | `grep -r`, `rg` | Microsoft Graph search within one document library, for whole words. It can miss Office files, PDFs, archives, the end of large files, words Graph splits differently (`foo.bar`) and recent writes. | | `find`, `du`, `ls -R`, `tree` | One recursive listing | The [Python SharePoint docs](/python/vfs/sharepoint#integration) list when each search answers and what it can miss. # Slack Source: https://docs.mirage.strukto.ai/typescript/setup/slack Mount a Slack workspace as a virtual filesystem from Node or the browser. MIRAGE ships `SlackVFS` in **two runtimes**: * `@struktoai/mirage-node`, talks to `https://slack.com/api/*` directly using a bot token (and optionally a user token for `search.messages`). * `@struktoai/mirage-browser`, stays secret-free: a small proxy server on your backend holds the token and forwards `/api/slack/*` to `https://slack.com/api/*`. The browser only ever sees the proxy URL. Both runtimes expose the same filesystem shape (`/slack/channels/`, `/slack/dms/`, `/slack/users/`) and the same shell commands, and both pair with the [slack CLI](/typescript/cli/slack) for acting on the workspace. ## Get a bot token 1. Visit the [Slack API basics page](https://api.slack.com/authentication/basics) and create an app for your workspace. 2. Under **OAuth & Permissions**, add the bot scopes you need. For read access: * `channels:history`, `channels:read` * `groups:history`, `groups:read` (optional, private channels) * `im:history`, `im:read` (optional, direct messages) * `mpim:history`, `mpim:read` (optional, group direct messages) * `users:read` 3. For the CLI `send-message` command, also add `chat:write`. The mount never posts. 4. For [`search.messages`](https://api.slack.com/methods/search.messages), Slack requires a **user token** (`xoxp-…`) with `search:read`. Bot tokens (`xoxb-…`) get `not_allowed_token_type`. Provide it via the optional `searchToken` field. 5. Install the app to your workspace and copy the **Bot User OAuth Token** (`xoxb-…`). ```bash theme={null} # .env.development SLACK_BOT_TOKEN=xoxb-... SLACK_USER_TOKEN=xoxp-... # optional, only needed for slack search ``` ## Node (server-side) ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { MountMode, SlackVFS, Workspace } from '@struktoai/mirage-node' const slack = new SlackVFS({ token: process.env.SLACK_BOT_TOKEN!, searchToken: process.env.SLACK_USER_TOKEN, // optional }) const ws = new Workspace({ '/slack': slack }, { mode: MountMode.READ }) const res = await ws.shell('ls /slack/channels/') console.log(res.stdoutText) ``` ### Config | Field | Description | | - | - | | `timeout` 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. | | `token` required, secret | Slack token every API call sends: a bot token (`xoxb-`) or a user token (`xoxp-`). | | `searchToken` secret | User token (`xoxp-`) with `search:read`, used only for Slack's `search.*` methods, which refuse a bot token. Unset searches with `token`. | | `baseUrl` default `'https://slack.com/api'` | Slack Web API root; override to point at a fake or proxy. | | `startTime` | Start of the mount's time scope, inclusive: an RFC 3339 timestamp with an explicit timezone and at most millisecond precision. Unset leaves the start open. | | `endTime` | End of the mount's time scope, exclusive, in the same format as `startTime`, which it must follow. Unset leaves the end open. | Fields marked secret are redacted in snapshots. ## Browser ```bash theme={null} pnpm add @struktoai/mirage-browser ``` The browser package never sees the bot token. Instead, point it at a relative URL that your backend proxies to `https://slack.com/api/*`, attaching the `Authorization: Bearer …` header server-side. ### Config | Field | Description | | - | - | | `timeout` 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. | | `startTime` | Start of the mount's time scope, inclusive: an RFC 3339 timestamp with an explicit timezone and at most millisecond precision. Unset leaves the start open. | | `endTime` | End of the mount's time scope, exclusive, in the same format as `startTime`, which it must follow. Unset leaves the end open. | | `proxyUrl` required | URL of your backend proxy, which forwards to `https://slack.com/api` and attaches the token. A path resolves against the page's origin; no query string or fragment. | | `getHeaders` secret | Function returning extra headers sent with every request to the proxy, such as your own session credential. | Fields marked secret are redacted in snapshots. ### 1. Server: minimal proxy ```ts theme={null} import { createServer } from 'node:http' const TOKEN = process.env.SLACK_BOT_TOKEN! const PREFIX = '/api/slack/' createServer(async (req, res) => { const url = new URL(req.url ?? '/', 'http://localhost') if (!url.pathname.startsWith(PREFIX)) { res.statusCode = 404 res.end() return } const upstream = new URL(`https://slack.com/api/${url.pathname.slice(PREFIX.length)}`) upstream.search = url.search const method = (req.method ?? 'GET').toUpperCase() const chunks: Buffer[] = [] if (method !== 'GET' && method !== 'HEAD') { for await (const chunk of req) chunks.push(chunk as Buffer) } const body = chunks.length > 0 ? Buffer.concat(chunks).toString('utf-8') : undefined const headers: Record<string, string> = { Authorization: `Bearer ${TOKEN}` } const ct = req.headers['content-type'] if (typeof ct === 'string') headers['content-type'] = ct const upstreamRes = await fetch(upstream, { method, headers, ...(body !== undefined ? { body } : {}) }) const text = await upstreamRes.text() res.statusCode = upstreamRes.status const upstreamCt = upstreamRes.headers.get('content-type') if (upstreamCt !== null) res.setHeader('content-type', upstreamCt) res.end(text) }).listen(8901, '127.0.0.1') ``` ### 2. Browser: wire it up ```ts theme={null} import { MountMode, SlackVFS, Workspace } from '@struktoai/mirage-browser' const slack = new SlackVFS({ proxyUrl: '/api/slack', // For multi-tenant setups, return per-request auth headers: // getHeaders: async () => ({ Authorization: `Bearer ${userJwt}` }), }) const ws = new Workspace({ '/slack': slack }, { mode: MountMode.READ }) const res = await ws.shell('ls /slack/channels/') console.log(res.stdoutText) ``` > [!WARNING] > > Calling `https://slack.com/api/*` directly from a browser fails CORS. The proxy is mandatory, Slack does not set permissive CORS headers. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Slack mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `slack`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > channels/ > <channel-name>__<channel-id>/ > <yyyy-mm-dd>/ > chat.jsonl # messages for that date > files/ # attachments shared that day > <name>__<F-id>.<ext> # cat downloads the bytes > dms/ > <user-name>__<dm-id>/ > <yyyy-mm-dd>/ > chat.jsonl > files/ > <name>__<F-id>.<ext> > users/ > <username>__<user-id>.json # user profile > ``` > > * A channel, DM or user name is `<display-name>__<id>`. The display name > keeps Slack's spelling; only `/` becomes `∕` (U+2215). `ls` the parent > first to find exact names, and quote a name that has spaces. > * Messages are JSONL; use `jq` for fields such as `.text`, `.user`, > `.ts` and `.files`. A day's `files/` may be empty. > * `.user` is a user ID (`U…`), not a username; resolve it through > `users/<username>__<user-id>.json` and filter messages by the ID. > * Without `start_time`/`end_time`, a channel lists the latest 90 days up > to its newest message; a date glob finds earlier days. > * With `start_time`/`end_time`, listings cover that scope; messages and > attachments outside it are absent, direct paths included, and `grep` > and `rg` see only the in-scope files. Users and channel metadata stay > available as context. > * Unless `walk_limit` is -1, `grep -rw` and `rg -w` read only the channel > and DM days Slack search names; attachments under `files/` are always > read. > > Time scope: `start_time=unbounded` (inclusive), `end_time=unbounded` (exclusive). Explicit paths and globs cannot escape this scope. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` with `-w` ask `slack` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. Without `-w`, `grep -r` and `rg` read every file. `slack` answers only for `channels/*/*/chat.jsonl` and `dms/*/*/chat.jsonl`; `grep -r` and `rg` read every other 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>` | `slack`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > channels/ > <channel-name>__<channel-id>/ > <yyyy-mm-dd>/ > chat.jsonl # messages for that date > files/ # attachments shared that day > <name>__<F-id>.<ext> # cat downloads the bytes > dms/ > <user-name>__<dm-id>/ > <yyyy-mm-dd>/ > chat.jsonl > files/ > <name>__<F-id>.<ext> > users/ > <username>__<user-id>.json # user profile > ``` > > - A channel, DM or user name is `<display-name>__<id>`. The display name > keeps Slack's spelling; only `/` becomes `∕` (U+2215). `ls` the parent > first to find exact names, and quote a name that has spaces. > - Messages are JSONL; use `jq` for fields such as `.text`, `.user`, > `.ts` and `.files`. A day's `files/` may be empty. > - `.user` is a user ID (`U…`), not a username; resolve it through > `users/<username>__<user-id>.json` and filter messages by the ID. > - Without `start_time`/`end_time`, a channel lists the latest 90 days up > to its newest message; a date glob finds earlier days. > - With `start_time`/`end_time`, listings cover that scope; messages and > attachments outside it are absent, direct paths included, and `grep` > and `rg` see only the in-scope files. Users and channel metadata stay > available as context. > - Unless `walk_limit` is -1, `grep -rw` and `rg -w` read only the channel > and DM days Slack search names; attachments under `files/` are always > read. > > Time scope: `start_time=unbounded` (inclusive), `end_time=unbounded` (exclusive). Explicit paths and globs cannot escape this scope. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` with `-w` ask `slack` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. Without `-w`, `grep -r` and `rg` read every file. `slack` answers only for `channels/*/*/chat.jsonl` and `dms/*/*/chat.jsonl`; `grep -r` and `rg` read every other 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. > ```` Each channel or DM directory contains day-partitioned directories for the last 90 days (or since channel creation). Each date directory contains `chat.jsonl` plus a `files/` directory for attachments shared that day. Each user file is the full profile JSON returned by `users.profile.get`. The Slack ID is embedded after `__` in directory and file names so you can extract it for the VFS-specific commands without an extra lookup. ## Shell commands Every standard MIRAGE shell command works on the mounted Slack tree: | Command | Notes | | - | - | | `ls` | List channels, DMs, users, dates | | `cat` | Read `chat.jsonl`, user `.json`, or files | | `head` / `tail` | First/last N lines | | `grep` / `rg` | Pattern search (file or directory level) | | `jq` | Query JSON, once per JSONL line (`-s` all) | | `wc` | Line/word/byte counts | | `stat` | File metadata (name, size, type) | | `find` | Recursive search with `-name`, `-maxdepth` | | `tree` | Directory tree view | | `pwd` / `cd` | Navigate the virtual tree | | `echo` (glob) | Glob expansion via the derived `glob` op | Acting on Slack (sending, reacting, pins, member info, search) goes through the [slack CLI](/typescript/cli/slack) when installed; the mounted tree stays read-oriented. ## Integration What Slack answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Slack | | - | - | | `grep -r`, `rg` | Slack search, for whole words, with a user token. It can miss recent messages, words only in other fields (bot names and link previews). | | `tail -f` | Each new message as it is posted | The [Python Slack docs](/python/vfs/slack#integration) list when each search answers and what it can miss. ## Troubleshooting > [accordion] `not_allowed_token_type` on `slack search` > > The account CLI's `slack search` command calls `search.messages`, which requires a **user token** (`xoxp-…`) with `search:read` scope. Include `searchToken` in the config passed to `ws.registerCli`; see the [Slack CLI setup](/typescript/cli/slack). Without it, `slack search` fails. VFS `grep` and `rg` still scan the mounted files; they simply skip the optional Slack-search optimization. > [accordion] CORS error in browser > > The browser cannot call `https://slack.com/api/*` directly, Slack does not set permissive CORS headers. You must run the proxy server shown above (or your own equivalent) and point `proxyUrl` at it. > [accordion] `rate_limited` from Slack > > `SlackVFS` uses an `IndexCacheStore` (default TTL 600s) to deduplicate channel / user / date listings, but high-volume reads of `.jsonl` files can still hit Slack's per-method rate limits. Cache hits avoid the API entirely; raise the index `ttl` (`index: { ttl }`) together with the mount's `ttl` if your workspace changes slowly. > > History limits depend on app distribution. Check Slack's current > [`conversations.history` method limits](https://docs.slack.dev/reference/methods/conversations.history/) > for your installation. ## Examples * [`examples/typescript/vfs/slack/slack.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/vfs/slack/slack.ts), shell commands against `/slack/` (`ls`, `cat`, `grep`, `jq`, `tree`, `find`, `cd`, glob). * [`examples/typescript/vfs/slack/slack_vfs.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/vfs/slack/slack_vfs.ts), `patchNodeFs(ws)` so native `node:fs` calls route through the workspace. * [`examples/typescript/vfs/slack/slack_fuse.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/vfs/slack/slack_fuse.ts), FUSE-mount the workspace so external processes can browse `/slack/` as a real filesystem. * [`examples/browser/vfs/slack/`](https://github.com/strukto-ai/mirage/tree/main/examples/browser/vfs/slack), proxy server + `@struktoai/mirage-browser` SlackVFS demo. See [Python Slack VFS](/python/vfs/slack) for the equivalent Python wiring. ## Time scope Set `start_time` and/or `end_time` in the mount's YAML `config` (or pass `start_time`/`end_time` to Python; `startTime`/`endTime` to the TypeScript constructor). Bounds are RFC3339 timestamps with an explicit timezone and at most millisecond precision. Start is inclusive; end is exclusive. An omitted or null bound is open. Start must precede end. ```yaml theme={null} mounts: /history: vfs: slack mode: read config: token: "<bot-token>" start_time: "2026-06-01T10:00:00Z" end_time: "2026-06-02T00:00:00Z" ``` With a bound configured, channel listings cover the selected period rather than the default recent window. Day directories use UTC. Messages are selected by creation time, and attachments follow their parent messages. Direct paths, `stat`, date globs, and `grep`/`rg` cannot escape the scope: a search only rules out files, so scoped searches scan the filtered files. User/member and channel/server metadata remain visible as context. These settings apply to the VFS, not to separately installed account CLIs. `mode: read` prevents mount writes; it does not freeze upstream edits or deletions. Rebuild/remount the VFS to change its scope so cached listings and bytes are cleared. # SQL Source: https://docs.mirage.strukto.ai/typescript/setup/sql Keep a Mirage filesystem in SQL tables. `SqlVFS` keeps a filesystem in a database's tables: a SQLite file, a Postgres server, a Durable Object's storage or a D1 database. ## Install ```bash theme={null} pnpm add @struktoai/mirage-node ``` ## Config ```ts theme={null} import { MountMode, SqlVFS, Workspace } from '@struktoai/mirage-node' const sql = new SqlVFS({ path: './workspace.db' }) const ws = new Workspace({ '/sql': sql }, { mode: MountMode.WRITE }) await ws.shell('echo "hello" | tee /sql/greet') await ws.shell('cat /sql/greet') ``` | Field | Default | Notes | | - | - | - | | `path` | `:memory:` | The SQLite file, opened and closed with the mount. | | `driver` | none | A database to borrow instead of a file; you close it. | | `capacity` | none | The most bytes the files may hold, like `100MB`. | To mount Postgres, install `pg` and pass its driver: ```ts theme={null} import { PostgresSqlDriver, SqlVFS } from '@struktoai/mirage-node' const driver = new PostgresSqlDriver('postgres://user:pass@localhost:5432/app') const sql = new SqlVFS({ driver }) ``` The tables are laid out as [AgentFS](https://github.com/tursodatabase/agentfs)'s: * `fs_inode`: one row per file and directory, with its size and mtime * `fs_dentry`: each entry's name under its parent directory * `fs_data`: a file's bytes, in rows of the database's chunk size (4 KiB unless the database says otherwise) * `fs_config`: the chunk size One database holds one filesystem. The Python mount reads and writes the same tables, so the two runtimes on one file serve one filesystem. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with SQL mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` # SSH Source: https://docs.mirage.strukto.ai/typescript/setup/ssh Mount a remote SSH host as a Mirage filesystem (Node only). `SSHVFS` opens an SFTP session and mounts the remote root as a filesystem. > [!NOTE] > > Node only. Requires the `ssh2` peer dependency. The browser SDK doesn't ship an SSH client. ## Install ```bash theme={null} pnpm add @struktoai/mirage-node ssh2 ``` ## Config ```ts theme={null} import { MountMode, SSHVFS, Workspace } from '@struktoai/mirage-node' const ssh = new SSHVFS({ host: 'jump.example.com', username: 'me', identityFile: '~/.ssh/id_ed25519', root: '/srv/data', }) const ws = new Workspace({ '/remote': ssh }, { mode: MountMode.READ }) await ws.shell('ls /remote') ``` | Field | Description | | - | - | | `host` required | DNS name or IP address of the remote. | | `hostname` | Address to connect to instead of `host`. | | `port` default `22` | SSH port. | | `username` | Login user; unset uses the local user name. | | `password` secret | Password for password authentication; prefer `identityFile`. | | `identityFile` | Path to a private key; `~` is expanded. Unset tries the SSH agent and the default keys in `~/.ssh` (`id_ed25519`, `id_ecdsa`, `id_rsa`, `id_dsa`). | | `privateKey` secret | A private key's own text, such as one a credential pointer reads from a secret store; offered after `identityFile`'s. | | `passphrase` secret | Passphrase of an encrypted private key, from `identityFile`, `privateKey` or a default key. | | `root` default `'/'` | Path on the remote that becomes the mount root. | | `timeout` default `30` | Seconds to wait for the connection to be ready, authentication included. | | `knownHosts` | Accepted but not applied: this backend does not verify host keys. | Fields marked secret are redacted in snapshots. ## Mount mode `read`, `write`, `exec`. Writes flush via SFTP put. Use `MountMode.EXEC` if `python3` or `js` should run scripts from the mount. For the full set of supported shell commands see the [Python SSH docs](/python/vfs/ssh). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with SSH mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `ssh`, write | > > #### 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` ask `ssh` which files may match. `wc -l` asks `ssh` instead of reading a file. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | `ssh`, write | > > ## 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` ask `ssh` which files may match. `wc -l` asks `ssh` instead of reading a file. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Integration What SSH answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On SSH | | - | - | | `grep -r`, `rg` | `grep` on the server, for any text. It misses nothing. | | `wc -l` | `wc -l` on the server | | `tail -f` | `tail -f` on the server | | `md5sum`, `sha256sum` and the other hash commands | The matching sum tool on the server | | `find`, `du`, `ls -R`, `tree` | One `find` on the server | The [Python SSH docs](/python/vfs/ssh#integration) list when each search answers and what it can miss. # Supabase Storage Source: https://docs.mirage.strukto.ai/typescript/setup/supabase Set up Supabase Storage as a MIRAGE VFS from Node or the browser. Supabase Storage exposes an S3-compatible API at `https://<project-ref>.storage.supabase.co/storage/v1/s3`, signed with AWS Signature V4 using Supabase **S3 Access Keys** (not your project anon / service-role JWT). MIRAGE derives the endpoint from your `project_ref` automatically and forces path-style URLs. ## Credentials ### 1. Create an S3 access key 1. Open the Supabase dashboard → your project → **Storage → Settings → S3 Access Keys** 2. Click **New access key**, scope to the bucket(s) you want MIRAGE to see 3. Copy the **Access key ID** and **Secret access key**, the secret is shown once ### 2. Environment variables ```bash theme={null} # .env.development SUPABASE_BUCKET=my-bucket SUPABASE_REGION=us-east-1 SUPABASE_PROJECT_REF=abcdefghijklmnop SUPABASE_ACCESS_KEY_ID=... SUPABASE_SECRET_ACCESS_KEY=... ``` > [!TIP] > > `SUPABASE_REGION` is metadata only, Supabase Storage accepts any region string but requires one for SigV4 signing. Use the region you selected when creating the project. ## Node (server-side) ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { MountMode, SupabaseVFS, Workspace } from '@struktoai/mirage-node' const sb = new SupabaseVFS({ bucket: process.env.SUPABASE_BUCKET!, region: process.env.SUPABASE_REGION!, projectRef: process.env.SUPABASE_PROJECT_REF!, accessKeyId: process.env.SUPABASE_ACCESS_KEY_ID!, secretAccessKey: process.env.SUPABASE_SECRET_ACCESS_KEY!, }) const ws = new Workspace({ '/bucket/': sb }, { mode: MountMode.READ }) const res = await ws.shell('ls /bucket/') console.log(res.stdoutText) ``` ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `accessKeyId` secret | Access key ID; set it with `secretAccessKey`. Unset uses the AWS SDK credential chain. | | `secretAccessKey` secret | Secret access key paired with `accessKeyId`. | | `sessionToken` secret | Session token for temporary credentials, sent with the access key pair. | | `profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `forcePathStyle` default `true` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `keyPrefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `timeout` 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. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | | `region` required | Provider region every request is signed for. Most providers also build their endpoint URL from it unless `endpoint` is set. | | `endpoint` | Endpoint URL that replaces the one the provider derives. | | `projectRef` | Supabase project reference. It builds the endpoint `https://<projectRef>.storage.supabase.co/storage/v1/s3` unless `endpoint` is set; one of the two is required. | Fields marked secret are redacted in snapshots. ## Browser (presigned URLs) ```bash theme={null} pnpm add @struktoai/mirage-browser ``` Same pattern as every other S3-compat backend: the browser calls a `presignedUrlProvider` callback that hits your server, which signs each S3 operation against the Supabase endpoint and returns the URL. The browser `fetch()`es directly. ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `presignedUrlProvider` required, secret | Function `(path, operation, options)` that returns a signed URL for each S3 operation; your server signs it, so the browser holds no keys. | | `region` | Region of the bucket. Most providers derive the endpoint from it; requests go to the host each presigned URL names. | | `endpoint` | Endpoint URL that replaces the one the provider derives. Requests go to the host each presigned URL names; the mount uses it to name its storage location. | | `defaultContentType` default `'application/octet-stream'` | `Content-Type` stored with every object the mount writes. | | `keyPrefix` | Key prefix the mount treats as its root. The browser can change it before a URL is signed, so enforce the prefix on the signing server. | | `timeout` 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. | | `projectRef` | Supabase project reference. It builds the endpoint `https://<projectRef>.storage.supabase.co/storage/v1/s3` unless `endpoint` is set. | Fields marked secret are redacted in snapshots. ### 1. Server: sign URLs with the Supabase endpoint ```ts theme={null} import { CopyObjectCommand, DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client, } from '@aws-sdk/client-s3' import { getSignedUrl } from '@aws-sdk/s3-request-presigner' const PROJECT_REF = process.env.SUPABASE_PROJECT_REF! const REGION = process.env.SUPABASE_REGION! const client = new S3Client({ region: REGION, endpoint: `https://${PROJECT_REF}.storage.supabase.co/storage/v1/s3`, forcePathStyle: true, credentials: { accessKeyId: process.env.SUPABASE_ACCESS_KEY_ID!, secretAccessKey: process.env.SUPABASE_SECRET_ACCESS_KEY!, }, }) const BUCKET = process.env.SUPABASE_BUCKET! app.post('/presign/supabase', async (req, res) => { const { path, op, opts } = req.body const key = path.replace(/^\/+/, '') const ttl = typeof opts?.ttlSec === 'number' ? opts.ttlSec : 300 let cmd switch (op) { case 'GET': cmd = new GetObjectCommand({ Bucket: BUCKET, Key: key }); break case 'PUT': cmd = new PutObjectCommand({ Bucket: BUCKET, Key: key, ContentType: opts?.contentType }); break case 'HEAD': cmd = new HeadObjectCommand({ Bucket: BUCKET, Key: key }); break case 'DELETE': cmd = new DeleteObjectCommand({ Bucket: BUCKET, Key: key }); break case 'LIST': cmd = new ListObjectsV2Command({ Bucket: BUCKET, Prefix: opts?.listPrefix, Delimiter: opts?.listDelimiter, ContinuationToken: opts?.listContinuationToken, }); break case 'COPY': cmd = new CopyObjectCommand({ Bucket: BUCKET, Key: key, CopySource: `${BUCKET}/${opts?.copySource}`, }); break } res.json({ url: await getSignedUrl(client, cmd, { expiresIn: ttl }) }) }) ``` > [!WARNING] > > Supabase requires **path-style** URLs (`forcePathStyle: true`). Virtual-hosted style is not supported. ### 2. Browser: wire it up ```ts theme={null} import { MountMode, SupabaseVFS, Workspace } from '@struktoai/mirage-browser' const sb = new SupabaseVFS({ bucket: 'my-bucket', projectRef: 'abcdefghijklmnop', presignedUrlProvider: async (path, op, opts) => { const r = await fetch('/presign/supabase', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path, op, opts }), }) const { url } = await r.json() return url }, }) const ws = new Workspace({ '/bucket/': sb }, { mode: MountMode.READ }) ``` ### 3. Configure CORS on the bucket Supabase Storage's S3 API respects the bucket's CORS configuration, which is set in the Supabase dashboard: 1. Project → **Storage → Settings → Policies / CORS configuration** 2. Add `http://localhost:5173` (and any production origins) 3. Methods: `GET, PUT, HEAD, DELETE, POST` 4. Headers: `*` 5. Exposed headers: `ETag, Content-Length, Content-Type, Last-Modified` See the [Supabase VFS](/python/vfs/supabase) docs for the equivalent Python wiring. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Supabase Storage mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Integration What Supabase Storage answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Supabase Storage | | - | - | | `find`, `du`, `ls -R`, `tree` | One recursive listing | # Tencent COS Source: https://docs.mirage.strukto.ai/typescript/setup/tencent Set up Tencent Cloud Object Storage as a MIRAGE VFS from Node or the browser. Tencent COS uses the S3 API with AWS Signature V4 against `https://cos.<region>.myqcloud.com`. MIRAGE derives this endpoint from your region automatically. COS bucket names include the APPID suffix (e.g. `my-bucket-1250000000`). Credentials (CAM `SecretId` as the access key and `SecretKey` as the secret) are created the same way in both runtimes, see [Tencent COS Credentials](/home/setup/tencent). ## Node (server-side) ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { MountMode, TencentVFS, Workspace } from '@struktoai/mirage-node' const cos = new TencentVFS({ bucket: process.env.COS_BUCKET!, region: process.env.COS_REGION!, accessKeyId: process.env.COS_SECRET_ID!, secretAccessKey: process.env.COS_SECRET_KEY!, }) const ws = new Workspace({ '/bucket/': cos }, { mode: MountMode.READ }) const res = await ws.shell('ls /bucket/') console.log(res.stdoutText) ``` ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `accessKeyId` secret | Access key ID; set it with `secretAccessKey`. Unset uses the AWS SDK credential chain. | | `secretAccessKey` secret | Secret access key paired with `accessKeyId`. | | `sessionToken` secret | Session token for temporary credentials, sent with the access key pair. | | `profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `forcePathStyle` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `keyPrefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `timeout` 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. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | | `region` required | Provider region every request is signed for. Most providers also build their endpoint URL from it unless `endpoint` is set. | | `endpoint` | Endpoint URL that replaces the one the provider derives. | Fields marked secret are redacted in snapshots. ## Browser (presigned URLs) ```bash theme={null} pnpm add @struktoai/mirage-browser ``` The browser `TencentVFS` is secret-free, your backend signs each operation using your CAM keys and returns a URL. COS accepts AWS Signature V4, so `@aws-sdk/s3-request-presigner` works, pointed at the COS endpoint. ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `presignedUrlProvider` required, secret | Function `(path, operation, options)` that returns a signed URL for each S3 operation; your server signs it, so the browser holds no keys. | | `region` | Region of the bucket. Most providers derive the endpoint from it; requests go to the host each presigned URL names. | | `endpoint` | Endpoint URL that replaces the one the provider derives. Requests go to the host each presigned URL names; the mount uses it to name its storage location. | | `defaultContentType` default `'application/octet-stream'` | `Content-Type` stored with every object the mount writes. | | `keyPrefix` | Key prefix the mount treats as its root. The browser can change it before a URL is signed, so enforce the prefix on the signing server. | | `timeout` 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. | Fields marked secret are redacted in snapshots. ### 1. Server: sign URLs with the COS endpoint ```ts theme={null} import { CopyObjectCommand, DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client, } from '@aws-sdk/client-s3' import { getSignedUrl } from '@aws-sdk/s3-request-presigner' const REGION = process.env.COS_REGION! const client = new S3Client({ region: REGION, endpoint: `https://cos.${REGION}.myqcloud.com`, credentials: { accessKeyId: process.env.COS_SECRET_ID!, secretAccessKey: process.env.COS_SECRET_KEY!, }, }) const BUCKET = process.env.COS_BUCKET! app.post('/presign/cos', async (req, res) => { const { path, op, opts } = req.body const key = path.replace(/^\/+/, '') const ttl = typeof opts?.ttlSec === 'number' ? opts.ttlSec : 300 let cmd switch (op) { case 'GET': cmd = new GetObjectCommand({ Bucket: BUCKET, Key: key }); break case 'PUT': cmd = new PutObjectCommand({ Bucket: BUCKET, Key: key, ContentType: opts?.contentType }); break case 'HEAD': cmd = new HeadObjectCommand({ Bucket: BUCKET, Key: key }); break case 'DELETE': cmd = new DeleteObjectCommand({ Bucket: BUCKET, Key: key }); break case 'LIST': cmd = new ListObjectsV2Command({ Bucket: BUCKET, Prefix: opts?.listPrefix, Delimiter: opts?.listDelimiter, ContinuationToken: opts?.listContinuationToken, }); break case 'COPY': cmd = new CopyObjectCommand({ Bucket: BUCKET, Key: key, CopySource: `${BUCKET}/${opts?.copySource}`, }); break } res.json({ url: await getSignedUrl(client, cmd, { expiresIn: ttl }) }) }) ``` ### 2. Browser: wire it up ```ts theme={null} import { MountMode, TencentVFS, Workspace } from '@struktoai/mirage-browser' const cos = new TencentVFS({ bucket: 'my-bucket-1250000000', region: 'ap-guangzhou', presignedUrlProvider: async (path, op, opts) => { const r = await fetch('/presign/cos', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path, op, opts }), }) const { url } = await r.json() return url }, }) const ws = new Workspace({ '/bucket/': cos }, { mode: MountMode.READ }) ``` > [!TIP] > > `region` on the browser config is only used for display/logging; the actual endpoint is baked into the presigned URLs your backend returns. ### 3. CORS Configure CORS rules in the Tencent Cloud console: COS -> your bucket -> **Security Management** -> **CORS**. Allow your dev/production origins with methods `GET, PUT, HEAD, DELETE, POST`, allowed headers `*`, and expose headers `ETag, Content-Length, Content-Type, Last-Modified`. See the [Tencent VFS](/python/vfs/tencent) docs for the equivalent Python wiring. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Tencent COS mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Integration What Tencent COS answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Tencent COS | | - | - | | `find`, `du`, `ls -R`, `tree` | One recursive listing | # TiDB Cloud Filesystem Source: https://docs.mirage.strukto.ai/typescript/setup/tidb_filesystem Mount a TiDB Cloud Filesystem, or a self-hosted drive9 server, as a MIRAGE VFS from Node. `TiDBFilesystemVFS` mounts a [TiDB Cloud Filesystem](https://www.pingcap.com/tidb/tidb-cloud-filesystem/) through its REST API. Agents list, read, write, move and remove files under the mount with ordinary shell commands, and no FUSE mount is needed. MIRAGE ships it in `@struktoai/mirage-node`. For tokens and regions, see [TiDB Cloud Filesystem Setup](/home/setup/tidb). ## Node ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { buildVfs, MountMode, Workspace } from '@struktoai/mirage-node' const vfs = await buildVfs('tidb_filesystem', { host: process.env.TIDB_FILESYSTEM_HOST, token: process.env.TIDB_FILESYSTEM_TOKEN, root_path: '/workspace', }) const ws = new Workspace({ '/fs': vfs }, { mode: MountMode.WRITE }) const res = await ws.shell('mkdir -p /fs/notes && echo hello > /fs/notes/a.txt && ls /fs/notes') console.log(res.stdoutText) ``` | Field | Description | | - | - | | `timeout` 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. | | `host` required | The file system's endpoint, such as `https://aws-us-east-1.drive9.ai` for its region, or the origin of a self-hosted drive9 server. | | `token` required, secret | The file system token, sent as a bearer token. | | `rootPath` default `'/'` | Directory inside the file system that becomes the mount root, such as `/projects/a` for a token scoped to it; `..` segments are refused. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with TiDB Cloud Filesystem mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Behavior * A file under 50,000 bytes is written with one request; a larger one goes up in parts, a few at a time, and reads of it stream from object storage, ranged when a command reads only part of it. * `>>` onto a file of 50,000 bytes or more sends only the new bytes and the file's last part; a smaller file is read and written back. * `mv` is one server-side rename, for a file or a whole directory. `rm -r` is one recursive delete. * `cp` reads the file and writes the copy, so the two never share content. * Before a write, `mkdir` or `mv`, Mirage asks the file system what the destination and its parents are, so a missing parent, a file in the way or a directory target fails as it does on a local disk. * A file in the extent layout, which only the file system's FUSE client writes and reads, reads as `Operation not supported`. See `examples/typescript/vfs/tidb_filesystem/tidb_filesystem.ts`. # Trello Source: https://docs.mirage.strukto.ai/typescript/setup/trello Mount Trello boards, lists, and cards as a Mirage filesystem. `TrelloVFS` exposes a Trello workspace as a tree of boards, lists, and cards. Setup steps for the API key/token live at [Trello Credentials](/home/setup/trello). ## Node ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { MountMode, TrelloVFS, Workspace } from '@struktoai/mirage-node' const trello = new TrelloVFS({ apiKey: process.env.TRELLO_API_KEY!, apiToken: process.env.TRELLO_API_TOKEN!, }) const ws = new Workspace({ '/trello': trello }, { mode: MountMode.READ }) await ws.shell('ls /trello/') ``` ## Browser ```bash theme={null} pnpm add @struktoai/mirage-browser ``` ```ts theme={null} import { MountMode, TrelloVFS, Workspace } from '@struktoai/mirage-browser' const trello = new TrelloVFS({ apiKey: TRELLO_API_KEY, apiToken: TRELLO_API_TOKEN, }) ``` ## Config | Field | Description | | - | - | | `timeout` 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. | | `apiKey` required, secret | Trello API key. | | `apiToken` required, secret | Trello API token. | | `workspaceId` | Only this workspace and its boards are listed or readable. Unset shows every workspace of the token's member. | | `boardIds` | Only these boards are listed or readable. Unset shows every open board of the shown workspaces. | | `baseUrl` default `'https://api.trello.com/1'` | Trello API root; override to point at a fake or proxy. | Fields marked secret are redacted in snapshots. ## Mount mode `read`. For board/list/card layout see the [Python Trello docs](/python/vfs/trello). Reads and writes by ID go through the [trello CLI](/typescript/cli/trello), which takes `workspaceId` and `boardIds` in its own config. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Trello mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `trello`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > workspaces/ > <workspace-name>__<workspace-id>/ > workspace.json > boards/ > <board-name>__<board-id>/ > board.json > members/ > <full-name>__<member-id>.json > labels/ > <label-name>__<label-id>.json > lists/ > <list-name>__<list-id>/ > list.json > cards/ > <card-name>__<card-id>/ > card.json > comments.jsonl > ``` > > * `ls` directories first to discover exact names. > * To act on boards and cards (list boards, members, lists, labels, cards > and comments; create, update, move, assign, label and comment on > cards), use the `trello` CLI if installed (`trello --help`). > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` with `-w` ask `trello` which files may match. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. Without `-w`, `grep -r` and `rg` read every file. `trello` answers only for `workspaces/*/boards/*/lists/*/cards/*/card.json`; `grep -r` and `rg` read every other 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>` | `trello`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > workspaces/ > <workspace-name>__<workspace-id>/ > workspace.json > boards/ > <board-name>__<board-id>/ > board.json > members/ > <full-name>__<member-id>.json > labels/ > <label-name>__<label-id>.json > lists/ > <list-name>__<list-id>/ > list.json > cards/ > <card-name>__<card-id>/ > card.json > comments.jsonl > ``` > > - `ls` directories first to discover exact names. > - To act on boards and cards (list boards, members, lists, labels, cards > and comments; create, update, move, assign, label and comment on > cards), use the `trello` CLI if installed (`trello --help`). > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep -r` and `rg` with `-w` ask `trello` which files may match. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. Without `-w`, `grep -r` and `rg` read every file. `trello` answers only for `workspaces/*/boards/*/lists/*/cards/*/card.json`; `grep -r` and `rg` read every other 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. > ```` ## Integration What Trello answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Trello | | - | - | | `grep -r`, `rg` | Trello search and the text the listing keeps, for whole words. It can miss recent writes. | The [Python Trello docs](/python/vfs/trello#integration) list when each search answers and what it can miss. # Upstash Redis Source: https://docs.mirage.strukto.ai/typescript/setup/upstash Mount an Upstash Redis database from Node or from a browser page with one URL. [Upstash](https://upstash.com) serves a Redis database through two entry points: the Redis protocol over TLS on port 6379, and a [REST API](https://upstash.com/docs/redis/features/restapi) on the same host. `@struktoai/mirage-node` uses the first and `@struktoai/mirage-browser` the second, and one configuration covers both, because the token Upstash prints is also the database password. ## Config The Upstash console prints a `redis-cli` line for the database. Its URL is the whole configuration, in Node and in the browser alike. ```ts theme={null} import { MountMode, RedisVFS, Workspace } from '@struktoai/mirage-browser' // or: import { MountMode, RedisVFS, Workspace } from '@struktoai/mirage-node' const redis = new RedisVFS({ url: process.env.UPSTASH_REDIS_URL!, // rediss://default:<token>@<name>.upstash.io:6379 keyPrefix: 'mirage/', }) const ws = new Workspace({ '/r': redis }, { mode: MountMode.WRITE }) await ws.shell('echo "hello" | tee /r/greet') await ws.shell('cat /r/greet') ``` | Field | Default | Notes | | - | - | - | | `url` | required | The `rediss://` URL from the console, password included. Redacted in snapshots. | | `keyPrefix` | `mirage:fs:` | Prefix prepended to every key. | | `token` | from the URL | Browser only. Needed when `url` is the REST URL (`https://<name>.upstash.io`) instead of the redis one. | | `maxRequestBytes` | `8388608` | Browser only. Upstash caps a REST request at 10 MB; a larger file is written as one `SET` plus `APPEND`s of this size. | `process.env` in the browser snippet stands for however your bundler injects the value; the [page example](https://github.com/strukto-ai/mirage/blob/main/examples/browser/vfs/redis/redis.html) uses a Vite `define` fed from `UPSTASH_REDIS_URL` in `.env.development`. > [!WARNING] > > That `define` copies the whole URL, password included, into the served JavaScript, so the > page is a local demo for a trusted machine: run it from the dev server, do not build or host > it. Anyone who reads the token out of a bundle can call the REST API directly and reach every > key, whatever `keyPrefix` and mount mode the page used. A page for other people needs a > server-side proxy, or a credential scoped to what that page may touch. ## One database, both runtimes The browser store keeps every value byte-identical to what the Node mount writes: writes go out as raw request bodies and reads come back base64-encoded. A page over REST and a server over the Redis protocol can therefore share one database at the same time, and the [Node example](https://github.com/strukto-ai/mirage/blob/main/examples/browser/vfs/redis/main.ts) shows the two reading each other's files. Python reaches the same database with the same URL through its [`RedisVFS`](/python/vfs/redis). ## Tokens and billing * The console's read-only token cannot `SCAN`, which directory listings need, so mount with the full token. * The free and pay-as-you-go tiers bill per command, and one shell command is several Redis commands (a directory listing costs a few per entry). Worth knowing before pointing an agent at a metered database. ## Mount mode `read`, `write`, `exec`. # Overview Source: https://docs.mirage.strukto.ai/typescript/setup/vfs TypeScript VFS types you can mount in a Mirage workspace. VFS types are the storage systems and services you mount into a Mirage workspace. Open **Providers** in the sidebar to browse every TypeScript-supported backend by category. Each provider page covers the required configuration, mounted tree, and VFS-specific behavior. Provider setup spans local and browser filesystems, object stores, cloud drives, collaboration tools, databases, vector stores, and agent memory systems. To implement another backend, see [Adding a New VFS](/typescript/vfs/new). # Weights & Biases Source: https://docs.mirage.strukto.ai/typescript/setup/wandb Read experiment runs, configuration, summaries, history, and run files. For API-key and entity discovery, see [Weights & Biases Setup](/home/setup/wandb). ```typescript theme={null} import { Workspace, MountMode, buildVfs } from '@struktoai/mirage-node' const ws = new Workspace({ '/wandb': await buildVfs('wandb', { entities: ['my-team'], api_key: process.env.WANDB_API_KEY, }), }, { mode: MountMode.READ }) ``` The VFS also ships in `@struktoai/mirage-browser`; its implementation uses standard `fetch`. Browser access depends on the service's CORS configuration. ## Config | Field | Description | | - | - | | `timeout` 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. | | `entities` required | W\&B entities (users or teams) the mount shows as top-level directories; no other entity is reachable. | | `apiKey` default `''`, secret | W\&B API key, sent as HTTP Basic auth. Empty sends no credentials. | | `baseUrl` default `'https://api.wandb.ai'` | W\&B API root. Queries go to its `/graphql`, and only downloads from the same origin carry the key. | | `pageSize` default `100` | Items per GraphQL page, and steps per window when reading `history.jsonl`. | | `maxPages` default `10000` | The most pages one listing or history read fetches. Past it the read fails rather than return a partial result. | Fields marked secret are redacted in snapshots. ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Weights & Biases mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | `wandb`, read | > > #### VFS Layout > > ##### `/<path>` > > ```text theme={null} > /<path> > <entity>/ > <project>/ > <run-id>/ > run.json > config.json > summary.json > history.jsonl > files/ > ``` > > * Read only. Only configured entities are visible. Run IDs are stable; > display names may repeat. > * `run.json` holds identity, creator, sweep/group/job, tags, timestamps, > notes, system metrics, history keys and count, and file count. Its > `user` contains the creator's id, name, username and email, when > available; its `read_only` is W\&B's permission, not the mount mode. > Missing run metadata is `null`. > * `history.jsonl` scans unsampled history in original order, preserving > missing metrics and `_step`. Logged training-step keys are independent > of `_step`. History reads may be large; use `head` to stream a prefix. > * `summary.json` metrics are stored values, not history maxima. > * `files/` keeps run-relative paths; `files/wandb-metadata.json`, when > present, describes the machine and runtime environment. > * Listings and reads are lazy. > > #### 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | Read only: no command changes files. `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>` | `wandb`, read | > > ## VFS Layout > > ### `/<path>` > > ```text > /<path> > <entity>/ > <project>/ > <run-id>/ > run.json > config.json > summary.json > history.jsonl > files/ > ``` > > - Read only. Only configured entities are visible. Run IDs are stable; > display names may repeat. > - `run.json` holds identity, creator, sweep/group/job, tags, timestamps, > notes, system metrics, history keys and count, and file count. Its > `user` contains the creator's id, name, username and email, when > available; its `read_only` is W&B's permission, not the mount mode. > Missing run metadata is `null`. > - `history.jsonl` scans unsampled history in original order, preserving > missing metrics and `_step`. Logged training-step keys are independent > of `_step`. History reads may be large; use `head` to stream a prefix. > - `summary.json` metrics are stored values, not history maxima. > - `files/` keeps run-relative paths; `files/wandb-metadata.json`, when > present, describes the machine and runtime environment. > - Listings and reads are lazy. > > ## 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>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | Read only: no command changes files. `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. > ```` The mount exposes `/<entity>/<project>/<run-id>/` with `run.json`, `config.json`, `summary.json`, `history.jsonl`, and `files/`. Configure one or more entities explicitly; project and run listings are fetched on demand and follow service pagination. Run IDs identify directories; duplicate display names remain separate runs. `run.json` contains the run metadata exposed by the supported W\&B API fields: | Fields | Contents | | - | - | | `entity`, `project`, `run`, `path` | Run identity and its `entity/project/run-id` path | | `storage_id`, `display_name`, `state` | W\&B's opaque storage ID, display name, and reported state | | `tags`, `sweep_name`, `group`, `job_type` | Experiment organization | | `commit`, `created_at`, `heartbeat_at` | Source revision, creation time, and last heartbeat | | `description`, `notes`, `user` | Run description, notes, and creator's `id`/`name`/`username`/`email` | | `read_only` | W\&B's reported edit permission; the Mirage mount remains read-only | | `system_metrics` | Latest system metrics decoded as JSON, retaining nested values | | `history_line_count`, `history_keys`, `file_count` | History row count, metric-key metadata including the last step, and file count | For example, the synthetic integration fixture renders this complete `run.json`: ```json theme={null} { "entity": "lab", "project": "experiments", "run": "run-a", "path": "lab/experiments/run-a", "storage_id": "synthetic-storage-id-a", "display_name": "duplicate", "state": "finished", "tags": [ "baseline", "café" ], "sweep_name": "sweep-01", "group": "ablation", "job_type": "train", "commit": "0123456789abcdef0123456789abcdef01234567", "read_only": false, "created_at": "2026-01-01T00:00:00Z", "heartbeat_at": "2026-01-01T00:05:00Z", "description": "Synthetic experiment metadata", "notes": "First line\nSecond line: café", "user": { "id": "synthetic-user-id-bob", "name": "Bob Example", "username": "bob", "email": "bob@example.com" }, "system_metrics": { "cpu": 0, "gpu.0.memoryAllocated": 128.5, "nested": { "missing": null } }, "history_line_count": 4, "history_keys": { "lastStep": 5, "keys": { "score": { "type": "number", "count": 3 }, "train_step": { "type": "number", "count": 4 } } }, "file_count": 4 } ``` Unavailable metadata is `null`; empty tags, zero counts, false permissions, and original timestamp strings are preserved. These fields are fetched only when reading `run.json`, in one run query. Listing and stat do not fetch them. The `user` is the run's creator, not the identity associated with the API key. When the creator exists, `user` has `id`, `name`, `username`, and `email`; W\&B requires the creator's ID and name, while username/email may be null. A missing creator is `user: null`. Reading these fields does not query the authenticated viewer or discover teams. Machine/runtime details are available at `files/wandb-metadata.json` when uploaded; reading `run.json` does not download that file. `config.json` unwraps W\&B's configuration `value` envelopes. `summary.json` contains the stored summary, which may differ from the best value in history. These documents have run-defined keys rather than a fixed Mirage field list. Nested objects, arrays, metric names containing `/` or `.`, and null values remain intact. For this fixture, they are `{"lr": 0.01, "label": "café"}` and `{"score": 0.4}`. `history.jsonl` scans full history in `_step` windows using the public SDK's unsampled scan protocol. It retains row order, missing keys, nulls, and logged training-step fields. `_step` and a training-step metric are separate values. An empty window does not end a scan. The last step is captured when a read begins; rows appended later are visible on a subsequent read. One-step query windows are widened to two steps to avoid a live API edge case; results are filtered to the original range without duplicates or later rows. Run files retain their relative paths and are downloaded as raw bytes. Listing and stat do not download histories or files. Rendered JSON and history have unknown sizes; raw file sizes come from W\&B's file metadata. Directory metadata uses Mirage's index cache (600 seconds by default). A project listing also establishes its runs' existence; a file catalog populates all nested directories, so traversing them reuses the same metadata. Config, summary, and history reads request their own fields. Downloads resolve the exact filename for a fresh URL on each read. File content and download URLs are not cached in the index. Reads and downloads stream, so `head` can stop before fetching the entire history. `page_size` defaults to 100 (maximum 1000); `max_pages` defaults to 10000. Exhausting a page budget raises an error instead of returning a complete-looking partial result. Recursive `du` is capped at 1000 entries; glob expansion uses Mirage's standard traversal limit. API keys use host configuration and are redacted from VFS state. No write operations or W\&B CLI are registered. # Wasabi Source: https://docs.mirage.strukto.ai/typescript/setup/wasabi Set up Wasabi as a MIRAGE VFS from Node or the browser. Wasabi uses the S3 API with AWS Signature V4 against `https://s3.<region>.wasabisys.com` (`https://s3.wasabisys.com` for `us-east-1`). MIRAGE derives this endpoint from your region automatically. Credentials (Wasabi access key pair) are created the same way in both runtimes, see [Wasabi Credentials](/home/setup/wasabi). ## Node (server-side) ```bash theme={null} pnpm add @struktoai/mirage-node ``` ```ts theme={null} import { MountMode, WasabiVFS, Workspace } from '@struktoai/mirage-node' const wasabi = new WasabiVFS({ bucket: process.env.WASABI_BUCKET!, region: process.env.WASABI_REGION!, accessKeyId: process.env.WASABI_ACCESS_KEY_ID!, secretAccessKey: process.env.WASABI_SECRET_ACCESS_KEY!, }) const ws = new Workspace({ '/bucket/': wasabi }, { mode: MountMode.READ }) const res = await ws.shell('ls /bucket/') console.log(res.stdoutText) ``` ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `accessKeyId` secret | Access key ID; set it with `secretAccessKey`. Unset uses the AWS SDK credential chain. | | `secretAccessKey` secret | Secret access key paired with `accessKeyId`. | | `sessionToken` secret | Session token for temporary credentials, sent with the access key pair. | | `profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. | | `forcePathStyle` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. | | `keyPrefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. | | `timeout` 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. | | `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. | | `region` default `'us-east-1'` | Wasabi region. It builds the endpoint `https://s3.<region>.wasabisys.com` (`https://s3.wasabisys.com` for `us-east-1`) unless `endpoint` is set, and signs every request. | | `endpoint` | Endpoint URL that replaces the one the provider derives. | Fields marked secret are redacted in snapshots. ## Browser (presigned URLs) ```bash theme={null} pnpm add @struktoai/mirage-browser ``` The browser `WasabiVFS` is secret-free, your backend signs each operation using your Wasabi keys and returns a URL. Wasabi accepts AWS Signature V4, so `@aws-sdk/s3-request-presigner` works, pointed at the Wasabi endpoint. ### Config | Field | Description | | - | - | | `bucket` required | Name of the bucket to mount. | | `presignedUrlProvider` required, secret | Function `(path, operation, options)` that returns a signed URL for each S3 operation; your server signs it, so the browser holds no keys. | | `region` default `'us-east-1'` | Region of the bucket. It builds the endpoint `https://s3.<region>.wasabisys.com` (`https://s3.wasabisys.com` for `us-east-1`) unless `endpoint` is set. | | `endpoint` | Endpoint URL that replaces the one the provider derives. Requests go to the host each presigned URL names; the mount uses it to name its storage location. | | `defaultContentType` default `'application/octet-stream'` | `Content-Type` stored with every object the mount writes. | | `keyPrefix` | Key prefix the mount treats as its root. The browser can change it before a URL is signed, so enforce the prefix on the signing server. | | `timeout` 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. | Fields marked secret are redacted in snapshots. ### 1. Server: sign URLs with the Wasabi endpoint ```ts theme={null} import { CopyObjectCommand, DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client, } from '@aws-sdk/client-s3' import { getSignedUrl } from '@aws-sdk/s3-request-presigner' const REGION = process.env.WASABI_REGION! const client = new S3Client({ region: REGION, endpoint: `https://s3.${REGION}.wasabisys.com`, credentials: { accessKeyId: process.env.WASABI_ACCESS_KEY_ID!, secretAccessKey: process.env.WASABI_SECRET_ACCESS_KEY!, }, }) const BUCKET = process.env.WASABI_BUCKET! app.post('/presign/wasabi', async (req, res) => { const { path, op, opts } = req.body const key = path.replace(/^\/+/, '') const ttl = typeof opts?.ttlSec === 'number' ? opts.ttlSec : 300 let cmd switch (op) { case 'GET': cmd = new GetObjectCommand({ Bucket: BUCKET, Key: key }); break case 'PUT': cmd = new PutObjectCommand({ Bucket: BUCKET, Key: key, ContentType: opts?.contentType }); break case 'HEAD': cmd = new HeadObjectCommand({ Bucket: BUCKET, Key: key }); break case 'DELETE': cmd = new DeleteObjectCommand({ Bucket: BUCKET, Key: key }); break case 'LIST': cmd = new ListObjectsV2Command({ Bucket: BUCKET, Prefix: opts?.listPrefix, Delimiter: opts?.listDelimiter, ContinuationToken: opts?.listContinuationToken, }); break case 'COPY': cmd = new CopyObjectCommand({ Bucket: BUCKET, Key: key, CopySource: `${BUCKET}/${opts?.copySource}`, }); break } res.json({ url: await getSignedUrl(client, cmd, { expiresIn: ttl }) }) }) ``` > [!NOTE] > > For `us-east-1` the endpoint is `https://s3.wasabisys.com` (no region segment). ### 2. Browser: wire it up ```ts theme={null} import { MountMode, WasabiVFS, Workspace } from '@struktoai/mirage-browser' const wasabi = new WasabiVFS({ bucket: 'my-bucket', region: 'us-east-2', presignedUrlProvider: async (path, op, opts) => { const r = await fetch('/presign/wasabi', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path, op, opts }), }) const { url } = await r.json() return url }, }) const ws = new Workspace({ '/bucket/': wasabi }, { mode: MountMode.READ }) ``` > [!TIP] > > `region` on the browser config is only used for display/logging; the actual endpoint is baked into the presigned URLs your backend returns. ### 3. CORS Wasabi supports the S3 `PutBucketCors` call, so the AWS CLI works against the Wasabi endpoint: ```bash theme={null} aws s3api put-bucket-cors --bucket "$WASABI_BUCKET" \ --endpoint-url "https://s3.$WASABI_REGION.wasabisys.com" \ --cors-configuration '{"CORSRules":[{"AllowedOrigins":["http://localhost:5173","https://app.example.com"],"AllowedMethods":["GET","PUT","HEAD","DELETE","POST"],"AllowedHeaders":["*"],"ExposeHeaders":["ETag","Content-Length","Content-Type","Last-Modified"]}]}' ``` See the [Wasabi VFS](/python/vfs/wasabi) docs for the equivalent Python wiring. For `write: conditional` on this provider, see [S3-compatible stores](/home/configuration#s3-compatible-stores). ## VFS.md The [VFS.md](/home/setup/vfs-md) an agent reads with Wasabi mounted at `/<path>`. > [tab] Rendered > > ### Virtual Filesystem > > | Path | Description | > | - | - | > | `/<path>` | write | > > #### 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. | > > #### Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | - | - | > | `/<path>` | `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>` | write | > > ## 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. | > > ## Limitations of Unix Commands for VFS > > Where a path differs from a local filesystem: > > | Path | Limitations | > | --- | --- | > | `/<path>` | `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. > ``` ## Integration What Wasabi answers through its own API, so fewer files are read. [Integration](/home/integration/overview) explains each command. | Command | On Wasabi | | - | - | | `md5sum` | The object's ETag, when it is the MD5: a single-part upload, unencrypted or under SSE-S3 | | `find`, `du`, `ls -R`, `tree` | One recursive listing | # Adding a New VFS Source: https://docs.mirage.strukto.ai/typescript/vfs/new Mount a service Mirage does not ship by writing one class. A VFS is a class that extends `BaseVFS`. Override `readdir`, `read` and `stat`, and `ls`, `cat`, `grep`, `find`, `head`, `wc` and the other read commands work on the service. [Custom VFS](/home/setup/custom-vfs) lists every method, with examples for a writable VFS and for grep on the service's own search. ## Write one ```ts theme={null} import { Accessor, BaseVFS, FileStat, type PathSpec, Workspace } from '@struktoai/mirage-node' import { parseConfigWithSchema, secretStr, z } from '@struktoai/mirage-core/vfs/secrets' const JiraConfigSchema = z.object({ site: z.string(), token: secretStr() }) class JiraAccessor extends Accessor { constructor(readonly client: JiraClient) { super() } } class JiraVFS extends BaseVFS<JiraAccessor> { constructor(input: Record<string, unknown>) { const config = parseConfigWithSchema(JiraConfigSchema, input) super({ name: 'jira', accessor: new JiraAccessor(makeClient(config)), vfsMd: 'Issues rendered as .json files.', }) } override async readdir(path: PathSpec): Promise<FileStat[]> { ... } override async read(path: PathSpec): Promise<Uint8Array> { ... } override async stat(path: PathSpec): Promise<FileStat> { ... } override async close(): Promise<void> { if (this.isClosed) return try { await this.accessor.client.close() } finally { await super.close() } } } const ws = new Workspace({ '/jira/': new JiraVFS({ site: 'acme', token: '...' }) }) await ws.shell('grep -rl outage /jira/') ``` `parseConfigWithSchema` refuses an unknown key by name, and `secretStr()` keeps the token out of logs and snapshots. The subpath import needs `npm install @struktoai/mirage-core`. `readdir` returns each child's `FileStat` with `name` set to the base name. The mount keeps the listing and answers a later `stat` from it, so `ls -l` costs one request. Use `path.vfsPath` to address the service and `path.virtual` for the workspace path. Set `FileStat.size` to the length of the bytes `read` returns, or `null` when it is unknown. ## Add functions as the service grows Every other function is optional. Override one, and the commands that need it start working; leave it out, and those commands answer `Operation not supported`. | Functions | Enables | | - | - | | `write`, `append`, `create`, `truncate` | `>`, `>>`, `touch`, `truncate`, `sed -i` | | `mkdir`, `rmdir`, `unlink`, `rmR`, `rename`, `copy`, `dirCopy`, `setattr` | `mkdir`, `rm`, `mv`, `cp`, `chmod`, `touch -d` | | `filesContaining`, `linesContaining` | [Search](/home/integration/search) for `grep` and `rg` from the service's own index | | `firstLines`, `lastLines`, `lineCount`, `checksum`, `readTree` | Fast `head`, `tail`, `wc -l`, `md5sum`, `find` ([Lines](/home/integration/lines), [Walks](/home/integration/walks)) | | `deltaHook` | [Notifications](/home/notifications/support) from the service's change feed | The mount mode still decides whether a write may run. `read` may return an async iterable of bytes for a large file, and `write` receives one when a program's output streams into the mount. ## Plug in the service's search `filesContaining` and `linesContaining` hand Mirage the service's own search. `grep` and `rg` ask them which files or lines can hold the text and read only those; they still match every line themselves, so the output is the same as a full read. `beforeFullWalk` can refuse a command that would walk the whole tree. For example, an S3 bucket whose objects are indexed in Elasticsearch under their keys, by whatever indexes the bucket (such as a function on S3 events). Extend the built-in `S3VFS` and answer from the index: ```ts theme={null} import { Client } from '@elastic/elasticsearch' import { MountMode, S3VFS, Workspace, type PathSpec, type S3Config } from '@struktoai/mirage-node' import { mountedPath } from '@struktoai/mirage-core/utils/key_prefix' class IndexedS3VFS extends S3VFS { override readonly wholeWordSearch = true constructor( config: S3Config, readonly es: Client, ) { super(config) } override async filesContaining( path: PathSpec, text: string, opts: { wholeWord: boolean; ignoreCase: boolean }, ): Promise<PathSpec[] | null> { if (!opts.wholeWord) return null const found = await this.es.search({ index: this.config.bucket, query: { match_phrase: { body: text } }, size: 1000, track_total_hits: true, }) const total = typeof found.hits.total === 'number' ? found.hits.total : (found.hits.total?.value ?? 0) if (total > found.hits.hits.length) return null return found.hits.hits.map((hit) => mountedPath(path, `/${hit._id}`)) } override async close(): Promise<void> { if (this.isClosed) return try { await this.es.close() } finally { await super.close() } } } const vfs = new IndexedS3VFS({ bucket: 'docs' }, new Client({ node: 'http://localhost:9200' })) const ws = new Workspace({ '/s3/': [vfs, MountMode.READ] }) await ws.shell('grep -rlw outage /s3/') ``` `grep -rlw outage /s3/` reads only the objects Elasticsearch names. Elasticsearch ignores case, so it may name more than grep prints; grep checks each line and drops the rest. `grep -rl outage` without `-w` gets `null` and reads every object, so `outages` still matches. The mount is read-only because a write through Mirage would leave the index behind. The answer is only as complete as the index: grep skips an object written elsewhere that Elasticsearch has not indexed yet, so return `null` while the indexer lags. | Function | Asked by | Answers | | - | - | - | | `filesContaining(path, text, { wholeWord, ignoreCase })` | `grep -r`, `rg` on a folder | The files under `path` that may hold `text`, or `null` to read every file | | `linesContaining(path, text, { ignoreCase })` | `grep`, `rg` on one file | The lines that may hold `text`, in file order, or `null` to read the file | | `beforeFullWalk(path, files)` | `tar -c`, `cp -r`, `rm -r`, `chmod -R`, `diff -r` | Resolve to let the walk run; reject to refuse it | * Answer more files than needed, never fewer: an extra file costs one read, a missing one is a wrong answer. Return `null` whenever the answer may be incomplete, such as a truncated result or an index that lags writes. * A search that matches only whole words, as Elasticsearch does, returns `null` unless `opts.wholeWord` is set, and sets `wholeWordSearch = true` so the mount's VFS.md tells the agent to use `grep -w`. * Set `searchable` to the globs the search covers, such as `['*/*.json']`; a file outside them is always read. * `walkLimit` caps how many files one command walks, 1000 by default. [Search](/home/integration/search) lists which patterns and flags reach these functions, and which built-in VFSs answer them. A service action that is not a file, such as a JQL search or adding a comment to an issue, belongs in a [CLI](/typescript/cli/custom), next to the mount. ## Use it in YAML A workspace YAML mounts the class by its file and name: ```yaml theme={null} mounts: /jira: vfs: ./jira.mjs:JiraVFS config: site: acme token: ${JIRA_TOKEN} ``` To write `vfs: jira` instead, register the class once: ```ts theme={null} import { registerVfs } from '@struktoai/mirage-node' registerVfs('jira', (config) => Promise.resolve(new JiraVFS(config))) ``` ## Examples Runnable, each with a Python twin: | Example | Shows | | - | - | | [`custom_vfs.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/vfs/new/custom_vfs.ts) | A complete backend in one file: grep on its search, a snapshot and a load | | [`basevfs_views.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/vfs/new/basevfs_views.ts) | A read-only VFS beside a nested mount, a symlink and a CLI | | [`custom_command.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/vfs/new/custom_command.ts) | A command of the VFS's own | | [`filetype.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/vfs/new/filetype.ts) | A renderer for one file type |