diff --git a/app/agent/prompt/System Core Prompt.txt b/app/agent/prompt/System Core Prompt.txt index b2fb0f0b6..e44f39a64 100644 --- a/app/agent/prompt/System Core Prompt.txt +++ b/app/agent/prompt/System Core Prompt.txt @@ -81,7 +81,7 @@ You act as a proactive agent. Your goal is to fully resolve the user's media-rel - When implementation depends on a Python or Node.js API, first identify the installed or locked dependency version from environment metadata, requirements, package manifests, lockfiles, local source, and type declarations. Use `rg` against the relevant package directory, `.venv`, or `node_modules` instead of scanning the entire project without bounds. If local evidence is insufficient, use `search_web` and then `browse_webpage` to read the matching version of the official documentation. Do not guess signatures from memory, mix examples from incompatible versions, or install a package only to inspect its API. - Use structured file tools for source edits because they enforce file access boundaries and conflict checks. Never use shell redirection, inline scripts, or another tool to bypass a file-tool permission denial. - On Windows, follow the command environment injected in `` for the entire task. If Git Bash is selected, use Git Bash/POSIX syntax and prefer `git` for repository work. Otherwise, when PowerShell 7 is selected, use `pwsh` syntax consistently. Never mix cmd.exe, Windows PowerShell, PowerShell 7, and POSIX syntax in one workflow, and treat command and file text as UTF-8. -- Use `execute_command` for administrator-only multi-file diagnostics, tests, Git, service operations, SSH, or an exact command the user requested. Use `action=run` for short bounded commands. Use `action=start` for long-running or interactive commands, including SSH; then continue with `read`, `wait`, `write`, or `kill` using the returned `session_id`. Do not start a background session for a short command that can finish within `action=run`. When the project `venv` or Docker `VENV_PATH` exists, the command environment sets `MOVIEPILOT_PYTHON` to `moviepilot-python` when available, otherwise the environment's `python`/`python3` (Windows uses `Scripts`); use that variable with `-m ...`, especially for downloader, SMB, and media-server operations that need the project's system permissions. Use the project `uv pip ...` or that interpreter's `-m pip ...` for dependencies. Do not switch to a system interpreter or use `sudo pip`. +- Use `execute_command` for administrator-only multi-file diagnostics, tests, Git, service operations, SSH, or an exact command the user requested. Use `action=run` for short bounded commands. Use `action=start` for long-running or interactive commands, including SSH; then continue with `read`, `wait`, `write`, or `kill` using the returned `session_id`. Do not start a background session for a short command that can finish within `action=run`. When the project `venv` or Docker `VENV_PATH` exists, the command environment puts it first on `PATH` and routes bare `python`/`python3` to `moviepilot-python` when available, otherwise the environment's standard Python (Windows uses `Scripts`); use `python -m ...`, especially for downloader, SMB, and media-server operations that need the project's system permissions. Use the project `uv pip ...` or that interpreter's `-m pip ...` for dependencies. Do not switch to a system interpreter or use `sudo pip`. - A terminal response confirms only the output it actually delivered. Resume with both `since_seq=output_until_seq` and `since_offset=output_until_offset`; never advance using `last_seq`. Set `since_offset=0` for partial-chunk paging. `wait` wakes for new output or completion; `timeout_ms=0` only polls and does not stop the process. Continue until the output cursor reaches the end and `output_complete=true` when a complete log is needed. If `output_lost=true`, disclose the missing output. If a start/write/kill response contains `output_error`, keep its `session_id` and recover with `read` using the suggested byte limit; do not repeat the action merely to retrieve output. diff --git a/app/agent/prompt/__init__.py b/app/agent/prompt/__init__.py index 4789f1a9f..6ba6ec4fd 100644 --- a/app/agent/prompt/__init__.py +++ b/app/agent/prompt/__init__.py @@ -265,7 +265,7 @@ class PromptManager: f"- 当前日期: {strftime('%Y-%m-%d')}", f"- 运行环境: {SystemUtils.platform} {'docker' if SystemUtils.is_docker() else ''}", "- 详细运行状态和数据库通过 `query_doctor_report` 或 `execute_command` 查询;配置值先加载对应 Skill,再通过 `moviepilot_api` 的配置 operation 查询。", - "- Python 命令: Agent 设置 `MOVIEPILOT_PYTHON` 为项目 `venv` 或 `VENV_PATH` 环境中的专用入口 `moviepilot-python`(不存在时回退到 `python`/`python3`,Windows 对应 `Scripts`),并设置 `VIRTUAL_ENV`;请优先使用该变量执行 `-m ...`,尤其是下载器、SMB、媒体服务器等需要系统权限的操作。安装依赖优先使用项目 `uv pip ...` 或该变量指向的 `-m pip ...`,不要切换到系统 Python 或使用 `sudo pip`。", + "- Python 命令: 项目 `venv` 或 Docker 的 `VENV_PATH` 存在时,Agent 会把它放在命令 PATH 最前,并让裸 `python`/`python3` 自动使用专用入口 `moviepilot-python`;入口不存在时回退到环境中的标准 Python(Windows 对应 `Scripts`)。请直接使用 `python -m ...`,尤其是下载器、SMB、媒体服务器等需要系统权限的操作。安装依赖优先使用项目 `uv pip ...` 或绑定环境中的 `python -m pip ...`,不要切换到系统 Python 或使用 `sudo pip`。", ] try: shell = resolve_agent_shell(cwd=str(get_runtime_setting("ROOT_PATH"))) diff --git a/app/agent/shell.py b/app/agent/shell.py index 94a139b2c..0a3de34a1 100644 --- a/app/agent/shell.py +++ b/app/agent/shell.py @@ -5,6 +5,7 @@ from __future__ import annotations import ntpath import os import posixpath +import shlex import shutil from dataclasses import dataclass from pathlib import Path, PureWindowsPath @@ -100,12 +101,34 @@ def _find_executable(executable: str, finder: CommandFinder, *, windows: bool) - return located -def _posix_policy(kind: str, executable: str, *, login: bool, git_available: bool = False) -> AgentShell: +def _posix_policy( + kind: str, + executable: str, + *, + login: bool, + git_available: bool = False, + command_prefix: str = "", +) -> AgentShell: """POSIX 类解释器使用统一 exec 参数;C shell 不支持登录与命令执行组合。""" if login and kind in {"csh", "tcsh"}: raise ValueError(f"{kind} 不支持 login=True 与命令执行组合") arguments = ("-lc",) if login else ("-c",) - return AgentShell(kind, executable, arguments, git_available=git_available, login=login) + return AgentShell( + kind, executable, arguments, command_prefix=command_prefix, + git_available=git_available, login=login, + ) + + +def _project_python_alias_prefix(environment: Mapping[str, str], *, windows: bool) -> str: + """让 POSIX Agent 命令中的裸 Python 使用已选定的项目运行时入口。""" + if windows or not environment.get("MOVIEPILOT_PYTHON"): + return "" + # shell 函数只存在于本次子进程,避免改写虚拟环境中的解释器或用户文件。 + runtime = shlex.quote(environment["MOVIEPILOT_PYTHON"]) + return ( + f"python() {{ {runtime} \"$@\"; }}\n" + f"python3() {{ {runtime} \"$@\"; }}" + ) def _windows_policy(kind: str, executable: str, *, login: Optional[bool], git_available: bool, @@ -215,7 +238,10 @@ def resolve_agent_shell( if not windows: selected = executable if executable is not None else current_environment.get("SHELL") or os.environ.get("SHELL") or "/bin/sh" path = _find_executable(selected, finder, windows=False) - return _posix_policy(_shell_kind(path, windows=False), path, login=bool(login)) + return _posix_policy( + _shell_kind(path, windows=False), path, login=bool(login), + command_prefix=_project_python_alias_prefix(current_environment, windows=False), + ) git_path = finder("git") or finder("git.exe") if executable is not None: diff --git a/docs/agent.md b/docs/agent.md index e374848a2..1ab52ba3e 100644 --- a/docs/agent.md +++ b/docs/agent.md @@ -65,7 +65,7 @@ Agent 人格是全局运行时配置,不按用户隔离;所有用户共享 `execute_command(action="run")` 返回结构化 JSON:`exit_code`、`timed_out`、`execution_outcome` 和 `status` 表示实际执行结果,`output` 保存输出预览,`output_file` 指向超长输出的临时归档。仅正常退出且退出码为 0 时成功;非零退出或已停止的超时命令为失败,无法确认进程结束时为未知,不能凭“有输出”判断成功。超时和取消不会撤销命令已经产生的外部副作用。取消继续向外传播,同时回收输出读取任务、关闭归档文件;`run` 与 `start` 都支持 `env`,并采用同一工作目录与解释器策略。 -项目安装目录存在 `venv`,或 Docker 的 `VENV_PATH` 环境存在时,`execute_command` 的一次性命令、pipe 和 PTY 会把该环境的 `bin`(Windows 为 `Scripts`)放在子进程 `PATH` 最前,设置 `VIRTUAL_ENV`,并设置 `MOVIEPILOT_PYTHON`。该变量优先指向 `moviepilot-python`,不存在时回退到同目录的 `python`/`python3`(Windows 对应 `Scripts`);执行 Python 优先使用该变量的 `-m ...`,尤其是下载器、SMB、媒体服务器等需要系统权限的操作。安装依赖优先使用项目 `uv pip ...` 或该变量指向的 `-m pip ...`,不要改用系统解释器或 `sudo pip`。 +项目安装目录存在 `venv`,或 Docker 的 `VENV_PATH` 环境存在时,`execute_command` 的一次性命令、pipe 和 PTY 会把该环境的 `bin`(Windows 为 `Scripts`)放在子进程 `PATH` 最前,设置 `VIRTUAL_ENV`,并让裸 `python`/`python3` 使用项目专用入口 `moviepilot-python`;入口不存在时回退到环境中的标准 Python。执行 Python 直接使用 `python -m ...`,尤其是下载器、SMB、媒体服务器等需要系统权限的操作。安装依赖优先使用项目 `uv pip ...` 或绑定环境中的 `python -m pip ...`,不要改用系统解释器或 `sudo pip`。 `run`、后台 pipe 和 PTY 共用 `cwd`、`shell`、`login` 解析。省略 `cwd` 使用 MoviePilot 根目录,相对路径也相对该目录,并支持 `~`;错误目录在进程启动前拒绝。POSIX 默认使用配置的 `SHELL`(未配置时 `/bin/sh`)且不启动登录模式,显式 `shell` 可选择已安装解释器,`login=true/false` 控制其支持的登录行为。登录启动文件可能改变目录或环境;PTY 本身不再隐式开启登录模式。Windows 未显式指定时保留 Git Bash → PowerShell 7 → cmd 的选择顺序与 UTF-8 策略;不支持的解释器/登录组合明确失败。回包的 `shell`、`login` 说明实际策略,默认解释器不可用不会阻断其它 Agent 业务能力。 diff --git a/docs/mcp-api.md b/docs/mcp-api.md index c8e30c257..41f964871 100644 --- a/docs/mcp-api.md +++ b/docs/mcp-api.md @@ -867,11 +867,11 @@ MCP、HTTP 工具管理接口、本地 CLI 和内置 Agent 都从同一严格目 `run`、pipe 和 PTY 共享 `cwd/shell/login`:默认及相对 `cwd` 使用 MoviePilot 根目录, POSIX 默认非登录;Windows 未指定时保留已有解释器/UTF-8 策略。回包包含实际 `shell/login`。 项目安装目录存在 `venv`,或 Docker 的 `VENV_PATH` 环境存在时,三种模式都会把该环境的 -`bin`(Windows 为 `Scripts`)放在子进程 `PATH` 最前、设置 `VIRTUAL_ENV`,并设置 -`MOVIEPILOT_PYTHON`。该变量优先指向 `moviepilot-python`,不存在时回退到同目录的 -`python`/`python3`(Windows 对应 `Scripts`);执行 Python 应优先使用该变量的 `-m ...`, -尤其是下载器、SMB、媒体服务器等需要系统权限的操作。安装依赖优先使用项目 `uv pip ...` 或 -该变量指向的 `-m pip ...`,不要改用系统解释器或 `sudo pip`。 +`bin`(Windows 为 `Scripts`)放在子进程 `PATH` 最前、设置 `VIRTUAL_ENV`,并让裸 +`python`/`python3` 使用项目专用入口 `moviepilot-python`;入口不存在时回退到环境中的标准 +Python。执行 Python 应直接使用 `python -m ...`,尤其是下载器、SMB、媒体服务器等需要系统 +权限的操作。安装依赖优先使用项目 `uv pip ...` 或绑定环境中的 `python -m pip ...`,不要改用 +系统解释器或 `sudo pip`。 `write(close_stdin=true)` 仅在 pipe 模式支持末段输入后 EOF,回包包含 `stdin_closed`;输出可继续读取。 PTY 会在写入之前拒绝 half-close,空 `write` 不代表 EOF,控制字节在 pipe 中也不等于信号。 新增 `interrupt` 只发送一次平台支持的中断并返回 `signal/signal_sent`,不会升级强杀; diff --git a/skills/database-operation/SKILL.md b/skills/database-operation/SKILL.md index b83fd31d5..55d7850d9 100644 --- a/skills/database-operation/SKILL.md +++ b/skills/database-operation/SKILL.md @@ -29,15 +29,11 @@ runtime, for example: ```bash cd -PYTHON="${MOVIEPILOT_PYTHON:-venv/bin/moviepilot-python}" -[ -x "$PYTHON" ] || PYTHON="${VENV_PATH:-venv}/bin/python" -[ -x "$PYTHON" ] || PYTHON="${VENV_PATH:-venv}/bin/python3" -"$PYTHON" skills/database-operation/scripts/mp-db.py tables +python skills/database-operation/scripts/mp-db.py tables ``` -Prefer the project-specific `moviepilot-python` entry; fall back to `python` or `python3` -from the project or Docker `VENV_PATH` only when it is unavailable. Agent -`execute_command` automatically provides `$MOVIEPILOT_PYTHON`. +The Agent command environment routes `python` to the project-specific `moviepilot-python` +entry when available and falls back to the project or Docker `VENV_PATH` Python otherwise. The runtime sets `MOVIEPILOT_ROOT` for copied skills. If you run a copied script directly from `/agent/skills/`, set that variable to the diff --git a/skills/downloader-operation/SKILL.md b/skills/downloader-operation/SKILL.md index 19485aa08..6f1aef7ea 100644 --- a/skills/downloader-operation/SKILL.md +++ b/skills/downloader-operation/SKILL.md @@ -21,16 +21,13 @@ runtime, for example: ```bash cd -PYTHON="${MOVIEPILOT_PYTHON:-venv/bin/moviepilot-python}" -[ -x "$PYTHON" ] || PYTHON="${VENV_PATH:-venv}/bin/python" -[ -x "$PYTHON" ] || PYTHON="${VENV_PATH:-venv}/bin/python3" -"$PYTHON" skills/downloader-operation/scripts/mp-downloader.py instances +python skills/downloader-operation/scripts/mp-downloader.py instances ``` -Prefer the project-specific `moviepilot-python` entry; fall back to `python` or `python3` -from the project or Docker `VENV_PATH` only when it is unavailable. Agent -`execute_command` automatically provides `$MOVIEPILOT_PYTHON`. Downloader connections -may depend on macOS local-network permissions, so this priority must be preserved. +The Agent command environment routes `python` to the project-specific `moviepilot-python` +entry when available and falls back to the project or Docker `VENV_PATH` Python otherwise. +Downloader connections may depend on macOS local-network permissions, so use the provided +`python` command for every operation. The runtime sets `MOVIEPILOT_ROOT` for copied skills. If you run a copied script directly from `/agent/skills/`, set that variable to the diff --git a/skills/mediaserver-operation/SKILL.md b/skills/mediaserver-operation/SKILL.md index d0c937900..53bf7fd61 100644 --- a/skills/mediaserver-operation/SKILL.md +++ b/skills/mediaserver-operation/SKILL.md @@ -22,16 +22,13 @@ runtime, for example: ```bash cd -PYTHON="${MOVIEPILOT_PYTHON:-venv/bin/moviepilot-python}" -[ -x "$PYTHON" ] || PYTHON="${VENV_PATH:-venv}/bin/python" -[ -x "$PYTHON" ] || PYTHON="${VENV_PATH:-venv}/bin/python3" -"$PYTHON" skills/mediaserver-operation/scripts/mp-mediaserver.py instances +python skills/mediaserver-operation/scripts/mp-mediaserver.py instances ``` -Prefer the project-specific `moviepilot-python` entry; fall back to `python` or `python3` -from the project or Docker `VENV_PATH` only when it is unavailable. Agent -`execute_command` automatically provides `$MOVIEPILOT_PYTHON`. Media-server connections -may depend on macOS local-network permissions, so this priority must be preserved. +The Agent command environment routes `python` to the project-specific `moviepilot-python` +entry when available and falls back to the project or Docker `VENV_PATH` Python otherwise. +Media-server connections may depend on macOS local-network permissions, so use the provided +`python` command for every operation. The runtime sets `MOVIEPILOT_ROOT` for copied skills. If you run a copied script directly from `/agent/skills/`, set that variable to the diff --git a/tests/test_agent_shell.py b/tests/test_agent_shell.py index 0c327c17d..b0058c8c6 100644 --- a/tests/test_agent_shell.py +++ b/tests/test_agent_shell.py @@ -6,6 +6,7 @@ import ntpath import os import shutil import subprocess +import sys from pathlib import Path from types import SimpleNamespace from unittest.mock import AsyncMock, patch @@ -154,6 +155,28 @@ def test_posix_shell_policy_preserves_native_shell_and_environment(monkeypatch) assert agent_text_subprocess_kwargs(platform_name="posix") == {} +def test_posix_shell_routes_bare_python_to_project_runtime() -> None: + """Agent 的裸 python 命令应在本次 shell 中使用项目专用运行时。""" + shell = resolve_agent_shell( + platform_name="posix", + environment={"SHELL": "/bin/sh", "MOVIEPILOT_PYTHON": sys.executable}, + ) + + command = shell.build_argv("python -c 'print(1)'")[-1] + assert "python()" in command + assert "python3()" in command + assert command.endswith("python -c 'print(1)'") + + result = subprocess.run( + shell.build_argv("python -c 'print(1)'"), + env={"PATH": os.environ["PATH"]}, + capture_output=True, + text=True, + check=True, + ) + assert result.stdout == "1\n" + + def test_windows_subprocess_environment_forces_utf8_after_overrides() -> None: """Windows 调用方不能通过自定义环境重新引入本地默认编码。""" environment = build_agent_subprocess_env( @@ -245,10 +268,10 @@ def test_prompt_injects_selected_windows_shell_without_executable_path() -> None def test_prompt_prioritizes_project_runtime_python() -> None: - """运行提示应指示专用入口优先并覆盖需要系统权限的操作。""" + """运行提示应指示裸 Python 自动使用专用入口。""" moviepilot_info = PromptManager()._get_moviepilot_info() - assert "MOVIEPILOT_PYTHON" in moviepilot_info + assert "裸 `python`/`python3`" in moviepilot_info assert "moviepilot-python" in moviepilot_info assert "下载器、SMB、媒体服务器" in moviepilot_info