> ## 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 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](https://docs.mirage.strukto.ai/home/policy/policies.md) 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:`](https://docs.mirage.strukto.ai/home/policy/route-machine) | at `pre_execute`, for every session | a route, or a deny or ask |
| a server's [policy file](https://docs.mirage.strukto.ai/home/access/http.md#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. 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](https://docs.mirage.strukto.ai/home/policy/policies.md#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](https://docs.mirage.strukto.ai/home/policy/policies.md#asks) |
| `{"kind": "route", "machine": "docker"}` | at `pre_execute` and `pre_command`: runs the line, or the command, on that machine |

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](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.

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


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