Last active
August 12, 2026 09:34
-
-
Save samuelcolvin/bae1f0017137239396283270325ea19c to your computer and use it in GitHub Desktop.
CLI for hackmonty.com
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env -S uv run --script | |
| # /// script | |
| # requires-python = ">=3.10" | |
| # dependencies = ["pydantic-monty-client>=0.0.21", "rich"] | |
| # /// | |
| """CLI for Hack Monty round 3 - https://hackmonty.com. | |
| Submits a local Python file to the sandbox and drives the run end to end. A | |
| second local Python file may supply module-level names used to resolve external | |
| function calls and name lookups the sandbox hands back to the client, and | |
| `--mount` exposes local directories to the sandbox's filesystem calls. | |
| Hackmonty is a `monty-server` deployment, so this speaks its own protocol | |
| rather than an HTTP one: `AsyncMontyWebsocket` opens the session and | |
| `feed_run` drives the whole pause/resume loop - host calls (sync and async), | |
| name lookups, and futures settled concurrently. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import asyncio | |
| import functools | |
| import hashlib | |
| import importlib.util | |
| import inspect | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import time | |
| from pathlib import Path | |
| from types import ModuleType | |
| from typing import Any, cast | |
| from rich.console import Console | |
| from rich.pretty import Pretty | |
| from pydantic_monty import ( | |
| AsyncMontyWebsocket, | |
| MontyCrashedError, | |
| MontyDisconnectError, | |
| MontyError, | |
| MontyRuntimeError, | |
| MontyShutdown, | |
| MontySyntaxError, | |
| MontyTypingError, | |
| MountDir, | |
| ResourceLimits, | |
| ) | |
| DEFAULT_URL = 'wss://hackmonty.com' | |
| # `--mount` mode names as `monty` spells them, mapped to the client's own | |
| MOUNT_MODES: dict[str, Any] = {'ro': 'read-only', 'rw': 'read-write', 'overlay': 'overlay'} | |
| async def main( | |
| code: str, | |
| globals: ModuleType, | |
| *, | |
| url: str = DEFAULT_URL, | |
| console: Console | None = None, | |
| user_secret: str | None = None, | |
| type_check: bool = False, | |
| type_check_stubs: str | None = None, | |
| limits: ResourceLimits | None = None, | |
| mounts: list[MountDir] | None = None, | |
| request_timeout: float | None = 60.0, | |
| ) -> Any: | |
| """Run `code` against hackmonty, resolving undefined names from `globals`. | |
| If `console` is provided, progress is printed to it for every external | |
| function the sandbox calls and every line it prints. If `user_secret` is | |
| provided, its SHA-256 hex digest names the session, so the Pydantic team can | |
| later verify from their traces that it was you who found the secret - see | |
| the "Request secret" section of `instructions.md`. | |
| If `type_check` is true the worker type-checks `code` before running it, | |
| against `type_check_stubs` (generated by `stubgen` from the globals file). | |
| `limits` are asked for, not granted: the server clamps anything above its | |
| own ceilings and applies its defaults to whatever is left out. | |
| `mounts` are served from *this* process, not the server: the sandbox | |
| suspends on each filesystem call and the client answers it out of the host | |
| directory, so nothing is uploaded and the server never sees the files. | |
| """ | |
| async with AsyncMontyWebsocket(url, request_timeout=request_timeout) as pool: | |
| # one checkout is one connection, served by a worker subprocess of its | |
| # own - the sandbox in `code`'s tracebacks is named by `script_name` | |
| async with pool.checkout( | |
| script_name=_script_name(user_secret), | |
| limits=limits, | |
| type_check=type_check, | |
| type_check_stubs=type_check_stubs, | |
| ) as session: | |
| return await session.feed_run( | |
| code, | |
| external_lookup=_external_lookup(globals, console), | |
| print_callback=_print_callback(console), | |
| mount=mounts, | |
| ) | |
| def cli() -> int: | |
| parser = argparse.ArgumentParser(description=f'Run a Python script against {DEFAULT_URL}.') | |
| # the script is positional, so the common case is `hackmonty.py prog.py`; | |
| # `--code` is the alternative for a one-liner, and exactly one is required | |
| source = parser.add_mutually_exclusive_group(required=True) | |
| source.add_argument('script', nargs='?', help='Path to a Python file to submit to the sandbox.') | |
| source.add_argument('-c', '--code', help="Python source to run instead of a file, e.g. --code '1 + 1'.") | |
| parser.add_argument( | |
| '-g', | |
| '--globals', | |
| dest='globals_path', | |
| default=None, | |
| help='Optional Python file whose module-level names resolve sandbox lookups.', | |
| ) | |
| parser.add_argument('--url', default=DEFAULT_URL, help=f'Hackmonty WebSocket URL (default: {DEFAULT_URL}).') | |
| parser.add_argument( | |
| '--user-secret', | |
| dest='user_secret', | |
| default=None, | |
| help='Plaintext secret known only to you; its SHA-256 names the session so Pydantic can verify the finder.', | |
| ) | |
| parser.add_argument( | |
| '-t', | |
| '--type-check', | |
| dest='type_check', | |
| action='store_true', | |
| help='Ask the worker to type-check the submitted code. When combined with --globals, ' | |
| 'stubgen runs over the globals file and the resulting .pyi is sent as type_check_stubs.', | |
| ) | |
| parser.add_argument( | |
| '-m', | |
| '--mount', | |
| dest='mounts', | |
| action='append', | |
| type=_mount, | |
| metavar='HOST::VIRTUAL[::MODE[::LIMIT]]', | |
| help='Mount a host directory into the sandbox, in the same format as `monty --mount`: ' | |
| '`/host/path::/virtual/path[::mode[::write_limit_bytes]]`, mode one of ro (default), rw or overlay. ' | |
| 'Repeatable. The directory is served by this process, never uploaded.', | |
| ) | |
| parser.add_argument( | |
| '--max-memory-mib', | |
| dest='max_memory_mib', | |
| type=int, | |
| default=None, | |
| help='Sandbox heap ceiling in MiB (the server clamps it to its own limit).', | |
| ) | |
| parser.add_argument( | |
| '--max-duration', | |
| dest='max_duration', | |
| type=float, | |
| default=None, | |
| help='Sandbox execution ceiling in seconds (the server clamps it to its own limit).', | |
| ) | |
| parser.add_argument( | |
| '--timeout', | |
| dest='timeout', | |
| type=float, | |
| default=60.0, | |
| help='Client-side deadline for a single turn, in seconds; 0 waits forever (default: 60).', | |
| ) | |
| args = parser.parse_args() | |
| globals_path = cast('str | None', args.globals_path) | |
| type_check = cast(bool, args.type_check) | |
| console = Console() | |
| code = cast('str | None', args.code) | |
| if code is None: | |
| code = Path(cast(str, args.script)).read_text() | |
| timeout = cast(float, args.timeout) | |
| try: | |
| value, elapsed = asyncio.run( | |
| _run_timed( | |
| code, | |
| _load_globals(globals_path), | |
| url=cast(str, args.url), | |
| console=console, | |
| user_secret=cast('str | None', args.user_secret), | |
| type_check=type_check, | |
| type_check_stubs=_generate_stubs(globals_path) if type_check and globals_path else None, | |
| limits=_limits(cast('int | None', args.max_memory_mib), cast('float | None', args.max_duration)), | |
| mounts=cast('list[MountDir] | None', args.mounts), | |
| request_timeout=timeout or None, | |
| ) | |
| ) | |
| except MontySyntaxError as exc: | |
| console.print(f'[bold red]syntax error:[/bold red] {exc}') | |
| return 1 | |
| except MontyTypingError as exc: | |
| console.print('[bold red]typing error:[/bold red]') | |
| console.out(exc.display(), highlight=False) | |
| return 1 | |
| except MontyRuntimeError as exc: | |
| console.print(f'[bold red]runtime error:[/bold red] {exc}') | |
| print(exc.display(), file=sys.stderr) | |
| return 1 | |
| # everything the server itself can do to a session: drain, a policy | |
| # deadline, over-capacity, a worker that died. None of them are `code`'s | |
| # fault, so they are reported without a traceback. | |
| except (MontyShutdown, MontyDisconnectError, MontyCrashedError) as exc: | |
| console.print(f'[bold red]{type(exc).__name__}:[/bold red] {exc}') | |
| return 1 | |
| except MontyError as exc: | |
| console.print(f'[bold red]{type(exc).__name__}:[/bold red] {exc}') | |
| return 1 | |
| console.print(f'{_fmt_dt(elapsed)} [bold]output:[/bold]') | |
| console.print(Pretty(value, indent_size=2)) | |
| return 0 | |
| async def _run_timed(code: str, globals: ModuleType, **kwargs: Any) -> tuple[Any, float]: | |
| """[`main`][], timing the whole session so the CLI can report how long it took.""" | |
| start = time.monotonic() | |
| value = await main(code, globals, **kwargs) | |
| return value, time.monotonic() - start | |
| def _external_lookup(globals: ModuleType, console: Console | None) -> dict[str, Any]: | |
| """The globals module's public names, as the table the sandbox reads from. | |
| Consulted lazily by name: a callable becomes a host function the sandbox | |
| can call (coroutines included, awaited concurrently), any other value is | |
| handed over when the name is read, and a name that is missing raises | |
| `NameError` in the sandbox. Modules are skipped - an `import` in the | |
| globals file is that file's own dependency, not a name to expose. | |
| """ | |
| return { | |
| name: _reporting(name, value, console) if callable(value) else value | |
| for name, value in vars(globals).items() | |
| if not name.startswith('_') and not isinstance(value, ModuleType) | |
| } | |
| def _reporting(name: str, fn: Any, console: Console | None) -> Any: | |
| """Wraps a host function so each call the sandbox makes reaches `console`. | |
| The wrapper only watches: an exception is reported and re-raised, for the | |
| client to hand back to the sandbox as the call's exception, exactly as an | |
| unwrapped function's would be. | |
| """ | |
| if console is None: | |
| return fn | |
| if inspect.iscoroutinefunction(fn): | |
| @functools.wraps(fn) | |
| async def report_async(*args: Any, **kwargs: Any) -> Any: | |
| start = time.monotonic() | |
| try: | |
| returned = await fn(*args, **kwargs) | |
| except Exception as exc: | |
| _report(console, name, args, kwargs, start, _raised(exc)) | |
| raise | |
| _report(console, name, args, kwargs, start, f'→ {returned!r}') | |
| return returned | |
| return report_async | |
| @functools.wraps(fn) | |
| def report(*args: Any, **kwargs: Any) -> Any: | |
| start = time.monotonic() | |
| try: | |
| returned = fn(*args, **kwargs) | |
| except Exception as exc: | |
| _report(console, name, args, kwargs, start, _raised(exc)) | |
| raise | |
| _report(console, name, args, kwargs, start, f'→ {returned!r}') | |
| return returned | |
| return report | |
| def _report( | |
| console: Console, | |
| name: str, | |
| args: tuple[Any, ...], | |
| kwargs: dict[str, Any], | |
| start: float, | |
| outcome: str, | |
| ) -> None: | |
| parts = [repr(a) for a in args] + [f'{k}={v!r}' for k, v in kwargs.items()] | |
| console.print(f'{_fmt_dt(time.monotonic() - start)} [bold]host call:[/bold] {name}({", ".join(parts)}) {outcome}') | |
| def _raised(exc: BaseException) -> str: | |
| return f'[red]raised {type(exc).__name__}:[/red] {exc}' | |
| def _print_callback(console: Console | None) -> Any: | |
| """Streams the sandbox's `print()` output as it arrives, or `None` to let it | |
| fall through to this process's own stdout/stderr.""" | |
| if console is None: | |
| return None | |
| def write(stream: str, text: str) -> None: | |
| console.out(text, end='', highlight=False, style='red' if stream == 'stderr' else None) | |
| return write | |
| def _script_name(user_secret: str | None) -> str: | |
| """The name the session runs under, carrying the finder's digest when given. | |
| It is what the server's traces call the session and what the sandbox's own | |
| tracebacks name, so a digest here is the durable record that the run was | |
| yours. | |
| """ | |
| if user_secret is None: | |
| return 'hackmonty.py' | |
| return f'hackmonty-{hashlib.sha256(user_secret.encode()).hexdigest()}.py' | |
| def _mount(spec: str) -> MountDir: | |
| """One `--mount` spec, parsed exactly as `monty --mount` parses it. | |
| `host_path::virtual_path[::mode[::write_limit_bytes]]`, using `::` as the | |
| separator so Windows drive letters stay unambiguous. The host directory is | |
| opened here - a missing or unreadable one is an argument error, reported | |
| before any session is opened rather than mid-run. | |
| """ | |
| match spec.split('::'): | |
| case [host_path, virtual_path]: | |
| mode, limit = 'ro', None | |
| case [host_path, virtual_path, mode]: | |
| limit = None | |
| case [host_path, virtual_path, mode, limit]: | |
| pass | |
| case _: | |
| raise argparse.ArgumentTypeError( | |
| f'invalid mount spec {spec!r}: expected host_path::virtual_path[::mode[::write_limit_bytes]]' | |
| ) | |
| if not host_path or not virtual_path: | |
| raise argparse.ArgumentTypeError(f'invalid mount spec {spec!r}: host and virtual paths must not be empty') | |
| if mode not in MOUNT_MODES: | |
| raise argparse.ArgumentTypeError(f'invalid mount mode {mode!r} in {spec!r}: expected ro, rw or overlay') | |
| if limit is not None and not limit.isdigit(): | |
| raise argparse.ArgumentTypeError(f'invalid write limit {limit!r} in {spec!r}: expected a non-negative integer') | |
| try: | |
| return MountDir( | |
| host_path=host_path, | |
| virtual_path=virtual_path, | |
| mode=MOUNT_MODES[mode], | |
| write_bytes_limit=int(limit) if limit is not None else None, | |
| ) | |
| # a bad host path or a relative virtual path is a `TypeError` from the client | |
| except (TypeError, OSError, ValueError) as exc: | |
| raise argparse.ArgumentTypeError(f'invalid mount spec {spec!r}: {exc}') from exc | |
| def _limits(max_memory_mib: int | None, max_duration: float | None) -> ResourceLimits | None: | |
| """The limits to ask the sandbox for, or `None` to take the server's own.""" | |
| limits: ResourceLimits = {} | |
| if max_memory_mib is not None: | |
| limits['max_memory'] = max_memory_mib * 1024 * 1024 | |
| if max_duration is not None: | |
| limits['max_duration_secs'] = max_duration | |
| return limits or None | |
| def _generate_stubs(globals_path: str) -> str: | |
| """Run `stubgen` over the globals file and return the resulting .pyi text.""" | |
| print('running stubgen...') | |
| p = Path(globals_path).resolve() | |
| with tempfile.TemporaryDirectory() as tmpdir: | |
| subprocess.run( | |
| ['uv', 'run', '--with', 'mypy', 'stubgen', p.name, '--include-docstrings', '-o', tmpdir], | |
| capture_output=True, | |
| text=True, | |
| cwd=p.parent, | |
| check=True, | |
| ) | |
| print('type stubs generated') | |
| return (Path(tmpdir) / f'{p.stem}.pyi').read_text() | |
| def _load_globals(path: str | None) -> ModuleType: | |
| if path is None: | |
| return ModuleType('hackmonty_globals') | |
| spec = importlib.util.spec_from_file_location('hackmonty_globals', path) | |
| if spec is None or spec.loader is None: | |
| raise RuntimeError(f'cannot load globals module from {path}') | |
| module = importlib.util.module_from_spec(spec) | |
| spec.loader.exec_module(module) | |
| return module | |
| def _fmt_dt(dt: float) -> str: | |
| return f'[dim]{dt * 1000:>5.0f}ms →[/dim]' | |
| if __name__ == '__main__': | |
| raise SystemExit(cli()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment