"""Prebuilt shell tool — sandboxed command execution.

Requires a SandboxSession in the handler context.
"""

from __future__ import annotations

from typing import Any


async def create_handler(*, session: Any = None, **kwargs: Any) -> Any:
    """Factory: return a sandboxed shell handler."""

    async def shell(command: str) -> str:
        if session is None:
            return "Error: No sandbox session available. Configure 'sandbox' in the agent YAML."
        result = await session.run(command=command)
        output = result.stdout
        if result.stderr:
            output += f"\n[stderr]\n{result.stderr}"
        if result.timed_out:
            output += "\n[TIMED OUT]"
        if not result.sandboxed:
            output = "[WARNING: Ran without sandbox]\n" + output
        return output

    return shell
