Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(background): prevent Windows host self-termination

Haozhe Wuf56a3d398fa0
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 2a5cac804..aa3c49e13 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -68,3 +68,41 @@ jobs:
run: |
cd frontend
npx vitest run --reporter=verbose
+
+ windows-background:
+ name: ${{ matrix.name }} / Python 3.14 background lifecycle
+ runs-on: ${{ matrix.runner }}
+ timeout-minutes: 10
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - name: Windows 11 ARM64
+ runner: windows-11-arm
+ architecture: arm64
+ - name: Windows Server 2025 x64
+ runner: windows-2025
+ architecture: x64
+
+ steps:
+ # actions/checkout v7.0.1
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
+
+ # actions/setup-python v7.0.0
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97
+ with:
+ python-version: "3.14"
+ architecture: ${{ matrix.architecture }}
+ cache: pip
+
+ - name: Install focused test dependencies
+ run: python -m pip install pytest pydantic pyyaml python-dotenv
+
+ - name: Run Windows background safety regressions
+ env:
+ PYTHONPATH: agent
+ run: >-
+ python -m pytest
+ agent/tests/test_background_tools.py
+ agent/tests/test_bash_tool.py
+ -q
diff --git a/README.md b/README.md
index c21c0e9b7..aed1caed0 100644
--- a/README.md
+++ b/README.md
@@ -985,7 +985,7 @@ Interactive docs: `http://localhost:8899/docs`
For localhost development, `vibe-trading serve` keeps the browser workflow simple. For any non-local client, sensitive API endpoints require `API_AUTH_KEY`; use `Authorization: Bearer <key>` for JSON/upload requests. Browser EventSource streams are handled by the Web UI after you enter the same key once in Settings.
-Shell-capable tools (`bash` / `background_run`) are enabled only for the interactive local CLI. Every other surface — the HTTP/SSE API and the MCP server on **all** transports (stdio included) — keeps them off unless you explicitly opt in with `VIBE_TRADING_ENABLE_SHELL_TOOLS=1` (or pass `--enable-shell-tools` to `vibe-trading-mcp`). Transport type never implicitly grants shell access. Document and journal readers are limited to upload/import roots by default; place files under `agent/uploads`, `agent/runs`, `./uploads`, `./data`, `~/.vibe-trading/uploads`, or `~/.vibe-trading/imports`, or add a dedicated directory through `VIBE_TRADING_ALLOWED_FILE_ROOTS`.
+Shell-capable process tools (`bash` / `background_run` / `cancel_background`) are enabled only for the interactive local CLI. Every other surface — the HTTP/SSE API and the MCP server on **all** transports (stdio included) — keeps them off unless you explicitly opt in with `VIBE_TRADING_ENABLE_SHELL_TOOLS=1` (or pass `--enable-shell-tools` to `vibe-trading-mcp`). Transport type never implicitly grants shell access. `cancel_background` stops only the tracked task ID returned by `background_run`; broad Python process-name termination is refused because it could terminate Vibe-Trading itself. Document and journal readers are limited to upload/import roots by default; place files under `agent/uploads`, `agent/runs`, `./uploads`, `./data`, `~/.vibe-trading/uploads`, or add a dedicated directory through `VIBE_TRADING_ALLOWED_FILE_ROOTS`.
Generated backtest code runs as a local Python subprocess and can make network requests through the configured market-data loaders. Its environment is intentionally narrow: the runner keeps OS/Python basics, proxy/certificate settings, `VIBE_TRADING_ALLOWED_RUN_ROOTS`, and read-only market-data keys such as `TUSHARE_TOKEN`, `FMP_API_KEY`, `FRED_API_KEY`, and `VIBE_TRADING_IWENCAI_KEY`. It does not pass LLM provider keys, API auth tokens, shell-tool switches, broker trading secrets, or live/advisory toggles to generated strategy code by default.
diff --git a/README_ar.md b/README_ar.md
index e126be48f..dce5e7f96 100644
--- a/README_ar.md
+++ b/README_ar.md
@@ -926,7 +926,7 @@ vibe-trading serve --port 8899
للتطوير على localhost، يبقي `vibe-trading serve` سير المتصفح بسيطاً. لأي عميل غير محلي، تتطلب نقاط API الحساسة `API_AUTH_KEY`؛ استخدم `Authorization: Bearer <key>` لطلبات JSON/الرفع. تتعامل Web UI مع تدفقات Browser EventSource بعد إدخال المفتاح نفسه مرة واحدة في Settings.
-الأدوات القادرة على shell (`bash` / `background_run`) مفعّلة فقط لواجهة CLI المحلية التفاعلية. أما بقية الأسطح — واجهة HTTP/SSE و MCP server على **جميع** وسائط النقل (بما في ذلك stdio) — فتبقى معطّلة ما لم تفعّلها صراحة عبر `VIBE_TRADING_ENABLE_SHELL_TOOLS=1` (أو تمرير `--enable-shell-tools` إلى `vibe-trading-mcp`). نوع وسيط النقل لا يمنح صلاحية shell ضمنيًا أبدًا. قارئات المستندات والسجلات محدودة افتراضياً بجذور الرفع/الاستيراد؛ ضع الملفات تحت `agent/uploads` أو `agent/runs` أو `./uploads` أو `./data` أو `~/.vibe-trading/uploads` أو `~/.vibe-trading/imports`، أو أضف دليلاً مخصصاً عبر `VIBE_TRADING_ALLOWED_FILE_ROOTS`.
+الأدوات القادرة على shell (`bash` / `background_run` / `cancel_background`) مفعّلة فقط لواجهة CLI المحلية التفاعلية. أما بقية الأسطح — واجهة HTTP/SSE و MCP server على **جميع** وسائط النقل (بما في ذلك stdio) — فتبقى معطّلة ما لم تفعّلها صراحة عبر `VIBE_TRADING_ENABLE_SHELL_TOOLS=1` (أو تمرير `--enable-shell-tools` إلى `vibe-trading-mcp`). نوع وسيط النقل لا يمنح صلاحية shell ضمنيًا أبدًا. قارئات المستندات والسجلات محدودة افتراضياً بجذور الرفع/الاستيراد؛ ضع الملفات تحت `agent/uploads` أو `agent/runs` أو `./uploads` أو `./data` أو `~/.vibe-trading/uploads` أو `~/.vibe-trading/imports`، أو أضف دليلاً مخصصاً عبر `VIBE_TRADING_ALLOWED_FILE_ROOTS`.
### إعدادات Web UI
diff --git a/README_ja.md b/README_ja.md
index b0ee7f684..a95f791e1 100644
--- a/README_ja.md
+++ b/README_ja.md
@@ -923,7 +923,7 @@ Interactive docs: `http://localhost:8899/docs`
localhost 開発では、`vibe-trading serve` は browser workflow を簡単に保ちます。非ローカル client では、sensitive API endpoints に `API_AUTH_KEY` が必要です。JSON/upload requests には `Authorization: Bearer <key>` を使ってください。Browser EventSource streams は、Settings で同じ key を一度入力した後、Web UI が処理します。
-Shell-capable tools(`bash` / `background_run`)はインタラクティブな local CLI でのみ有効です。それ以外のすべての面 — HTTP/SSE API と MCP server の**すべての** transport(stdio を含む)— は、`VIBE_TRADING_ENABLE_SHELL_TOOLS=1` を明示的に設定する(または `vibe-trading-mcp` に `--enable-shell-tools` を渡す)まで無効のままです。transport の種類が暗黙に shell アクセスを許可することはありません。Document と journal readers は既定で upload/import roots に制限されます。ファイルは `agent/uploads`、`agent/runs`、`./uploads`、`./data`、`~/.vibe-trading/uploads`、`~/.vibe-trading/imports` の下に置くか、`VIBE_TRADING_ALLOWED_FILE_ROOTS` で専用 directory を追加してください。
+Shell-capable process tools(`bash` / `background_run` / `cancel_background`)はインタラクティブな local CLI でのみ有効です。それ以外のすべての面 — HTTP/SSE API と MCP server の**すべての** transport(stdio を含む)— は、`VIBE_TRADING_ENABLE_SHELL_TOOLS=1` を明示的に設定する(または `vibe-trading-mcp` に `--enable-shell-tools` を渡す)まで無効のままです。transport の種類が暗黙に shell アクセスを許可することはありません。Document と journal readers は既定で upload/import roots に制限されます。ファイルは `agent/uploads`、`agent/runs`、`./uploads`、`./data`、`~/.vibe-trading/uploads`、`~/.vibe-trading/imports` の下に置くか、`VIBE_TRADING_ALLOWED_FILE_ROOTS` で専用 directory を追加してください。
### Web UI Settings
diff --git a/README_ko.md b/README_ko.md
index 1319bdb22..a4c89afba 100644
--- a/README_ko.md
+++ b/README_ko.md
@@ -926,7 +926,7 @@ Interactive docs: `http://localhost:8899/docs`
localhost 개발에서 `vibe-trading serve`는 browser workflow를 단순하게 유지합니다. non-local client에서는 민감한 API endpoint에 `API_AUTH_KEY`가 필요합니다. JSON/upload request에는 `Authorization: Bearer <key>`를 사용하세요. Browser EventSource stream은 Web UI Settings에 같은 key를 한 번 입력하면 Web UI가 처리합니다.
-Shell-capable tools(`bash` / `background_run`)는 대화형 local CLI에서만 활성화됩니다. 그 외 모든 표면 — HTTP/SSE API와 MCP server의 **모든** transport(stdio 포함) — 는 `VIBE_TRADING_ENABLE_SHELL_TOOLS=1`을 명시적으로 설정하지 않는 한(또는 `vibe-trading-mcp`에 `--enable-shell-tools`를 전달하지 않는 한) 비활성 상태로 유지됩니다. transport 종류가 암묵적으로 shell 접근을 부여하는 일은 없습니다. Document와 journal reader는 기본적으로 upload/import roots로 제한됩니다. 파일은 `agent/uploads`, `agent/runs`, `./uploads`, `./data`, `~/.vibe-trading/uploads`, `~/.vibe-trading/imports` 아래에 두거나, `VIBE_TRADING_ALLOWED_FILE_ROOTS`로 전용 directory를 추가하세요.
+Shell-capable process tools(`bash` / `background_run` / `cancel_background`)는 대화형 local CLI에서만 활성화됩니다. 그 외 모든 표면 — HTTP/SSE API와 MCP server의 **모든** transport(stdio 포함) — 는 `VIBE_TRADING_ENABLE_SHELL_TOOLS=1`을 명시적으로 설정하지 않는 한(또는 `vibe-trading-mcp`에 `--enable-shell-tools`를 전달하지 않는 한) 비활성 상태로 유지됩니다. transport 종류가 암묵적으로 shell 접근을 부여하는 일은 없습니다. Document와 journal reader는 기본적으로 upload/import roots로 제한됩니다. 파일은 `agent/uploads`, `agent/runs`, `./uploads`, `./data`, `~/.vibe-trading/uploads`, `~/.vibe-trading/imports` 아래에 두거나, `VIBE_TRADING_ALLOWED_FILE_ROOTS`로 전용 directory를 추가하세요.
### Web UI Settings
diff --git a/README_zh.md b/README_zh.md
index c8bf7f00e..f86369338 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -950,7 +950,7 @@ vibe-trading serve --port 8899
对于 localhost 开发,`vibe-trading serve` 会保持浏览器工作流简单。对任何非本地客户端,敏感 API endpoints 都要求 `API_AUTH_KEY`;JSON/upload 请求请使用 `Authorization: Bearer <key>`。浏览器 EventSource streams 会在你于 Settings 中输入同一个 key 后由 Web UI 处理。
-Shell-capable tools(`bash` / `background_run`)仅对交互式本地 CLI 启用。其他所有入口 —— HTTP/SSE API 以及 MCP server 的**所有** transport(含 stdio)—— 默认关闭,除非你显式设置 `VIBE_TRADING_ENABLE_SHELL_TOOLS=1`(或给 `vibe-trading-mcp` 传 `--enable-shell-tools`)。transport 类型永远不会隐式授予 shell 访问权限。文档和日志读取器默认限制在 upload/import roots 内;请将文件放在 `agent/uploads`、`agent/runs`、`./uploads`、`./data`、`~/.vibe-trading/uploads` 或 `~/.vibe-trading/imports` 下,或通过 `VIBE_TRADING_ALLOWED_FILE_ROOTS` 添加专用目录。
+Shell-capable process tools(`bash` / `background_run` / `cancel_background`)仅对交互式本地 CLI 启用。其他所有入口 —— HTTP/SSE API 以及 MCP server 的**所有** transport(含 stdio)—— 默认关闭,除非你显式设置 `VIBE_TRADING_ENABLE_SHELL_TOOLS=1`(或给 `vibe-trading-mcp` 传 `--enable-shell-tools`)。transport 类型永远不会隐式授予 shell 访问权限。`cancel_background` 只终止 `background_run` 返回的已跟踪 task ID;系统会拒绝按进程名广泛终止 Python,避免把 Vibe-Trading 自身一起终止。文档和日志读取器默认限制在 upload/import roots 内;请将文件放在 `agent/uploads`、`agent/runs`、`./uploads`、`./data`、`~/.vibe-trading/uploads` 或 `~/.vibe-trading/imports` 下,或通过 `VIBE_TRADING_ALLOWED_FILE_ROOTS` 添加专用目录。
### Web UI Settings
diff --git a/agent/mcp_server.py b/agent/mcp_server.py
index 3dda0ea32..80de23c2e 100644
--- a/agent/mcp_server.py
+++ b/agent/mcp_server.py
@@ -81,8 +81,8 @@ logger = logging.getLogger(__name__)
_skills_loader = None
_registry = None
_goal_store = None
-# Fail-closed default: the bash / background_run shell tools are a remote
-# code-execution surface once the MCP server is reachable by any client (stdio,
+# Fail-closed default: bash / background_run / cancel_background form a remote
+# process-control surface once the MCP server is reachable by any client (stdio,
# SSE, or Streamable HTTP), so they stay OFF unless an operator explicitly opts
# in. main() may flip this on via --enable-shell-tools or the
# VIBE_TRADING_ENABLE_SHELL_TOOLS env var. Keeping the module-level default off
@@ -100,11 +100,12 @@ def _env_shell_tools_enabled() -> bool:
def _resolve_include_shell_tools(cli_opt_in: bool) -> bool:
"""Resolve whether the MCP server should register shell tools.
- Shell tools (``bash`` / ``background_run``) run arbitrary OS commands and are
- an RCE surface regardless of transport. They are therefore disabled for every
- transport unless the operator explicitly opts in. Transport type never
- implicitly grants shell access: previously ``stdio`` force-enabled these tools
- with no opt-out (GHSA-6wjh-cc6v-xfrx), which also widened the reachable
+ Process-control tools (``bash`` / ``background_run`` /
+ ``cancel_background``) run commands or terminate tracked command trees and
+ are an RCE surface regardless of transport. They are therefore disabled for
+ every transport unless the operator explicitly opts in. Transport type never
+ implicitly grants shell access: previously ``stdio`` force-enabled these
+ tools with no opt-out (GHSA-6wjh-cc6v-xfrx), which also widened the reachable
surface of the ``bash`` OS-command-injection issue (GHSA-m768-22r9-h4x7).
Args:
@@ -2126,9 +2127,9 @@ def main():
parser.add_argument(
"--enable-shell-tools",
action="store_true",
- help="Register the bash / background_run shell tools (arbitrary OS "
- "command execution — RCE surface). OFF by default for every transport; "
- "equivalent to setting VIBE_TRADING_ENABLE_SHELL_TOOLS=1.",
+ help="Register bash / background_run / cancel_background (OS process "
+ "control — RCE surface). OFF by default for every transport; equivalent "
+ "to setting VIBE_TRADING_ENABLE_SHELL_TOOLS=1.",
)
args = parser.parse_args()
_include_shell_tools = _resolve_include_shell_tools(args.enable_shell_tools)
diff --git a/agent/src/tools/__init__.py b/agent/src/tools/__init__.py
index 94557ce01..9c32d6a26 100644
--- a/agent/src/tools/__init__.py
+++ b/agent/src/tools/__init__.py
@@ -27,7 +27,7 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
_SUBCLASSES_CACHE: list[type[BaseTool]] | None = None
-_SHELL_TOOL_NAMES = {"bash", "background_run"}
+_SHELL_TOOL_NAMES = {"bash", "background_run", "cancel_background"}
def _discover_subclasses() -> list[type[BaseTool]]:
diff --git a/agent/src/tools/_shell_safety.py b/agent/src/tools/_shell_safety.py
new file mode 100644
index 000000000..a1bab2130
--- /dev/null
+++ b/agent/src/tools/_shell_safety.py
@@ -0,0 +1,59 @@
+"""Shared safety checks for host shell commands."""
+
+from __future__ import annotations
+
+import re
+
+_PYTHON_PROCESS = r"python(?:w|\d+(?:\.\d+)*)?(?:\.exe)?\b"
+_TASKKILL_PYTHON = re.compile(
+ rf"\btaskkill(?:\.exe)?\b"
+ rf"[^;&\r\n]*(?:/im\s+{_PYTHON_PROCESS}|get-process\s+"
+ rf"(?:-name\s+)?{_PYTHON_PROCESS})",
+ re.IGNORECASE,
+)
+_UNIX_PYTHON_KILL = re.compile(
+ rf"^(?:sudo\s+)?(?:pkill|killall)\b[^;&\r\n]*{_PYTHON_PROCESS}",
+ re.IGNORECASE,
+)
+_POWERSHELL_PREFIX = re.compile(
+ r"^(?:powershell|pwsh)(?:\.exe)?\b",
+ re.IGNORECASE,
+)
+_POWERSHELL_PYTHON_BY_NAME = re.compile(
+ rf"\bstop-process\b[^;&\r\n]*-name\s+{_PYTHON_PROCESS}",
+ re.IGNORECASE,
+)
+_POWERSHELL_PYTHON_PIPE = re.compile(
+ rf"\bget-process\s+(?:-name\s+)?{_PYTHON_PROCESS}"
+ r"[^;&\r\n]*\|\s*stop-process\b",
+ re.IGNORECASE,
+)
+_BROAD_PYTHON_KILL_ERROR = (
+ "Broad Python process termination is blocked because it can terminate "
+ "Vibe-Trading itself. Use cancel_background with the task_id returned "
+ "by background_run."
+)
+
+
+def broad_python_kill_error(command: str) -> str | None:
+ """Return an error when a shell command broadly kills Python by name.
+
+ Args:
+ command: Shell source submitted to a shell-capable tool.
+
+ Returns:
+ An actionable error for unsafe broad termination, otherwise ``None``.
+ """
+ for segment in re.split(r"[;\r\n]|(?<![<>])&(?![<>])", command):
+ normalized = segment.strip().replace('"', " ").replace("'", " ")
+ normalized = re.sub(r"\s+", " ", normalized)
+ if _TASKKILL_PYTHON.search(normalized):
+ return _BROAD_PYTHON_KILL_ERROR
+ if _UNIX_PYTHON_KILL.search(normalized):
+ return _BROAD_PYTHON_KILL_ERROR
+ if _POWERSHELL_PREFIX.search(normalized) and (
+ _POWERSHELL_PYTHON_BY_NAME.search(normalized)
+ or _POWERSHELL_PYTHON_PIPE.search(normalized)
+ ):
+ return _BROAD_PYTHON_KILL_ERROR
+ return None
diff --git a/agent/src/tools/background_tools.py b/agent/src/tools/background_tools.py
index e19d35e4c..ad9df0429 100644
--- a/agent/src/tools/background_tools.py
+++ b/agent/src/tools/background_tools.py
@@ -7,11 +7,13 @@ import os
import signal
import subprocess
import threading
+import time
import uuid
from pathlib import Path
from typing import Any, Dict, List, Optional
from src.agent.tools import BaseTool
+from src.tools._shell_safety import broad_python_kill_error
WORKDIR = Path(__file__).resolve().parents[2]
_COMMAND_TIMEOUT_SECONDS = 300.0
@@ -58,6 +60,16 @@ def _taskkill_windows_process_tree(process: subprocess.Popen[str]) -> None:
process.kill()
+def _force_stop_process_tree(process: subprocess.Popen[str]) -> None:
+ """Force-stop one tracked process tree without draining its pipes."""
+ if process.poll() is not None:
+ return
+ if os.name == "nt":
+ _taskkill_windows_process_tree(process)
+ else:
+ _signal_posix_process_group(process, signal.SIGKILL)
+
+
def _terminate_process_tree(process: subprocess.Popen[str]) -> tuple[str, str]:
"""Terminate a timed-out process tree, drain its pipes, and reap its root."""
if os.name == "nt":
@@ -104,21 +116,45 @@ class BackgroundManager:
Returns:
JSON string containing status and task_id.
"""
+ safety_error = broad_python_kill_error(command)
+ if safety_error:
+ return json.dumps(
+ {"status": "error", "error": safety_error},
+ ensure_ascii=False,
+ )
+
task_id = uuid.uuid4().hex[:8]
- self.tasks[task_id] = {
- "status": "running",
- "result": None,
- "command": command,
- "exit_code": None,
- }
+ started_at = time.monotonic()
+ with self._lock:
+ self.tasks[task_id] = {
+ "status": "running",
+ "result": None,
+ "command": command,
+ "exit_code": None,
+ "process": None,
+ "cancel_requested": False,
+ "started_at": started_at,
+ }
threading.Thread(target=self._execute, args=(task_id, command), daemon=True).start()
return json.dumps({"status": "ok", "task_id": task_id, "message": f"Started: {command[:80]}"})
def _execute(self, task_id: str, command: str) -> None:
exit_code: int | None = None
process: subprocess.Popen[str] | None = None
+ output = ""
+ status = "error"
try:
process = _start_process(command)
+ with self._lock:
+ task = self.tasks.get(task_id)
+ if task is None:
+ _force_stop_process_tree(process)
+ return
+ task["process"] = process
+ cancel_requested = bool(task.get("cancel_requested"))
+ if cancel_requested:
+ _force_stop_process_tree(process)
+
try:
stdout, stderr = process.communicate(timeout=_COMMAND_TIMEOUT_SECONDS)
output = _combined_output(stdout, stderr)
@@ -137,25 +173,135 @@ class BackgroundManager:
status = "timeout"
except Exception as e:
output, status = str(e), "error"
- self.tasks[task_id]["status"] = status
- self.tasks[task_id]["result"] = output or "(no output)"
- self.tasks[task_id]["exit_code"] = exit_code
+
with self._lock:
+ task = self.tasks.get(task_id)
+ if task is None:
+ return
+ if task.get("cancel_requested"):
+ status = "cancelled"
+ cancel_message = "Cancelled by request"
+ output = (
+ f"{output}\n{cancel_message}"
+ if output
+ else cancel_message
+ )
+ output = output[:_MAX_OUTPUT_CHARS]
+ task["status"] = status
+ task["result"] = output or "(no output)"
+ task["exit_code"] = exit_code
+ task["process"] = None
+ started_at = task.get("started_at")
+ if isinstance(started_at, (int, float)):
+ task["duration_seconds"] = round(
+ max(0.0, time.monotonic() - started_at),
+ 3,
+ )
self._notifications.append({
"task_id": task_id, "status": status,
"command": command[:80], "result": (output or "")[:500],
"exit_code": exit_code,
})
+ def cancel(self, task_id: str) -> str:
+ """Cancel one task by its tracked process group.
+
+ Args:
+ task_id: Identifier returned by :meth:`run`.
+
+ Returns:
+ JSON string describing the cancellation request.
+ """
+ with self._lock:
+ task = self.tasks.get(task_id)
+ if task is None:
+ return json.dumps({
+ "status": "error",
+ "error": f"Unknown task {task_id}",
+ })
+
+ task_status = task["status"]
+ if task_status == "cancelling":
+ return json.dumps({
+ "status": "ok",
+ "task_id": task_id,
+ "task_status": "cancelling",
+ "message": "Cancellation already requested",
+ })
+ if task_status != "running":
+ return json.dumps({
+ "status": "error",
+ "error": f"Task {task_id} is already {task_status}",
+ "task_status": task_status,
+ })
+
+ process = task.get("process")
+ if process is not None and process.poll() is not None:
+ return json.dumps({
+ "status": "error",
+ "error": f"Task {task_id} is already finishing",
+ "task_status": task_status,
+ })
+
+ task["cancel_requested"] = True
+ task["status"] = "cancelling"
+
+ if process is not None:
+ _force_stop_process_tree(process)
+ return json.dumps({
+ "status": "ok",
+ "task_id": task_id,
+ "task_status": "cancelling",
+ "message": "Cancellation requested",
+ })
+
def check(self, task_id: Optional[str] = None) -> str:
+ task: dict | None = None
+ task_summaries: list[tuple[str, str, str]] = []
+ with self._lock:
+ if task_id:
+ t = self.tasks.get(task_id)
+ task = dict(t) if t is not None else None
+ else:
+ task_summaries = [
+ (tid, t["status"], t["command"])
+ for tid, t in self.tasks.items()
+ ]
+
if task_id:
- t = self.tasks.get(task_id)
+ t = task
if not t:
return json.dumps({"status": "error", "error": f"Unknown task {task_id}"})
- return json.dumps({"status": t["status"], "command": t["command"][:60],
- "result": t.get("result") or "(running)",
- "exit_code": t.get("exit_code")}, ensure_ascii=False)
- lines = [f"{tid}: [{t['status']}] {t['command'][:60]}" for tid, t in self.tasks.items()]
+ status = t["status"]
+ result = t.get("result")
+ payload = {
+ "status": status,
+ "command": t["command"][:60],
+ "result": result or "(running)",
+ "exit_code": t.get("exit_code"),
+ }
+ started_at = t.get("started_at")
+ if isinstance(started_at, (int, float)):
+ duration = t.get("duration_seconds")
+ if not isinstance(duration, (int, float)):
+ duration = max(0.0, time.monotonic() - started_at)
+ elapsed = round(duration, 1)
+ payload["elapsed_seconds"] = elapsed
+ payload["timeout_seconds"] = _COMMAND_TIMEOUT_SECONDS
+ if status in {"running", "cancelling"}:
+ remaining = max(0.0, _COMMAND_TIMEOUT_SECONDS - duration)
+ payload["timeout_remaining_seconds"] = round(remaining, 1)
+ if not result:
+ payload["result"] = (
+ f"({status} for {elapsed:g}s; automatic timeout "
+ f"after {_COMMAND_TIMEOUT_SECONDS:g}s; use "
+ "cancel_background(task_id) to stop safely)"
+ )
+ return json.dumps(payload, ensure_ascii=False)
+ lines = [
+ f"{tid}: [{status}] {command[:60]}"
+ for tid, status, command in task_summaries
+ ]
return "\n".join(lines) if lines else "No background tasks."
def drain_notifications(self) -> List[dict]:
@@ -175,7 +321,12 @@ def get_background_manager() -> BackgroundManager:
class BackgroundRunTool(BaseTool):
name = "background_run"
- description = "Run command in background thread. Returns task_id immediately. Use for long-running operations (ML training, large data processing)."
+ description = (
+ "Run a shell command in a tracked background process group. Returns "
+ "task_id immediately and times out after 300 seconds. On Windows the "
+ "shell is cmd.exe, not PowerShell. Poll with check_background and stop "
+ "only with cancel_background; never use taskkill/pkill/killall."
+ )
parameters = {"type": "object", "properties": {
"command": {"type": "string", "description": "Shell command to run in background"},
}, "required": ["command"]}
@@ -187,7 +338,11 @@ class BackgroundRunTool(BaseTool):
class CheckBackgroundTool(BaseTool):
name = "check_background"
- description = "Check background task status. Omit task_id to list all."
+ description = (
+ "Check background task status, elapsed time, and remaining time before "
+ "the 300-second automatic timeout. Omit task_id to list all. To stop "
+ "a running task, pass its task_id to cancel_background."
+ )
parameters = {"type": "object", "properties": {
"task_id": {"type": "string"},
}, "required": []}
@@ -195,3 +350,27 @@ class CheckBackgroundTool(BaseTool):
def execute(self, **kw: Any) -> str:
return _BG.check(kw.get("task_id"))
+
+
+class CancelBackgroundTool(BaseTool):
+ """Cancel one process group created by :class:`BackgroundRunTool`."""
+
+ name = "cancel_background"
+ description = (
+ "Cancel exactly one background_run task by task_id using its tracked "
+ "process group/PID. Never kills processes by executable name."
+ )
+ parameters = {
+ "type": "object",
+ "properties": {
+ "task_id": {
+ "type": "string",
+ "description": "task_id returned by background_run",
+ },
+ },
+ "required": ["task_id"],
+ }
+ is_readonly = False
+
+ def execute(self, **kw: Any) -> str:
+ return _BG.cancel(kw["task_id"])
diff --git a/agent/src/tools/bash_tool.py b/agent/src/tools/bash_tool.py
index 74324ccca..4c82b1e4d 100644
--- a/agent/src/tools/bash_tool.py
+++ b/agent/src/tools/bash_tool.py
@@ -7,6 +7,7 @@ import subprocess
from typing import Any
from src.agent.tools import BaseTool
+from src.tools._shell_safety import broad_python_kill_error
_OUTPUT_LIMIT = 50_000
_DEFAULT_TIMEOUT = 120
@@ -16,7 +17,12 @@ class BashTool(BaseTool):
"""Execute shell commands in the working directory."""
name = "bash"
- description = "Execute a shell command in the working directory. Use for installing packages, running scripts, or inspecting files."
+ description = (
+ "Execute a shell command in the working directory. On Windows the "
+ "shell is cmd.exe, not PowerShell. Use for installing packages, "
+ "running scripts, or inspecting files. Never kill Python processes "
+ "by name; stop a background_run task with cancel_background."
+ )
parameters = {
"type": "object",
"properties": {
@@ -38,6 +44,12 @@ class BashTool(BaseTool):
"""
command = kwargs["command"]
cwd = kwargs.get("run_dir")
+ safety_error = broad_python_kill_error(command)
+ if safety_error:
+ return json.dumps(
+ {"status": "error", "error": safety_error},
+ ensure_ascii=False,
+ )
try:
result = subprocess.run(
diff --git a/agent/tests/test_background_tools.py b/agent/tests/test_background_tools.py
index f92428a1e..424701285 100644
--- a/agent/tests/test_background_tools.py
+++ b/agent/tests/test_background_tools.py
@@ -6,8 +6,10 @@ import json
import os
import shlex
import sys
+import threading
import time
from pathlib import Path
+from unittest.mock import MagicMock
import pytest
@@ -49,6 +51,266 @@ def test_nonzero_exit_is_reported_as_error() -> None:
]
+def test_cancel_unknown_task_returns_actionable_error() -> None:
+ manager = BackgroundManager()
+
+ result = json.loads(manager.cancel("missing"))
+
+ assert result == {
+ "status": "error",
+ "error": "Unknown task missing",
+ }
+
+
+def test_check_running_task_reports_timeout_context(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ manager = BackgroundManager()
+ manager.tasks["slow"] = {
+ "status": "running",
+ "result": None,
+ "command": "python slow.py",
+ "exit_code": None,
+ "process": None,
+ "cancel_requested": False,
+ "started_at": 100.0,
+ }
+ monkeypatch.setattr(background_tools.time, "monotonic", lambda: 297.0)
+
+ result = json.loads(manager.check("slow"))
+
+ assert result["status"] == "running"
+ assert result["elapsed_seconds"] == 197.0
+ assert result["timeout_seconds"] == 300.0
+ assert result["timeout_remaining_seconds"] == 103.0
+ assert "cancel_background" in result["result"]
+
+
+def test_cancel_targets_only_the_tracked_process(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ manager = BackgroundManager()
+ target = MagicMock()
+ target.poll.return_value = None
+ target.pid = 4321
+ sibling = MagicMock()
+ sibling.poll.return_value = None
+ sibling.pid = 8765
+ manager.tasks = {
+ "target": {
+ "status": "running",
+ "result": None,
+ "command": "python target.py",
+ "exit_code": None,
+ "process": target,
+ "cancel_requested": False,
+ },
+ "sibling": {
+ "status": "running",
+ "result": None,
+ "command": "python sibling.py",
+ "exit_code": None,
+ "process": sibling,
+ "cancel_requested": False,
+ },
+ }
+ stopped: list[object] = []
+ monkeypatch.setattr(
+ background_tools,
+ "_force_stop_process_tree",
+ stopped.append,
+ )
+
+ result = json.loads(manager.cancel("target"))
+
+ assert result == {
+ "status": "ok",
+ "task_id": "target",
+ "task_status": "cancelling",
+ "message": "Cancellation requested",
+ }
+ assert stopped == [target]
+ assert manager.tasks["target"]["status"] == "cancelling"
+ assert manager.tasks["target"]["cancel_requested"] is True
+ assert manager.tasks["sibling"]["status"] == "running"
+ assert manager.tasks["sibling"]["cancel_requested"] is False
+
+
+def test_cancel_completed_task_does_not_touch_process(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ manager = BackgroundManager()
+ process = MagicMock()
+ manager.tasks["done"] = {
+ "status": "completed",
+ "result": "finished",
+ "command": "python done.py",
+ "exit_code": 0,
+ "process": process,
+ "cancel_requested": False,
+ }
+ stop = MagicMock()
+ monkeypatch.setattr(background_tools, "_force_stop_process_tree", stop)
+
+ result = json.loads(manager.cancel("done"))
+
+ assert result == {
+ "status": "error",
+ "error": "Task done is already completed",
+ "task_status": "completed",
+ }
+ stop.assert_not_called()
+
+
+def test_cancel_background_tool_contract() -> None:
+ tool = background_tools.CancelBackgroundTool()
+
+ assert tool.name == "cancel_background"
+ assert tool.parameters["required"] == ["task_id"]
+ assert tool.is_readonly is False
+
+
+def test_windows_process_tree_kill_uses_pid_never_image_name(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ process = MagicMock()
+ process.pid = 4321
+ run = MagicMock()
+ monkeypatch.setattr(background_tools.subprocess, "run", run)
+
+ background_tools._taskkill_windows_process_tree(process)
+
+ args = run.call_args.args[0]
+ assert args == ["taskkill", "/PID", "4321", "/T", "/F"]
+ assert "/IM" not in args
+ assert "python.exe" not in args
+
+
+ "command",
+ [
+ 'taskkill /F /IM python.exe 2>nul & echo "done"',
+ (
+ "taskkill /F /PID (Get-Process python | "
+ "Where-Object {$_.MainWindowTitle -eq ''} | "
+ "Select-Object -First 1 -ExpandProperty Id)"
+ ),
+ ],
+)
+def test_background_run_rejects_broad_python_termination(command: str) -> None:
+ manager = BackgroundManager()
+
+ result = json.loads(manager.run(command))
+
+ assert result["status"] == "error"
+ assert "cancel_background" in result["error"]
+ assert manager.tasks == {}
+
+
+def _wait_for_task_status(
+ manager: BackgroundManager,
+ task_id: str,
+ expected: set[str],
+ timeout: float = 5.0,
+) -> dict:
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ task = json.loads(manager.check(task_id))
+ if task["status"] in expected:
+ return task
+ time.sleep(0.02)
+ pytest.fail(
+ f"task {task_id} did not reach {sorted(expected)}: "
+ f"{manager.check(task_id)}"
+ )
+
+
+def _wait_for_registered_process(
+ manager: BackgroundManager,
+ task_id: str,
+ timeout: float = 5.0,
+) -> None:
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ with manager._lock:
+ process = manager.tasks[task_id].get("process")
+ if process is not None:
+ return
+ time.sleep(0.02)
+ pytest.fail(f"task {task_id} did not register its process")
+
+
+def test_cancel_running_task_reaps_process() -> None:
+ manager = BackgroundManager()
+ command = f'"{sys.executable}" -c "import time; time.sleep(30)"'
+ task_id = json.loads(manager.run(command))["task_id"]
+ _wait_for_registered_process(manager, task_id)
+
+ result = json.loads(manager.cancel(task_id))
+ task = _wait_for_task_status(manager, task_id, {"cancelled"})
+
+ assert result["status"] == "ok"
+ assert task["status"] == "cancelled"
+ assert task["exit_code"] not in (None, 0)
+ assert "Cancelled by request" in task["result"]
+
+
+def test_cancel_running_task_leaves_sibling_alive() -> None:
+ manager = BackgroundManager()
+ command = f'"{sys.executable}" -c "import time; time.sleep(30)"'
+ target_id = json.loads(manager.run(command))["task_id"]
+ sibling_id = json.loads(manager.run(command))["task_id"]
+ _wait_for_registered_process(manager, target_id)
+ _wait_for_registered_process(manager, sibling_id)
+
+ try:
+ result = json.loads(manager.cancel(target_id))
+ target = _wait_for_task_status(manager, target_id, {"cancelled"})
+ sibling = json.loads(manager.check(sibling_id))
+
+ assert result["status"] == "ok"
+ assert target["status"] == "cancelled"
+ assert sibling["status"] == "running"
+ finally:
+ sibling = json.loads(manager.check(sibling_id))
+ if sibling["status"] in {"running", "cancelling"}:
+ manager.cancel(sibling_id)
+ _wait_for_task_status(manager, sibling_id, {"cancelled"})
+
+
+def test_cancel_before_process_registration_is_honored(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ manager = BackgroundManager()
+ start_entered = threading.Event()
+ allow_start = threading.Event()
+ process = MagicMock()
+ process.pid = 4321
+ process.poll.return_value = None
+ process.communicate.return_value = ("", "")
+ process.returncode = -9
+ stop = MagicMock()
+
+ def delayed_start(command: str) -> object:
+ del command
+ start_entered.set()
+ assert allow_start.wait(timeout=2.0)
+ return process
+
+ monkeypatch.setattr(background_tools, "_start_process", delayed_start)
+ monkeypatch.setattr(background_tools, "_force_stop_process_tree", stop)
+
+ task_id = json.loads(manager.run("python slow.py"))["task_id"]
+ assert start_entered.wait(timeout=2.0)
+ result = json.loads(manager.cancel(task_id))
+ allow_start.set()
+ task = _wait_for_task_status(manager, task_id, {"cancelled"})
+
+ assert result["status"] == "ok"
+ assert task["status"] == "cancelled"
+ stop.assert_called_once_with(process)
+
+
@pytest.mark.skipif(os.name == "nt", reason="POSIX process-group regression")
def test_timeout_kills_descendant_and_reaps_shell(
tmp_path: Path,
diff --git a/agent/tests/test_bash_tool.py b/agent/tests/test_bash_tool.py
new file mode 100644
index 000000000..1a029c5c2
--- /dev/null
+++ b/agent/tests/test_bash_tool.py
@@ -0,0 +1,66 @@
+"""Safety regression tests for host shell execution."""
+
+from __future__ import annotations
+
+import json
+from unittest.mock import MagicMock
+
+import pytest
+
+from src.tools import bash_tool
+from src.tools.bash_tool import BashTool
+
+
+ "command",
+ [
+ 'taskkill /F /IM python.exe 2>nul & echo "killed any python"',
+ (
+ "taskkill /F /PID (Get-Process python | "
+ "Where-Object {$_.MainWindowTitle -eq ''} | "
+ "Select-Object -First 1 -ExpandProperty Id)"
+ ),
+ 'powershell -Command "taskkill /F /IM python.exe"',
+ 'start "" taskkill /F /IM python.exe',
+ "powershell -NoProfile -Command \"Stop-Process -Name python -Force\"",
+ "powershell -Command \"Get-Process python | Stop-Process -Force\"",
+ "pkill -9 -f python",
+ "killall python3",
+ ],
+)
+def test_rejects_broad_python_process_termination(
+ command: str,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ run = MagicMock(side_effect=AssertionError("unsafe command reached subprocess"))
+ monkeypatch.setattr(bash_tool.subprocess, "run", run)
+
+ result = json.loads(BashTool().execute(command=command))
+
+ assert result["status"] == "error"
+ assert "cancel_background" in result["error"]
+ run.assert_not_called()
+
+
+ "command",
+ [
+ "python --version",
+ "taskkill /PID 4321 /T /F",
+ "echo python.exe",
+ ],
+)
+def test_allows_non_broad_process_commands(
+ command: str,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ run = MagicMock()
+ run.return_value.returncode = 0
+ run.return_value.stdout = "ok"
+ run.return_value.stderr = ""
+ monkeypatch.setattr(bash_tool.subprocess, "run", run)
+
+ result = json.loads(BashTool().execute(command=command))
+
+ assert result["status"] == "ok"
+ run.assert_called_once()
diff --git a/agent/tests/test_mcp_regression.py b/agent/tests/test_mcp_regression.py
index 94c90818f..8d9f5135e 100644
--- a/agent/tests/test_mcp_regression.py
+++ b/agent/tests/test_mcp_regression.py
@@ -185,10 +185,10 @@ def test_mcp_server_exposes_well_known_tool_names() -> None:
# ---------------------------------------------------------------------------
# Shell-tool opt-in policy (GHSA-6wjh-cc6v-xfrx / GHSA-m768-22r9-h4x7)
#
-# The bash / background_run tools run arbitrary OS commands. The MCP server must
-# NOT register them unless the operator explicitly opts in — for EVERY transport.
-# stdio previously force-enabled them with no opt-out; that is the regression
-# these tests guard against.
+# The bash / background_run / cancel_background tools control OS processes. The
+# MCP server must NOT register them unless the operator explicitly opts in — for
+# EVERY transport. stdio previously force-enabled shell tools with no opt-out;
+# that is the regression these tests guard against.
# ---------------------------------------------------------------------------
@@ -234,6 +234,7 @@ def test_mcp_registry_omits_shell_tools_under_default_policy(monkeypatch: pytest
assert "bash" not in registry.tool_names
assert "background_run" not in registry.tool_names
+ assert "cancel_background" not in registry.tool_names
class _RecordingRegistry:
diff --git a/agent/tests/test_tool_registry_security.py b/agent/tests/test_tool_registry_security.py
index 4766f1d85..42231c1e3 100644
--- a/agent/tests/test_tool_registry_security.py
+++ b/agent/tests/test_tool_registry_security.py
@@ -14,6 +14,7 @@ def test_shell_tools_absent_from_default_registry(monkeypatch: pytest.MonkeyPatc
assert "bash" not in registry.tool_names
assert "background_run" not in registry.tool_names
+ assert "cancel_background" not in registry.tool_names
def test_shell_tools_require_registry_opt_in(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -23,3 +24,4 @@ def test_shell_tools_require_registry_opt_in(monkeypatch: pytest.MonkeyPatch) ->
assert "bash" in registry.tool_names
assert "background_run" in registry.tool_names
+ assert "cancel_background" in registry.tool_names