Run the commands and servers your agent starts, with time limits, output limits, sandboxing, and guaranteed cleanup.
When an agent calls a tool, the tool often starts a local process: a shell command, a test run, a dev server, an MCP server. Those processes can hang, print gigabytes, spawn children that outlive the agent, or touch files and networks they shouldn't. Agent Supervisor is the layer your application calls to start them instead of spawning them directly. It:
- stops runaway work: deadlines, cancellation, and a TERM → grace → KILL shutdown that takes the whole process tree with it;
- bounds output: stdout, stderr, and stdin are capped, so a noisy tool can't exhaust memory;
- sandboxes: a cleared environment, filesystem grants, no network or loopback-only network, and memory, process-count, and CPU limits, using each operating system's native mechanism;
- reports what happened: every process ends with a structured result: exit code or signal, timeout, cancellation, and how much of the policy the platform actually enforced;
- cleans up after an agent run: processes started during a framework call are stopped when the call ends, fails, or is cancelled.
It works on Linux, macOS, and Windows, from Python, Rust, and Node.js, either embedded in your application or as a separate service that keeps processes alive while clients disconnect and reconnect.
Agent Supervisor does not run models or decide which tools to call. Your application and agent framework keep doing that; Agent Supervisor only runs the processes you ask it to run.
An MCP server and three agent workers (Codex, Claude Code, LangGraph) start under the Supervisor; the first worker finishes and its run is recorded as succeeded.
📖 Full documentation: https://rooagi.github.io/agent-supervisor/
- Install
- Run your first command
- Limit time and output
- Restrict files and network
- Clean up after an agent run
- Keep a server running
- Run it as a service
- Watch processes in the terminal
- Platform support
- Where to go next
| Language | Install |
|---|---|
| Python 3.9+ | pip install agent-supervisor |
| Rust | cargo add agent-supervisor and cargo add tokio --features macros,rt-multi-thread |
| Node.js 18+ | npm install @rooagi/agent-supervisor |
Python framework adapters are optional extras: openai, microsoft,
langgraph, pydantic-ai, google-adk, mcp, and fastmcp, for example
pip install 'agent-supervisor[openai]'. The npm package ships prebuilt
bindings for Linux (x64, arm64, glibc), macOS (x64, arm64), and Windows (x64);
on other platforms, build from source with Rust (see the
Node.js client guide).
run() starts one command, waits for it, and returns its result. Commands are
an argument list, never a shell string, and the executable must be an absolute
path.
import asyncio
import sys
from agent_supervisor import Command, Policy, run
async def main():
result = await run(
Command([sys.executable, "-c", "print('hello from a supervised process')"]),
policy=Policy(),
)
print(result.termination, result.exit_code) # exited 0
print(result.stdout.decode()) # hello from a supervised process
asyncio.run(main())Rust
use agent_supervisor::{run, Command, Policy};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let command = Command {
argv: vec!["/bin/echo".into(), "hello from a supervised process".into()],
cwd: None,
};
let result = run(&command, &Policy::default()).await?;
println!("{:?}", result.termination); // Exited { code: Some(0), signal: None }
print!("{}", String::from_utf8_lossy(&result.stdout));
Ok(())
}Node.js
import { Command, Policy, run } from '@rooagi/agent-supervisor'
const result = await run(
new Command([process.execPath, '-e', "console.log('hello from a supervised process')"]),
{ policy: new Policy() }
)
console.log(result.termination) // { Exited: { code: 0, signal: null } }
process.stdout.write(result.stdout)Every result tells you how the process ended (termination: exited, killed by
a signal, timed out, cancelled), its captured stdout and stderr, which
executable actually ran, and whether the policy was fully enforced or only
partly (enforcement).
Without any configuration, a one-shot command gets 5 seconds and keeps at
most 64 KiB of stdout and 16 KiB of stderr. In Python these limits are
set on the Command:
result = await run(
Command(
["/usr/bin/make", "test"],
cwd="/workspace/project",
timeout=120.0, # seconds
max_stdout_bytes=1_000_000,
max_stderr_bytes=256_000,
),
policy=Policy(),
)
if result.termination == "timed_out":
print("tests took longer than two minutes and were stopped")When the deadline passes, the whole process tree is stopped, not just the
first process. In Rust and Node.js the same limits live in the policy's
limits (timeout_ms/timeoutMs, output_bytes/outputBytes, and so on),
next to the optional memory_bytes, max_processes, and cpu_quota_micros.
The default Policy() is permissive for compatibility: host network and no
filesystem restriction. The child's environment is always cleared; pass the
variables a tool needs explicitly. Narrow the rest for tools you don't fully
trust:
import os
import sys
from agent_supervisor import Command, Policy, run
policy = Policy(
network="disabled", # "host" (default), "disabled", or "loopback"
enforcement="required", # fail instead of running with weaker isolation
filesystem=[
("/workspace/project", ["read", "write"]),
(os.path.realpath(sys.base_prefix), ["read"]), # the interpreter itself
],
)
result = await run(Command([sys.executable, "-I", "/workspace/project/tool.py"]), policy=policy)- Filesystem: once you pass
filesystem, the child can only use the directory trees you grant (read,write,append). On macOS the system directories (/usr,/bin,/System) stay readable; on Linux they don't, so grant whatever the tool itself needs to load. - Network:
"disabled"blocks IP networking (local Unix sockets still work)."loopback"lets a tool run and reach a local server, such as a dev server and its tests, while blocking connections to other machines. - Enforcement: with
"best_effort"(the default) a command still runs when the platform can't apply part of the policy, and the result says so; with"required"it fails instead. Callplatform_capabilities()to see what the current machine supports.
See the security model and filesystem and network for each platform's exact guarantees.
An agent run wraps one call into your agent framework. It gives the call a deadline, and every process its tools start through the run is stopped when the call finishes, fails, or is cancelled. Nothing is left behind.
With a framework adapter, it is one argument. For the OpenAI Agents SDK
(pip install 'agent-supervisor[openai]'):
import asyncio
from agents import Agent
from agent_supervisor import Supervisor
from agent_supervisor.openai import Runner
agent = Agent(name="Assistant", instructions="Answer the user's question clearly.")
async def main():
supervisor = Supervisor()
try:
result = await Runner.run(agent, "What does Agent Supervisor do?", supervisor=supervisor)
print(result.final_output)
finally:
await supervisor.shutdown_all()
asyncio.run(main())Adapters exist for the OpenAI Agents SDK, Microsoft Agent Framework, LangGraph, PydanticAI, and Google ADK in Python, and for the OpenAI Agents SDK, LangChain.js, LangGraph.js, Vercel AI SDK, and Google ADK in Node.js. Without an adapter, use an agent run directly and start tool commands through it:
from agent_supervisor import AgentRunPolicy, Command, Policy, Supervisor
supervisor = Supervisor()
async with supervisor.start_agent_run(AgentRunPolicy(timeout=300)) as agent_run:
# inside a tool:
result = await agent_run.run_command(Command(["/usr/bin/git", "status"], cwd="/workspace/project"), policy=Policy())
# leaving the block stops anything the run still ownsSee agent runs and SDK adapters.
Some tools start something that should outlive a single tool call, such as a
dev server or a language server. Start it as a background job: it belongs to
the Supervisor, not to one agent run, and keeps running until you stop it.
import sys
from agent_supervisor import Command, Policy, Supervisor
supervisor = Supervisor()
job = await supervisor.start_background(
Command([sys.executable, "-m", "http.server", "8000"], cwd="/workspace/site"),
policy=Policy(network="loopback"),
)
print(supervisor.process_status(job)) # running
# later
await supervisor.shutdown_process(job, grace=2.0)
result = await supervisor.wait_process(job)supervisor.shutdown_all() stops every remaining job when your application
exits. To supervise a local MCP server, see the
MCP guide; for interactive
terminals and connected pipelines, see the
Rust and
Python API references.
In embedded mode, processes belong to your application and stop when it does.
agent-supervisor-service is a separate process that owns them instead, so a
desktop app or agent host can restart or disconnect and reattach to processes
that are still running. Clients authenticate with role tokens over a Unix
socket. The service is available on Linux and macOS; on Windows use embedded
mode.
1. Build it and create credentials (once):
cargo build --release --bin agent-supervisor-service
target/release/agent-supervisor-service --init-credentials-dir ~/.config/agent-supervisorThis writes three tokens: view.token (read only), control.token (start and
stop processes), and tui.token (the terminal manager).
2. Start the service:
target/release/agent-supervisor-service \
--socket "$XDG_RUNTIME_DIR/agent-supervisor.sock" \
--view-token-file ~/.config/agent-supervisor/view.token \
--control-token-file ~/.config/agent-supervisor/control.token \
--tui-token-file ~/.config/agent-supervisor/tui.token \
--state-dir ~/.local/state/agent-supervisor--state-dir is optional: with it, the service records runs and their outcomes
so they survive a restart of the service.
3. Connect and start a process (Python shown; Rust and Node.js have matching clients):
import os
from agent_supervisor import SupervisorServiceClient
client = await SupervisorServiceClient.connect(
os.path.expandvars("$XDG_RUNTIME_DIR/agent-supervisor.sock"),
token_path=os.path.expanduser("~/.config/agent-supervisor/control.token"),
role="control",
)
process = await client.start_process(
"/bin/echo",
args=["hello from the service"],
policy={
"environment": {"inherit": [], "variables": {}, "executableSearchPaths": []},
"filesystem": None,
"network": "host",
"limits": {"timeoutMs": 30000, "inputBytes": 65536, "outputBytes": 65536, "stderrBytes": 16384},
"enforcement": "best_effort",
},
)
print(process.process_id) # stable ID; reattach with client.attach_process(...)
async for event in process.events():
print(event.type, event.data) # processStarted, stdout b'hello from the service\n', exitedCheck on it or stop it from the command line:
agent-supervisor-service --status --socket "$XDG_RUNTIME_DIR/agent-supervisor.sock" --view-token-file ~/.config/agent-supervisor/view.token
agent-supervisor-service --shutdown --socket "$XDG_RUNTIME_DIR/agent-supervisor.sock" --control-token-file ~/.config/agent-supervisor/control.tokenThe service also runs a coordinator that records agent runs, their activities and attempts, with an ordered event stream clients can subscribe to. See the Supervisor guide, the run coordinator, and the Node.js client guide.
agent-supervisor-tui shows every managed process with its state, PID, and
labels, alongside active and recent agent runs. You can inspect a process or
stop it from the keyboard.
cargo build --manifest-path tui/Cargo.toml --release
tui/target/release/agent-supervisor-tui \
--service-socket "$XDG_RUNTIME_DIR/agent-supervisor.sock" \
--token-file ~/.config/agent-supervisor/tui.token --role tuiKeys: j/k to move, i for details, s to stop the selected process, a
to stop all, ? for help, q to quit. An embedded Supervisor can launch the
same dashboard with start_tui(). See the
terminal process manager guide.
| Capability | Linux | macOS | Windows |
|---|---|---|---|
| Process-tree cleanup | Process groups, cgroup v2 | Process groups | Job Objects |
| Memory, process, and CPU limits | cgroup v2 | Partial; see platform_capabilities() |
Job Objects |
| Filesystem isolation | Landlock | Seatbelt (sandbox-exec) |
AppContainer |
network="disabled" |
✓ | ✓ | ✓, with a filesystem policy |
network="loopback" |
✓, private network namespace | ✓ ¹ | Not supported |
| Interactive terminals (PTY) | ✓ | ✓ | ConPTY |
| Service mode | ✓ | ✓ | Embedded mode only |
¹ On macOS a tool that listens on every interface (0.0.0.0) in loopback mode
can still accept connections from other machines; listen on 127.0.0.1.
Linux has no such gap: it needs unprivileged user namespaces and refuses the
command where they are disabled.
Enforcement always depends on the host. When it matters, check
platform_capabilities() and use enforcement="required".
| I want to… | Read |
|---|---|
| Try every API in all three languages | Quickstart |
| Understand commands, policies, and results | Core concepts |
| Plug it into my agent framework | Agent runs and SDK adapters |
| Supervise MCP servers | MCP servers |
| Know exactly what is isolated | Security model |
| Look up a type or method | Rust API · Python API · Node.js |
| Run untrusted WebAssembly instead of native code | WebAssembly runner (Rust, opt-in wasm feature) |
| See runnable programs | examples/ |
| See what changed | Release notes |
An experimental adapter for NVIDIA OpenShell sandboxes lives in
dev/openshell-adapter/, outside the published packages; read its
contract first.
Before opening a pull request, run:
cargo fmt --all -- --check
cargo test --all-targets -- --test-threads=1
cargo clippy --all-targets -- -D warningsPlatform integration tests must run on their own operating system; cross-compiling doesn't replace native Linux, macOS, and Windows runs. See testing and coverage. Releases are published by pushing a version tag; see how to release.
