Skip to content

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

⚠️ 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.

langchain-hyperlight

A LangChain tool that executes untrusted code inside a Microsoft 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.

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

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

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 (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:

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:

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(...):

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:

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.

Installing on Linux

The package 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):

    grep -E 'vmx|svm' /proc/cpuinfo
  2. Ensure the KVM device exists (the kvm_amd/kvm_intel module is loaded):

    ls -l /dev/kvm

    If it is missing, the module is not loaded — 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:

    sudo usermod -aG kvm $USER
    # log out and back in, then verify:
    groups
  4. Install the package in a venv:

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

Immutable distros (Bluefin / Fedora Silverblue)

On ostree-based immutable distros, the kvm group lives in the immutable /usr/lib/group, so usermod alone has no effect. Copy the group into the writable /etc/group first:

sudo sh -c 'grep -E "^kvm:" /usr/lib/group >> /etc/group'
sudo usermod -aG kvm $USER
getent group kvm   # must show: kvm:x:36:qemu,aion

Also, never layer Python packages system-wide on an immutable image — use uv, pipx, or a distrobox/toolbox container:

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

Development

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

License

Apache-2.0. Hyperlight is a CNCF sandbox project.

About

Langchain tool for running code on Microsoft's Hyperlight

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages