DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(sandbox): support Windows code execution (#964)
john00010dcbb1d339312
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.pyindex dff3b0a4a..c3562c799 100644--- a/deeptutor/agents/chat/agentic_pipeline.py+++ b/deeptutor/agents/chat/agentic_pipeline.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport asyncioimport logging+import sysfrom typing import Anyfrom deeptutor.agents._shared.tool_composition import (@@ -1601,23 +1602,55 @@ class AgenticChatPipeline:)except Exception:return ""++ # Only the "how do I get a script into a file" clause depends on the+ # host shell; everything else in the note is identical, so vary that+ # one clause rather than duplicating the whole paragraph per platform.+ is_windows = sys.platform == "win32"if self.language == "zh":+ how_to_write = (+ (+ "通过 exec 使用 PowerShell here-string 将脚本写入文件再运行,例如:\n"+ " @'\n...Python 脚本内容...\n'@ | Set-Content -Encoding utf8 gen.py\n"+ " python gen.py\n"+ "不要使用 bash heredoc(<<'PY')或 POSIX 重定向语法——当前为 Windows 环境。"+ )+ if is_windows+ else (+ "直接通过 exec 写入并运行脚本(如 heredoc:python - <<'PY' … PY,"+ "或 cat > gen.py <<'EOF' … EOF 后再运行)。"+ )+ )return ("[本轮工作区]\n"f"脚本和临时文件应写入:{exec_dir}\n""相对路径会解析到这个目录。需要创建 PDF、图片、表格或其他下载文件时,"- "直接通过 exec 写入并运行脚本(如 heredoc:python - <<'PY' … PY,"- "或 cat > gen.py <<'EOF' … EOF 后再运行)。生成的文件会自动以可下载"- "卡片呈现给用户——在回答里描述你做了什么即可,不要粘贴原始 URL。"+ f"{how_to_write}"+ "生成的文件会自动以可下载卡片呈现给用户——在回答里描述你做了什么即可,"+ "不要粘贴原始 URL。"+ )+ how_to_write = (+ (+ "write the script to a file through exec with a PowerShell "+ "here-string, then run it, for example:\n"+ " @'\n...Python script contents...\n'@ | Set-Content -Encoding utf8 gen.py\n"+ " python gen.py\n"+ "Do not use Bash heredoc (<<'PY') or POSIX redirection syntax; "+ "this is a Windows environment. ")+ if is_windows+ else (+ "write and run scripts directly through exec (e.g. a heredoc: "+ "python - <<'PY' … PY, or cat > gen.py <<'EOF' … EOF then run it). "+ )+ )return ("[Turn workspace]\n"f"Scripts and temporary files should be written under: {exec_dir}\n""Relative paths resolve to this directory. When creating PDFs, images, "- "spreadsheets, or other downloadable files, write and run scripts directly "- "through exec (e.g. a heredoc: python - <<'PY' … PY, or cat > gen.py <<'EOF' "- "… EOF then run it). Generated files are shown to the user automatically as "- "downloadable cards — describe what you made, do not paste raw URLs."+ f"spreadsheets, or other downloadable files, {how_to_write}"+ "Generated files are shown to the user automatically as downloadable "+ "cards — describe what you made, do not paste raw URLs.")def _t(self, key: str, default: str = "", **kwargs: Any) -> str:diff --git a/deeptutor/services/sandbox/backends.py b/deeptutor/services/sandbox/backends.pyindex a434a2fc0..7c81e2ca9 100644--- a/deeptutor/services/sandbox/backends.py+++ b/deeptutor/services/sandbox/backends.py@@ -249,7 +249,33 @@ class RestrictedSubprocessBackend(SandboxBackend):level = IsolationLevel.APPLICATION- _SAFE_ENV_KEYS = ("PATH", "HOME", "LANG", "LC_ALL", "TMPDIR")+ _SAFE_ENV_KEYS = ("PATH", "PATHEXT", "HOME", "LANG", "LC_ALL", "TMPDIR", "SYSTEMROOT")++ @staticmethod+ def _powershell_executable() -> str:+ """Return the PowerShell executable available on PATH.++ Prefer ``pwsh`` (PowerShell 7+) when present: it defaults to UTF-8 and+ is the version still receiving updates. The commands we generate are+ written for Windows PowerShell 5.1 syntax, which 7 also accepts, so+ either host works.+ """+ return (+ shutil.which("pwsh")+ or shutil.which("powershell.exe")+ or shutil.which("powershell")+ or "powershell.exe"+ )++ @staticmethod+ def _powershell_command(command: str) -> str:+ # PowerShell 5 defaults to the active console code page. Force UTF-8+ # before running model-authored commands so Chinese output survives the+ # byte-oriented asyncio pipe consistently.+ return (+ "$OutputEncoding = [Console]::OutputEncoding = "+ "[System.Text.UTF8Encoding]::new($false); " + command+ )async def exec(self, request: ExecRequest) -> ExecResult:env = {k: os.environ[k] for k in self._SAFE_ENV_KEYS if k in os.environ}@@ -264,6 +290,18 @@ class RestrictedSubprocessBackend(SandboxBackend):cwd=cwd,env=env,)+ elif sys.platform == "win32":+ process = await asyncio.create_subprocess_exec(+ self._powershell_executable(),+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ self._powershell_command(request.command),+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ cwd=cwd,+ env=env,+ )else:process = await asyncio.create_subprocess_shell(request.command,@@ -281,7 +319,27 @@ async def _communicate(process: asyncio.subprocess.Process, timeout_s: int) -> Etry:stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout_s)except asyncio.TimeoutError:- process.kill()+ if sys.platform == "win32" and process.pid:+ # ``Process.kill`` only terminates powershell.exe; taskkill's /T+ # flag also tears down python/compiler children started by it.+ try:+ killer = await asyncio.create_subprocess_exec(+ "taskkill",+ "/PID",+ str(process.pid),+ "/T",+ "/F",+ stdout=asyncio.subprocess.DEVNULL,+ stderr=asyncio.subprocess.DEVNULL,+ )+ with suppress(asyncio.TimeoutError):+ await asyncio.wait_for(killer.wait(), timeout=5.0)+ except OSError:+ # Extremely unusual (PATH corruption / stripped-down host),+ # but still return a timeout result instead of masking it.+ process.kill()+ else:+ process.kill()with suppress(asyncio.TimeoutError):await asyncio.wait_for(process.wait(), timeout=5.0)return ExecResult(timed_out=True, exit_code=124)diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.pyindex e2e485f04..7575c3cc4 100644--- a/deeptutor/tools/builtin/__init__.py+++ b/deeptutor/tools/builtin/__init__.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport asyncioimport jsonimport logging+import sysfrom typing import Anyfrom deeptutor.capabilities.ima import IMA_TOOL_TYPES@@ -305,6 +306,35 @@ class CodeExecutionTool(_PromptHintsMixin, BaseTool):"cc": "c",}+ @classmethod+ def _command_for_platform(cls, language: str, *, has_stdin: bool) -> str:+ """Build the shell command understood by the selected host platform."""+ if sys.platform != "win32":+ source_name, command_template = cls._LANGUAGES[language]+ stdin_redirect = "< stdin.txt" if has_stdin else ""+ return command_template.format(src=source_name, stdin=stdin_redirect).strip()++ commands = {+ "python": "python main.py",+ # Use syntax supported by Windows PowerShell 5 as well as 7;+ # ``&&`` only exists in PowerShell 7.+ "c": "gcc main.c -O2 -o prog.exe; if ($LASTEXITCODE -eq 0) { .\\prog.exe }",+ "cpp": "g++ -std=c++17 -O2 main.cpp -o prog.exe; if ($LASTEXITCODE -eq 0) { .\\prog.exe }",+ }+ command = commands[language]+ # PowerShell's pipeline supplies stdin without relying on POSIX `<`.+ if not has_stdin:+ return command+ if language == "python":+ return "Get-Content stdin.txt | python main.py"+ compiler, source = ("gcc", "main.c") if language == "c" else ("g++", "main.cpp")+ flags = "-O2" if language == "c" else "-std=c++17 -O2"+ return (+ "$stdinText = Get-Content -Raw stdin.txt; "+ f"{compiler} {flags} {source} -o prog.exe; "+ "if ($LASTEXITCODE -eq 0) { $stdinText | .\\prog.exe }"+ )+def get_definition(self) -> ToolDefinition:return ToolDefinition(name="code_execution",@@ -368,7 +398,7 @@ class CodeExecutionTool(_PromptHintsMixin, BaseTool):if not code:raise ValueError("code_execution requires non-empty 'code'.")language = self._resolve_language(kwargs.get("language"))- source_name, command_template = self._LANGUAGES[language]+ source_name, _ = self._LANGUAGES[language]try:timeout = int(kwargs.get("timeout") or 30)@@ -396,11 +426,10 @@ class CodeExecutionTool(_PromptHintsMixin, BaseTool):run_dir.mkdir(parents=True, exist_ok=True)(run_dir / source_name).write_text(code, encoding="utf-8")- stdin_redirect = ""- if str(kwargs.get("stdin") or "") != "":+ has_stdin = str(kwargs.get("stdin") or "") != ""+ if has_stdin:(run_dir / "stdin.txt").write_text(str(kwargs["stdin"]), encoding="utf-8")- stdin_redirect = "< stdin.txt"- command = command_template.format(src=source_name, stdin=stdin_redirect).strip()+ command = self._command_for_platform(language, has_stdin=has_stdin)limits = ResourceLimits(timeout_s=timeout)request = ExecRequest(@@ -414,7 +443,7 @@ class CodeExecutionTool(_PromptHintsMixin, BaseTool):# The source file, compiled binary, and stdin scratch are inputs we# wrote ourselves — exclude them so only program-generated files# surface as artifacts.- meta_files = {source_name, "prog", "stdin.txt"}+ meta_files = {source_name, "prog", "prog.exe", "stdin.txt"}artifacts = [artifactfor artifact in collect_public_artifacts(str(run_dir))diff --git a/tests/agents/chat/test_workspace_system_note.py b/tests/agents/chat/test_workspace_system_note.pynew file mode 100644index 000000000..a357c994f--- /dev/null+++ b/tests/agents/chat/test_workspace_system_note.py@@ -0,0 +1,79 @@+"""The turn-workspace note must describe the host shell the model will get.++`exec` runs through PowerShell on Windows and a POSIX shell elsewhere, so the+note has to teach the matching way to write a script to a file — a Bash heredoc+is a syntax error in PowerShell, and the model would silently produce no file.+Everything else in the note is host-independent and must stay identical, which+is what keeps the two variants from drifting apart.+"""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace++import pytest++from deeptutor.agents.chat import agentic_pipeline+from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline+++def note(monkeypatch: pytest.MonkeyPatch):+ def render(*, language: str, platform: str) -> str:+ monkeypatch.setattr(agentic_pipeline.sys, "platform", platform)+ monkeypatch.setattr(+ AgenticChatPipeline,+ "_workspace_key",+ staticmethod(lambda context: "session-1"),+ )+ monkeypatch.setattr(+ "deeptutor.services.path_service.get_path_service",+ lambda: SimpleNamespace(+ get_task_workspace=lambda *a, **k: Path("/tmp/ws"),+ ),+ )+ pipeline = SimpleNamespace(+ _exec_enabled=True,+ language=language,+ _workspace_key=lambda context: "session-1",+ )+ return AgenticChatPipeline._workspace_system_note(pipeline, object())++ return render++[email protected]("language", ["en", "zh"])+def test_windows_note_teaches_powershell_not_heredoc(note, language: str) -> None:+ windows = note(language=language, platform="win32")+ assert "Set-Content" in windows+ assert "python gen.py" in windows+ # A Bash heredoc as the *instruction* is what breaks on Windows; the note+ # may name it only to tell the model not to use it.+ assert "python - <<'PY'" not in windows++[email protected]("language", ["en", "zh"])+def test_posix_note_teaches_heredoc_and_never_powershell(note, language: str) -> None:+ posix = note(language=language, platform="linux")+ assert "python - <<'PY'" in posix+ assert "Set-Content" not in posix+ assert "PowerShell" not in posix++[email protected]("language", ["en", "zh"])+def test_host_independent_guidance_is_identical(note, language: str) -> None:+ """Only the script-writing clause may differ between hosts."""+ windows = note(language=language, platform="win32")+ posix = note(language=language, platform="linux")+ for shared in ("/tmp/ws", "exec"):+ assert shared in windows and shared in posix+ tail = "不要粘贴原始 URL。" if language == "zh" else "do not paste raw URLs."+ assert windows.endswith(tail) and posix.endswith(tail)+ header = "[本轮工作区]" if language == "zh" else "[Turn workspace]"+ assert windows.startswith(header) and posix.startswith(header)+++def test_note_is_empty_when_exec_is_disabled(monkeypatch: pytest.MonkeyPatch) -> None:+ pipeline = SimpleNamespace(_exec_enabled=False, language="en")+ assert AgenticChatPipeline._workspace_system_note(pipeline, object()) == ""diff --git a/tests/core/test_builtin_tools.py b/tests/core/test_builtin_tools.pyindex 12be382d6..efb569dcb 100644--- a/tests/core/test_builtin_tools.py+++ b/tests/core/test_builtin_tools.py@@ -301,6 +301,18 @@ async def test_code_execution_tool_compiles_cpp(tmp_path, monkeypatch: pytest.Moassert captured["command"] == "c++ -std=c++17 -O2 main.cpp -o prog && ./prog"+def test_code_execution_tool_uses_windows_shell_syntax(monkeypatch: pytest.MonkeyPatch) -> None:+ import deeptutor.tools.builtin as builtin++ monkeypatch.setattr(builtin.sys, "platform", "win32")++ assert CodeExecutionTool._command_for_platform("python", has_stdin=False) == "python main.py"+ assert (+ CodeExecutionTool._command_for_platform("cpp", has_stdin=True)+ == "$stdinText = Get-Content -Raw stdin.txt; g++ -std=c++17 -O2 main.cpp -o prog.exe; if ($LASTEXITCODE -eq 0) { $stdinText | .\\prog.exe }"+ )++@pytest.mark.asyncioasync def test_code_execution_tool_rejects_bad_input() -> None:tool = CodeExecutionTool()