modal_sandbox(
*,
app_name: str = "agents-codex-sdk",
timeout: int = 300,
) -> AsyncIterator[Sandbox]
Start a direct executor in /workspace and wait for termination on exit.
Install the codex-modal extra and configure MODAL_TOKEN_ID and MODAL_TOKEN_SECRET
or a Modal profile. The app is reused across runs. Each call gets a fresh
VM with a lifetime capped at timeout seconds. Use modal.Sandbox.from_id
with the yielded ID to transfer files while the executor is running.
Source code in src/openai_agents/codex/extensions/modal.py
| @asynccontextmanager
async def modal_sandbox(
*, app_name: str = "agents-codex-sdk", timeout: int = 300
) -> AsyncIterator[Sandbox]:
"""Start a direct executor in /workspace and wait for termination on exit.
Install the codex-modal extra and configure MODAL_TOKEN_ID and MODAL_TOKEN_SECRET
or a Modal profile. The app is reused across runs. Each call gets a fresh
VM with a lifetime capped at timeout seconds. Use modal.Sandbox.from_id
with the yielded ID to transfer files while the executor is running.
"""
try:
modal = import_module("modal")
probe = import_module("modal.sandbox").Probe
except ImportError as error:
raise ImportError("Install the SDK wheel with the codex-modal extra.") from error
if "runtime" not in inspect.signature(modal.Sandbox.create).parameters:
raise ImportError(
"Codex VM sandboxes require the codex-modal extra. "
"Use a separate environment for Classic's modal extra."
)
app = await modal.App.lookup.aio(app_name, create_if_missing=True)
image = (
modal.Image.debian_slim(python_version="3.12")
.apt_install("bubblewrap", "ripgrep")
.pip_install(f"openai-codex-cli-bin=={codex_version()}")
.workdir(_WORKSPACE)
)
token = secrets.token_urlsafe(32)
remote = await modal.Sandbox.create.aio(
"python",
"-c",
_LAUNCH_CODEX,
*server_args(f"ws://0.0.0.0:{_PORT}", digest(token)),
app=app,
image=image,
# Codex uses Bubblewrap, which needs Linux user namespaces.
runtime="vm",
encrypted_ports=[_PORT],
readiness_probe=probe.with_tcp(_PORT),
timeout=timeout,
)
try:
await remote.wait_until_ready.aio(timeout=60)
tunnels = await remote.tunnels.aio()
host, port = tunnels[_PORT].tls_socket
yield Sandbox(id=remote.object_id, url=f"wss://{host}:{port}", cwd=_WORKSPACE, token=token)
finally:
try:
await remote.terminate.aio(wait=True)
finally:
await remote.detach.aio()
|