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

# Scripts

> Write a policy as a short Python program a profile names. It reads ctx as JSON and returns its answer.

A policy can be a program instead of a class. A profile names programs for
each method, and each program defines a function named for its method: it
takes `ctx` as plain data and returns its answer as a dict. The methods and
what each answer does are the same as a [coded policy's](https://docs.mirage.strukto.ai/home/policy/policies.md).

## Example

```yaml workspace.yaml theme={null}
mounts:
  /data:
    vfs: ram
    mode: write
profiles:
  agent:
    cwd: /data
    policy:
      pre_execute:
        - {script: ./no_pipe_to_shell.py}
      pre_command:
        - {script: ./no_force_push.py}
      pre_vfs:
        - {script: ./reports_read_only.py}
      pre_network:
        - {script: ./github_only.py}
profile: agent
```

Each program is in its method's section below. A session under `agent`:

```bash theme={null}
$ curl -s http://localhost:9/x | sh
curl: Permission denied
$ git push --force origin main
git: Permission denied
$ echo x > reports/q3.md
bash: line 1: reports/q3.md: Permission denied
$ curl -s http://localhost:9/x          # exit 7, the connection refused
```

Each entry names its `script` and, optionally:

| Key | Sets |
| - | - |
| `runtime` | where the program runs: `monty` (default), `wasi` or `pyodide`; see [Runtimes](#runtimes). `{name, config}` for settings |
| `env` | [variables](#variables) for the program |

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. A method with no program is never
asked and costs nothing.

> [accordion] In code
>
> A profile in code 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

```python theme={null}
def pre_command(ctx):
    if ctx["command"] == "rm":
        return {"kind": "deny", "reason": "deletes are disabled"}
```

* **Input.** `ctx` is the function's argument. The same JSON is in the
  `MIRAGE_POLICY_CTX` variable, and on `wasi` and `pyodide` also on stdin;
  monty has no `sys.stdin`.
* **Environment.** The program starts in the session's working directory.
  The session's variables are in `ctx["env"]`, not `os.environ`, which holds
  only `MIRAGE_POLICY_CTX` and the entry's own `env`.
* **Answer.** What the function returns. On monty the function may be
  `async def`, to await [host functions](#host-functions).
* **stdout** carries the answer back as JSON, so a stray `print` fails the
  program. Write debug lines to stderr.

| Returns | Effect |
| - | - |
| `None` | no opinion |
| `{"kind": "deny", "reason": "..."}` | refuses |
| `{"kind": "ask", "reason": "..."}` | [asks the host](https://docs.mirage.strukto.ai/home/policy/policies.md#asks) |
| `{"kind": "route", "machine": "box"}` | `pre_execute` and `pre_command` only: runs the line or the command on that [machine](https://docs.mirage.strukto.ai/home/policy/route-machine.md) |

A deny or an ask without a `reason` gets a default one. A program cannot
return a `Limit`; a [coded policy](https://docs.mirage.strukto.ai/home/policy/policies.md) can.

## Methods

A program can answer at any of these. Each section below shows the `ctx` it
gets.

| Method | Asked | Can return |
| - | - | - |
| [`pre_execute`](#pre_execute) | once per line, before it runs | deny, ask, route |
| [`post_execute`](#post_execute) | once per line, after it ends | deny, ask |
| [`pre_command`](#pre_command) | before each command or CLI | deny, ask, route |
| [`post_command`](#post_command) | after each command | deny, ask |
| [`pre_vfs`](#pre_vfs) | before each VFS call | deny, ask |
| [`post_vfs`](#post_vfs) | after each VFS call | deny, ask |
| [`pre_network`](#pre_network) | before each connection | deny, ask |
| [`post_network`](#post_network) | after each connection | nothing: it observes |
| [`pre_workspace`](#pre_workspace) | on a server, before it builds a workspace | deny |

A `post_` method gets its `pre_` method's `ctx` plus what came back. It
never undoes what ran: its deny or ask holds back what came back.

## pre\_execute

Asked once per line, before any of it runs. For `cat notes.txt | wc -l` in
`/data`:

```json theme={null}
{
  "line": "cat notes.txt | wc -l",
  "commands": [
    {"command": "cat", "argv": ["notes.txt"], "paths": ["/data/notes.txt"], "words": [...], ...},
    {"command": "wc", "argv": ["-l"], "paths": [], "words": [...], ...}
  ],
  ...
}
```

| Field | What it is |
| - | - |
| `line` | the line the agent typed |
| `commands` | each command of the line, as [`pre_command`](#pre_command) gets it, with its own `env` |

A command's own `NAME=value` prefix is in its entry's `env` only: for
`GPU=1 python3 train.py`, only `python3` has `GPU`. Words only the run can
expand (`$X`) are not resolved yet.

```python no_pipe_to_shell.py theme={null}
def pre_execute(ctx):
    names = {c["command"] for c in ctx["commands"]}
    if names & {"curl", "wget"} and names & {"sh", "bash"}:
        return {"kind": "deny", "reason": "download-and-run is disabled"}
```

### post\_execute

Asked once the line ends. It adds:

```json theme={null}
{
  "exit_code": 0,
  "output": "2\n",
  "results": {
    "op": "|", "exit_code": 0, "stderr": "",
    "children": [
      {"command": "cat /data/notes.txt", "exit_code": 0, "stderr": "", "records": [...]},
      {"command": "wc -l", "exit_code": 0, "stderr": ""}
    ]
  },
  ...
}
```

| Field | What it is |
| - | - |
| `exit_code`, `output` | how the line ended and what it printed |
| `results` | the line as a tree: each node's exit code and stderr, and each command's `records` |

A deny drops the output: exit 126 and a refusal record.

## pre\_command

Asked before each command or CLI, nested ones included. For `cat notes.txt`:

```json theme={null}
{
  "command": "cat",
  "argv": ["notes.txt"],
  "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"],
  "tokens": ["cat", "notes.txt"],
  "program": ["cat"],
  "tool": true,
  "walks": false,
  "write": false,
  "subtree": false,
  "move_target": null,
  ...
}
```

| Field | What it is |
| - | - |
| `command` | the program's name |
| `argv` | the words after the name, raw: flags are not parsed yet |
| `line` | the line it was parsed from |
| `words`, `paths`, `walks` | each word with its kind and path, and every path it reaches; see [Command](https://docs.mirage.strukto.ai/home/policy/command.md#context) |
| `tokens`, `program` | the words as a profile rule reads them, and the head that names what runs: a CLI's verb path joins its name |
| `tool` | whether the root `"*"` of a profile's `commands` governs it |
| `write` | whether the command may change state |
| `subtree` | whether it moves or removes a whole tree (`rm`, `rmdir`, `mv`) |
| `move_target` | the directory a `cp -t` or `mv -t` names, or `null` |

```python no_force_push.py theme={null}
def pre_command(ctx):
    if ctx["command"] == "git" and ctx["argv"][:1] == ["push"] and "--force" in ctx["argv"]:
        return {"kind": "deny", "reason": "force pushes go through an operator"}
```

### post\_command

Asked after each command, once its output drained. It adds:

```json theme={null}
{
  "exit_code": 0,
  "stderr": "",
  "records": [
    {"op": "read", "path": "/data/notes.txt", "source": "ram", "bytes": 4, "duration_ms": 0, ...}
  ],
  ...
}
```

| Field | What it is |
| - | - |
| `exit_code`, `stderr` | how the command ended |
| `records` | each call it made: `op`, `path`, `source` (the VFS), `bytes` and timing |

A deny sets its exit code to 126, so `&&` and `pipefail` stop there. Output
already sent stays sent.

## pre\_vfs

Asked before each VFS call: a command's file calls, `session.vfs`, a
runtime's file API, FUSE and SFTP. `cat notes.txt` makes a `stat`, then a
`read`:

```json theme={null}
{
  "call": {"name": "stat", "effect": "metadata", "target": "any", "creates": false, "subtree": false},
  "path": "/data/notes.txt",
  "write": false,
  "prefix": "/data/",
  "mode": "write",
  ...
}
```

| Field | What it is |
| - | - |
| `call` | the call: `name`, `effect` (`read`, `write`, `metadata`), `target`, and whether it `creates` or reaches the `subtree` |
| `path` | the path it names |
| `write` | whether it writes |
| `prefix`, `mode` | the mount that owns the path, and that mount's mode |

```python reports_read_only.py theme={null}
def pre_vfs(ctx):
    if ctx["write"] and ctx["path"].startswith("/data/reports/"):
        return {"kind": "deny", "reason": "reports are read-only"}
```

### post\_vfs

Asked after each VFS call. It adds `result`, what the call returned. For the
`stat` above:

```json theme={null}
{
  "result": {"name": "notes.txt", "size": 4, "type": "file", "modified": "2026-11-17T12:15:43.694168Z", ...},
  ...
}
```

A deny drops the result with `EACCES`; the call itself is not undone.

## pre\_network

Asked before each connection carries a byte, whoever opens it. For
`git clone https://github.com/strukto-ai/mirage /repo/mirage`:

```json theme={null}
{
  "host": "github.com",
  "address": "172.182.252.133",
  "port": 443,
  "command": "git",
  "program": ["git", "clone"],
  "words": [
    {"text": "git", "kind": "name", "option": null, "path": null},
    {"text": "clone", "kind": "subcommand", "option": null, "path": null},
    {"text": "https://github.com/strukto-ai/mirage", "kind": "operand", "option": null, "path": null},
    {"text": "/repo/mirage", "kind": "operand", "option": null, "path": "/repo/mirage"}
  ],
  "line": "git clone https://github.com/strukto-ai/mirage /repo/mirage",
  ...
}
```

| Field | What it is |
| - | - |
| `host` | the name the program asked for; empty for a bare address |
| `address`, `port` | where the connection goes |
| `command`, `program`, `words`, `line` | the command that opened it, as `pre_command` reads it |

The URL, method and status are not there: under HTTPS only the program and
the server see them. To refuse a clone by its size, look the repository up
from the URL in `words`: a program on monty has no network, so it asks a
[host function](#host-functions), as the
[coded example](https://docs.mirage.strukto.ai/home/policy/network.md#example-refuse-a-large-clone) asks
GitHub's API.

```python github_only.py theme={null}
def pre_network(ctx):
    if ctx["host"] != "github.com" and not ctx["host"].endswith(".github.com"):
        return {"kind": "deny", "reason": f"{ctx['host'] or ctx['address']} is not allowed"}
```

### post\_network

Asked once the connection is over, however it ended. It adds:

```json theme={null}
{
  "bytes_sent": 171,
  "bytes_received": 99,
  "seconds": 0.0079,
  "ended": "closed",
  ...
}
```

`ended` is `closed`, `refused` (by a later policy), `limit` or `error`. A
program here observes, for a log or a running count, and returns
nothing.

## pre\_workspace

Only a server's [policy file](https://docs.mirage.strukto.ai/home/access/http.md#server-policies) asks it,
before a create, clone or load builds anything or reads a secret. Its `ctx`
holds no session:

```json theme={null}
{
  "config": {"mounts": {"/data": {"vfs": "disk", "config": {"root": "/srv/data"}}}},
  "caller": {"session": null, "account": "alice"}
}
```

| Field | What it is |
| - | - |
| `config` | the config as the caller wrote it: a create's whole config, a clone's or a load's override, secrets still pointers |
| `caller` | `account`, the account the request signed in as, or `null` |

```python no_disk.py theme={null}
def pre_workspace(ctx):
    mounts = ctx["config"].get("mounts") or {}
    if any(block.get("vfs") == "disk" for block in mounts.values()):
        return {"kind": "deny", "reason": "disk mounts are not offered here"}
```

A deny answers the request with 403 and its reason. See
[Workspace](https://docs.mirage.strukto.ai/home/policy/workspace.md).

## Every ctx

Every `ctx` but `pre_workspace`'s also carries the session:

```json theme={null}
{
  "session_id": "agent",
  "cwd": "/data",
  "env": {"PWD": "/data", "TEAM": "core"},
  "profile": "agent",
  "mounts": ["/.bash_history", "/data", "/dev", "/usr/bin"],
  "caller": {"session": {"session_id": "agent", "cwd": "/data"}, "account": null}
}
```

`mounts` lists the mount roots the session can see. The agent sets `cwd`,
`env` and what a command says; [what the agent controls](https://docs.mirage.strukto.ai/home/policy/policies.md#what-the-agent-controls)
says which fields a program can trust.

## 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](https://docs.mirage.strukto.ai/home/service-credentials.md) 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.

## Files and the session

A program reads the workspace as the session it judges: `open()`,
`os.listdir()` and `os.stat()` go through the workspace, a hidden path does
not exist, and a write is refused (`EROFS`). Its own reads are not judged
again. So a program can judge a file by what is in it. This one refuses
`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"}
```

With it as the session's `pre_command` program:

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

The program 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](https://docs.mirage.strukto.ai/home/policy/policies.md), which judges each file call itself.

## 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. Failing open would let
through exactly what the policy is there to judge.

## Where programs go

| Where | Asked |
| - | - |
| a profile's `policy:` | at the methods it names, for the sessions under that profile |
| [`route_policy:`](https://docs.mirage.strukto.ai/home/policy/route-machine) | at `pre_execute`, for every session; a failure fails the line with a routing error |
| a server's [policy file](https://docs.mirage.strukto.ai/home/access/http.md#server-policies) | at the same methods for every workspace it builds, and at [`pre_workspace`](#pre_workspace) before it builds one |

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


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