Metadata-Version: 2.5
Name: langchain-hyperlight
Version: 0.1.0
Summary: LangChain tool for executing untrusted code in Microsoft Hyperlight micro VMs (experimental, AI-generated)
Project-URL: Homepage, https://github.com/wildaces215/langchain-hyperlight
Project-URL: Repository, https://github.com/wildaces215/langchain-hyperlight
Project-URL: Documentation, https://github.com/wildaces215/langchain-hyperlight#readme
Author: theph03*nix215
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: code-execution,hyperlight,langchain,micro-vm,sandbox,wasm
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.10
Requires-Dist: hyperlight-sandbox[python-guest,wasm]>=0.5.0
Requires-Dist: langchain-core>=0.3.0
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Provides-Extra: js
Requires-Dist: hyperlight-sandbox[hyperlight-js,javascript-guest]>=0.5.0; extra == 'js'
Description-Content-Type: text/markdown

> ⚠️ **VIBE-CODED — AI-GENERATED, NOT PRODUCTION-READY**
>
> This project was written by an AI ("vibe coded"). It is **experimental** and has had
> **no security review, fuzzing, or adversarial testing**. It has only been smoke-tested
> on **Linux (x86_64)**. **Use at your own risk** — do not rely on it for anything
> security-sensitive or mission-critical. See [Limitations](#limitations).

# langchain-hyperlight

A [LangChain](https://www.langchain.com/) tool that executes untrusted code inside a
[Microsoft Hyperlight](https://github.com/hyperlight-dev/hyperlight) **micro virtual machine**.

Hyperlight is a lightweight Virtual Machine Manager (VMM) designed to be embedded within
applications. It runs untrusted code in hardware-isolated micro VMs (KVM, MSHV, or Hyper-V)
with very low latency and minimal overhead. This package exposes that capability to LangChain
agents as a standard tool, so an LLM can safely run arbitrary code without touching the host.

## Features

- **Hardware isolation** — code runs in a micro VM, not on the host.
- **Host tool dispatch** — register host callables that guest code invokes by name with
  schema-validated arguments (`call_tool(...)`).
- **Capability-based file access** — read-only `/input`, writable `/output`, strict path isolation.
- **Network allow-listing** — network is off by default; opt in per-domain and per-HTTP-verb.
- **Snapshot / restore** — capture and rewind sandbox state.
- **Lazy sandbox creation** — constructing the tool is cheap; the micro VM boots on first use.

## Limitations

This is an early-stage, AI-generated integration. Be aware of the following before adopting it.

### Platform

- **x86_64 only.** Hyperlight currently targets x86_64; there are no `aarch64` (ARM) wheels.
  Raspberry Pi, Apple Silicon, and AWS Graviton are unsupported.
- **glibc 2.34+.** The Rust backend ships `manylinux_2_34_x86_64` wheels, so it needs a recent
  glibc. Works on Ubuntu 22.04+, Debian 12+, Fedora 36+, RHEL 9+. Does **not** work on
  Ubuntu 20.04, Debian 11, RHEL 8, or musl-based distros (Alpine, Void) without building the
  Rust backend from source.
- **Python 3.10–3.14.**
- **A hypervisor is required at runtime:** KVM (`/dev/kvm`) or MSHV on Linux.
- **Tested on Linux only.** This package has only been tested on **Linux (x86_64)**. It is
  **not tested on Windows or macOS** — use on those platforms at your own risk.

### Security model

- The micro VM isolates the *guest code* you run, but any **host tools you register via
  `host_tools` run with full host privileges** inside the sandbox's `call_tool(...)`. Only
  register callables you trust, and treat their inputs as untrusted.
- Network is off by default and gated by `allowed_domains`, but an allow-listed domain is
  reachable by any code running in the sandbox.
- This package has **not** been security-reviewed. Do not treat it as a hardened sandbox
  boundary without your own audit.

### Maturity

- **Alpha / vibe-coded.** No fuzzing, no adversarial testing, no cross-platform CI matrix.
- The thread-confinement worker (required because the `WasmSandbox` is `unsendable` in PyO3)
  is correct for the tested paths but has not been stress-tested under heavy concurrency.
- `host_tools` accepts plain Python callables only — it does not yet wrap LangChain
  `BaseTool` instances directly.

## Installation

> **Platform support:** this package is **tested on Linux (x86_64) only**. It is
> **not tested on Windows or macOS** — install and use on those platforms at your own risk.

```shell
pip install langchain-hyperlight
```

This pulls in `langchain-core` and `hyperlight-sandbox[wasm,python_guest]`.

> **Prerequisite:** a working hypervisor is required at *runtime* (not at install time):
>
> - **Linux:** KVM (`/dev/kvm`) or MSHV (`/dev/mshv`)

## Quick start

```python
from langchain_hyperlight import HyperlightSandboxTool

tool = HyperlightSandboxTool(
    host_tools={
        "add": lambda a=0, b=0: a + b,
        "greet": lambda name="world": f"Hello, {name}!",
    },
    allowed_domains={"https://httpbin.org": ["GET"]},
)

result = tool.invoke({
    "code": """
total = call_tool('add', a=3, b=4)
greeting = call_tool('greet', name='James')
print(f"3 + 4 = {total}")
print(greeting)
""",
})
print(result)
```

### Using it inside an agent

```python
from langchain_core.tools import create_agent  # or your agent of choice

agent = create_agent(model, tools=[tool])
```

The tool is a standard `langchain_core.tools.BaseTool`, so it works with any LangChain agent
runtime (LangGraph, `create_agent`, `AgentExecutor`, etc.).

## Relationship to Microsoft's Agent Framework

Microsoft ships an official Hyperlight integration for *its own* Agent Framework:
[`agent-framework-hyperlight`](https://github.com/microsoft/agent-framework/tree/main/python/packages/hyperlight)
(`HyperlightExecuteCodeTool` / `HyperlightCodeActProvider`). This package is the **LangChain**
equivalent: it targets `langchain_core.tools.BaseTool` and mirrors the same concepts — the
`execute_code` tool name, `file_mounts`, `allowed_domains`, and host-tool dispatch via
`call_tool(...)` — so the mental model transfers directly.

### Thread safety

The Hyperlight `WasmSandbox` is `unsendable` in PyO3: it may only be accessed and dropped from
the OS thread that created it, or it panics. This tool routes every sandbox operation through a
dedicated single-threaded worker, so it is safe to call from arbitrary threads and event loops
(including LangChain's async `ainvoke`).

## Guest environment

By default the sandbox runs **Python**. Inside the guest, these built-ins are available:

| Function | Purpose |
| --- | --- |
| `call_tool(name, **kwargs)` | Invoke a host-registered tool by name |
| `http_get(url)` / `http_post(url, body=...)` | HTTP to allow-listed domains only |
| `read_file(path)` / `write_file(path, data)` | Capability-based file I/O (`/input`, `/output`) |

## Configuration

`HyperlightSandboxTool` forwards its constructor arguments to
[`hyperlight_sandbox.Sandbox`](https://github.com/hyperlight-dev/hyperlight-sandbox):

| Argument | Default | Description |
| --- | --- | --- |
| `backend` | `"wasm"` | `"wasm"` (Python/JS guest) or `"hyperlight-js"` |
| `module` | `"python_guest.path"` | Packaged guest module reference |
| `module_path` | `None` | Explicit path to a `.aot`/`.wasm` guest |
| `input_dir` / `output_dir` | `None` | Host directories mounted into the guest |
| `temp_output` | `False` | Use a temporary output directory |
| `heap_size` / `stack_size` | `None` | Guest memory limits (e.g. `"25Mi"`) |
| `host_tools` | `{}` | `{name: callable}` exposed to the guest |
| `allowed_domains` | `{}` | Network allow-list (see below) |
| `file_mounts` | `{}` | Host paths staged into the guest `/input` tree (see below) |

`allowed_domains` accepts a domain string, a `(target, methods)` tuple, an `AllowedDomain`, or a
sequence of any of these:

```python
from langchain_hyperlight import AllowedDomain

tool = HyperlightSandboxTool(
    allowed_domains=[
        "api.github.com",                              # all methods
        ("internal.example.com", "GET"),               # GET only
        AllowedDomain("https://httpbin.org", ("GET", "POST")),
    ],
)
```

`file_mounts` accepts a path string (same path on host and in the sandbox), a
`(host_path, mount_path)` tuple, a `FileMount`, or a sequence of any of these. Mounted files are
staged into a managed temporary `/input` tree and are readable in the guest via `read_file(...)`:

```python
from langchain_hyperlight import FileMount

tool = HyperlightSandboxTool(
    file_mounts=[
        "/host/data",                                  # -> /input/data
        ("/host/models", "models"),                    # -> /input/models
        FileMount("/host/config", "config"),           # -> /input/config
    ],
)
```

The `create_hyperlight_tool()` factory is a thin convenience over the same constructor:

```python
from langchain_hyperlight import create_hyperlight_tool

tool = create_hyperlight_tool(
    host_tools={"add": lambda a=0, b=0: a + b},
    allowed_domains=["api.github.com"],
)
```

> **Note:** the tool always creates and owns its sandbox on a dedicated thread. Do not
> construct a `hyperlight_sandbox.Sandbox` yourself and try to share it across threads — the
> underlying `WasmSandbox` is `unsendable` and will panic if touched from a different thread
> than the one that created it. The tool manages this confinement for you.

## Running on Bluefin / Fedora Silverblue (immutable)

Bluefin is an immutable Fedora (Silverblue) image. The package itself installs normally into a
virtual environment, but the **KVM hypervisor** must be available on the host:

1. **Verify virtualization is enabled** in firmware (AMD-V / Intel VT-x):

   ```shell
   grep -E 'vmx|svm' /proc/cpuinfo
   ```

2. **Ensure the KVM device exists** (the `kvm_amd`/`kvm_intel` module is loaded):

   ```shell
   ls -l /dev/kvm
   ```

   If it is missing, the module is not loaded. On Bluefin this is usually a firmware/BIOS
   setting (enable SVM/VT-x) rather than a package issue, since the kernel ships KVM.

3. **Add your user to the `kvm` group** so you can open `/dev/kvm` without root:

   ```shell
   sudo usermod -aG kvm $USER
   # log out and back in, then verify:
   groups
   ```

4. **Install the package in a venv** (never layer Python packages system-wide on an immutable
   image — use `uv`, `pipx`, or a `distrobox`/`toolbox` container):

   ```shell
   uv venv .venv
   uv pip install --python .venv/bin/python langchain-hyperlight
   ```

   For a fully isolated dev environment, `distrobox` is the idiomatic Bluefin approach:

   ```shell
   distrobox create --name hyperlight-dev --image fedora:latest
   distrobox enter hyperlight-dev
   ```

## Development

```shell
uv venv .venv
uv pip install --python .venv/bin/python -e ".[dev]"
.venv/bin/pytest
```

Tests that require a hypervisor are skipped automatically when `/dev/kvm` (or `/dev/mshv`) is
unavailable.

## References

- [Hyperlight project site](https://hyperlight.org/) — official docs and getting-started guide
- [hyperlight-dev/hyperlight](https://github.com/hyperlight-dev/hyperlight) — the VMM itself
- [hyperlight-dev/hyperlight-sandbox](https://github.com/hyperlight-dev/hyperlight-sandbox) — the
  multi-backend sandbox framework this tool wraps
- [hyperlight-dev/hyperlight-wasm](https://github.com/hyperlight-dev/hyperlight-wasm) — the Wasm
  component backend
- [Microsoft Agent Framework Hyperlight integration](https://github.com/microsoft/agent-framework/tree/main/python/packages/hyperlight) —
  the canonical `agent-framework-hyperlight` package this tool mirrors
- [Microsoft Learn: Hyperlight integration](https://learn.microsoft.com/en-us/agent-framework/integrations/hyperlight)
- [`hyperlight-sandbox` on PyPI](https://pypi.org/project/hyperlight-sandbox/)

## License

Apache-2.0. Hyperlight is a [CNCF](https://cncf.io/) sandbox project.
