|
| 1 | +# Tencent is pleased to support the open source community by making tRPC-Agent-Python available. |
| 2 | +# |
| 3 | +# Copyright (C) 2026 Tencent. All rights reserved. |
| 4 | +# |
| 5 | +# tRPC-Agent-Python is licensed under Apache-2.0. |
| 6 | +"""Sandbox execution of skill scripts via SDK workspace runtimes.""" |
| 7 | +import os |
| 8 | +import shutil |
| 9 | +import sys |
| 10 | +from dataclasses import dataclass |
| 11 | + |
| 12 | +from trpc_agent_sdk.code_executors import (WorkspacePutFileInfo, WorkspaceRunProgramSpec, |
| 13 | + WorkspaceStageOptions, |
| 14 | + create_container_workspace_runtime, |
| 15 | + create_local_workspace_runtime) |
| 16 | + |
| 17 | +SKILL_WS_DIR = "skills/code-review" |
| 18 | +DIFF_WS_PATH = "work/inputs/changes.diff" |
| 19 | +_PYTHON3_DIR = os.path.dirname(shutil.which("python3") or sys.executable) |
| 20 | +SANDBOX_ENV = {"PATH": f"{_PYTHON3_DIR}:/usr/local/bin:/usr/bin:/bin", |
| 21 | + "HOME": "/tmp", "LANG": "C.UTF-8"} |
| 22 | + |
| 23 | +RUNTIME_LOCAL = "local" |
| 24 | +RUNTIME_CONTAINER = "container" |
| 25 | +RUNTIME_CUBE = "cube" |
| 26 | + |
| 27 | + |
| 28 | +async def create_runtime(kind: str): |
| 29 | + """Create a workspace runtime. Container is the production default; |
| 30 | + local is a development-only fallback; cube needs env credentials.""" |
| 31 | + if kind == RUNTIME_LOCAL: |
| 32 | + return create_local_workspace_runtime() |
| 33 | + if kind == RUNTIME_CONTAINER: |
| 34 | + return create_container_workspace_runtime() |
| 35 | + if kind == RUNTIME_CUBE: |
| 36 | + from trpc_agent_sdk.code_executors.cube import (CubeClientConfig, |
| 37 | + CubeWorkspaceRuntimeConfig, |
| 38 | + create_cube_sandbox_client, |
| 39 | + create_cube_workspace_runtime) |
| 40 | + if not os.getenv("CUBE_API_KEY") and not os.getenv("E2B_API_KEY"): |
| 41 | + raise ValueError("cube runtime requires CUBE_API_KEY/E2B_API_KEY; " |
| 42 | + "see examples/skills_with_cube") |
| 43 | + cfg = CubeClientConfig( |
| 44 | + execute_timeout=float(os.getenv("CUBE_EXECUTE_TIMEOUT", "60")), |
| 45 | + idle_timeout=int(os.getenv("CUBE_IDLE_TIMEOUT", "600")), |
| 46 | + auto_recover=True) |
| 47 | + client = await create_cube_sandbox_client(cfg) |
| 48 | + return create_cube_workspace_runtime(sandbox_client=client, |
| 49 | + execute_timeout=cfg.execute_timeout, |
| 50 | + workspace_cfg=CubeWorkspaceRuntimeConfig()) |
| 51 | + raise ValueError(f"unknown runtime {kind!r}; expected local|container|cube") |
| 52 | + |
| 53 | + |
| 54 | +@dataclass |
| 55 | +class SandboxRunOutcome: |
| 56 | + """Result of one sandboxed script execution.""" |
| 57 | + |
| 58 | + script: str |
| 59 | + status: str # ok | failed | timeout | error |
| 60 | + exit_code: int |
| 61 | + duration_ms: int |
| 62 | + timed_out: bool |
| 63 | + stdout: str |
| 64 | + stderr: str |
| 65 | + error_type: str = "" |
| 66 | + truncated: bool = False |
| 67 | + |
| 68 | + |
| 69 | +class SandboxSession: |
| 70 | + """One workspace: staged code-review skill + staged diff + script runs.""" |
| 71 | + |
| 72 | + def __init__(self, runtime, skill_root: str, timeout_sec: float = 60.0, |
| 73 | + max_output_bytes: int = 262144): |
| 74 | + self._runtime = runtime |
| 75 | + self._skill_root = skill_root |
| 76 | + self._timeout = timeout_sec |
| 77 | + self._max_output = max_output_bytes |
| 78 | + self._ws = None |
| 79 | + self._exec_id = "" |
| 80 | + |
| 81 | + async def open(self, exec_id: str) -> None: |
| 82 | + self._exec_id = exec_id |
| 83 | + manager = self._runtime.manager(None) |
| 84 | + self._ws = await manager.create_workspace(exec_id, None) |
| 85 | + fs = self._runtime.fs(None) |
| 86 | + await fs.stage_directory(self._ws, self._skill_root, SKILL_WS_DIR, |
| 87 | + WorkspaceStageOptions(mode="copy"), None) |
| 88 | + |
| 89 | + async def put_diff(self, diff_text: str) -> None: |
| 90 | + fs = self._runtime.fs(None) |
| 91 | + await fs.put_files(self._ws, [WorkspacePutFileInfo( |
| 92 | + path=DIFF_WS_PATH, content=diff_text.encode("utf-8"), mode=0o644)], None) |
| 93 | + |
| 94 | + def _truncate(self, text: str): |
| 95 | + if len(text.encode("utf-8", errors="replace")) <= self._max_output: |
| 96 | + return text, False |
| 97 | + return text.encode("utf-8", errors="replace")[:self._max_output].decode( |
| 98 | + "utf-8", errors="replace"), True |
| 99 | + |
| 100 | + async def run_script(self, script_name: str, |
| 101 | + args: tuple = (DIFF_WS_PATH,)) -> SandboxRunOutcome: |
| 102 | + """Run one skill script under `env -i` (environment whitelist).""" |
| 103 | + env_args = [f"{k}={v}" for k, v in SANDBOX_ENV.items()] |
| 104 | + argv = ["-i", *env_args, "python3", |
| 105 | + f"{SKILL_WS_DIR}/scripts/{script_name}", *args] |
| 106 | + spec = WorkspaceRunProgramSpec(cmd="env", args=argv, env={}, cwd=".", |
| 107 | + timeout=self._timeout) |
| 108 | + try: |
| 109 | + ret = await self._runtime.runner(None).run_program(self._ws, spec, None) |
| 110 | + except Exception as ex: # noqa: BLE001 - sandbox failure must not crash the review |
| 111 | + return SandboxRunOutcome(script=script_name, status="error", exit_code=-1, |
| 112 | + duration_ms=0, timed_out=False, stdout="", |
| 113 | + stderr=str(ex)[:1024], error_type=type(ex).__name__) |
| 114 | + stdout, t1 = self._truncate(ret.stdout or "") |
| 115 | + stderr, t2 = self._truncate(ret.stderr or "") |
| 116 | + if ret.timed_out: |
| 117 | + status = "timeout" |
| 118 | + elif ret.exit_code == 0: |
| 119 | + status = "ok" |
| 120 | + else: |
| 121 | + status = "failed" |
| 122 | + return SandboxRunOutcome(script=script_name, status=status, |
| 123 | + exit_code=ret.exit_code, |
| 124 | + duration_ms=int(ret.duration * 1000), |
| 125 | + timed_out=ret.timed_out, stdout=stdout, |
| 126 | + stderr=stderr, |
| 127 | + error_type="timeout" if ret.timed_out else "", |
| 128 | + truncated=t1 or t2) |
| 129 | + |
| 130 | + async def close(self) -> None: |
| 131 | + if self._ws is None: |
| 132 | + return |
| 133 | + try: |
| 134 | + await self._runtime.manager(None).cleanup(self._exec_id, None) |
| 135 | + except Exception: # noqa: BLE001 - best-effort cleanup |
| 136 | + pass |
0 commit comments