From d667fa6c572f37116b4fa37cc2bec2fb837f7306 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Fri, 30 Oct 2026 09:23:48 +0800 Subject: [PATCH] feat: enforce DSH assistant capability boundaries --- docs/user/dsh-ai-supervision.md | 4 +-- src/dx_productivity/dsh/actions.py | 18 +++++++++++- src/dx_productivity/dsh/client.py | 8 ++++- .../trial_task_center/ui/dsh_panel.py | 29 ++++++++++++++++++- .../trial_task_center/ui/main_window.py | 2 +- tests/dsh/test_core.py | 13 ++++++++- 6 files changed, 67 insertions(+), 7 deletions(-) diff --git a/docs/user/dsh-ai-supervision.md b/docs/user/dsh-ai-supervision.md index fc6aa61..0d8e507 100644 --- a/docs/user/dsh-ai-supervision.md +++ b/docs/user/dsh-ai-supervision.md @@ -1,5 +1,5 @@ -# DSH AI 监管助手 +# DSH助手 DSH 是任务中心内的工具型监管入口。它先使用本地规则识别失败、超时和不确定状态;明确失败可生成一次性的重试动作。模型只负责解释和提出结构化建议,不能直接调用 CAD、Shell、文件系统或任意网络工具。 -打开任务中心的“DSH AI 监管”后,可以查看当前任务状态并进行人工对话。未配置 DeepSeek/OpenAI 兼容接口时,对话会明确提示,但本地监管和固定动作仍然可用。工程写入、规则修改和不确定状态恢复始终需要人工确认。 +打开任务中心的“DSH助手”后,可以查看当前任务状态并进行人工对话。未配置 DeepSeek/OpenAI 兼容接口时,对话会明确提示,但本地监管和固定动作仍然可用。模型动作最多 3 个,必须绑定当前任务;未知动作、跨任务参数和非法 JSON 会被拒绝。工程写入、规则修改和不确定状态恢复始终需要人工确认。 diff --git a/src/dx_productivity/dsh/actions.py b/src/dx_productivity/dsh/actions.py index f55f2fd..fa25d0a 100644 --- a/src/dx_productivity/dsh/actions.py +++ b/src/dx_productivity/dsh/actions.py @@ -6,6 +6,7 @@ from typing import Any, Mapping ALLOWED_ACTIONS = {"retry_failed", "pause_task", "refresh_snapshot"} +AUTO_ACTIONS = {"retry_failed"} @dataclass(frozen=True) @@ -31,4 +32,19 @@ def validate_action(raw: Mapping[str, Any]) -> ActionProposal: if not task_id or len(task_id) > 128: raise ValueError("invalid_dsh_task_id") reason = str(raw.get("reason", ""))[:500] - return ActionProposal(str(raw["name"]), task_id, reason, bool(raw.get("requires_confirmation", False))) + name = str(raw["name"]) + # The model cannot lower the confirmation requirement by setting a flag. + requires_confirmation = name not in AUTO_ACTIONS + return ActionProposal(name, task_id, reason, requires_confirmation) + + +def validate_model_actions(raw_actions: Any, *, task_id: str) -> list[ActionProposal]: + if not isinstance(raw_actions, list) or len(raw_actions) > 3: + raise ValueError("invalid_dsh_actions") + proposals = [] + for raw in raw_actions: + proposal = validate_action(raw) + if proposal.task_id != task_id: + raise ValueError("dsh_action_task_mismatch") + proposals.append(proposal) + return proposals diff --git a/src/dx_productivity/dsh/client.py b/src/dx_productivity/dsh/client.py index 36f0a26..0355107 100644 --- a/src/dx_productivity/dsh/client.py +++ b/src/dx_productivity/dsh/client.py @@ -6,6 +6,8 @@ import urllib.request from dataclasses import dataclass from typing import Any, Mapping +from .actions import validate_model_actions + class DshClientError(RuntimeError): pass @@ -42,6 +44,10 @@ class OpenAICompatibleClient: result = json.loads(content) except (OSError, KeyError, IndexError, TypeError, ValueError, urllib.error.URLError) as exc: raise DshClientError("dsh_model_response_invalid") from exc - if not isinstance(result, dict) or not isinstance(result.get("reply"), str) or not isinstance(result.get("actions", []), list): + if not isinstance(result, dict) or not isinstance(result.get("reply"), str): raise DshClientError("dsh_model_response_invalid") + try: + result["actions"] = validate_model_actions(result.get("actions", []), task_id=str(snapshot.get("task_id", ""))) + except (TypeError, ValueError) as exc: + raise DshClientError("dsh_model_action_rejected") from exc return result diff --git a/src/dx_productivity/trial_task_center/ui/dsh_panel.py b/src/dx_productivity/trial_task_center/ui/dsh_panel.py index 656bd19..2c20752 100644 --- a/src/dx_productivity/trial_task_center/ui/dsh_panel.py +++ b/src/dx_productivity/trial_task_center/ui/dsh_panel.py @@ -2,7 +2,9 @@ from __future__ import annotations from PySide6.QtWidgets import QDialog, QFormLayout, QHBoxLayout, QLabel, QListWidget, QLineEdit, QMessageBox, QPushButton, QTextEdit, QVBoxLayout +from ...dsh.actions import ActionProposal from ...dsh.client import DshClientError, OpenAICompatibleClient +from ...dsh.service_adapter import DshServiceAdapter from ...dsh.snapshot import TaskSnapshot from ...dsh.supervisor import DshSupervisor @@ -10,9 +12,10 @@ from ...dsh.supervisor import DshSupervisor class DshPanel(QDialog): def __init__(self, service, *, task_id: str = "", snapshot: TaskSnapshot | None = None, client=None, parent=None): super().__init__(parent) - self.setWindowTitle("DSH AI 监管助手") + self.setWindowTitle("DSH助手") self.resize(720, 520) self.client = client + self.adapter = DshServiceAdapter(service) self.snapshot = snapshot or TaskSnapshot(task_id, "observe") self.supervisor = DshSupervisor() self.issue = QLabel("本地监管:等待异常事件") @@ -41,6 +44,30 @@ class DshPanel(QDialog): try: result = self.client.chat(message, self.snapshot.safe_dict()) self.chat.append(f"助手:{result['reply']}") + self._show_actions(result.get("actions", [])) except DshClientError as error: self.chat.append(f"助手:{error}") + def _show_actions(self, actions): + for proposal in actions: + if not isinstance(proposal, ActionProposal): + continue + button = QPushButton(f"执行:{proposal.name} · {proposal.reason or 'DSH建议'}") + button.clicked.connect(lambda _checked=False, p=proposal, b=button: self._execute(p, b)) + self.actions.addItem("") + self.actions.setItemWidget(self.actions.item(self.actions.count() - 1), button) + + def _execute(self, proposal: ActionProposal, button: QPushButton): + if proposal.requires_confirmation and QMessageBox.question( + self, "确认DSH动作", f"确认执行 {proposal.name}?\n\n{proposal.reason}", + QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, + QMessageBox.StandardButton.No) != QMessageBox.StandardButton.Yes: + return + button.setEnabled(False) + try: + result = self.adapter.execute(proposal) + self.chat.append(f"DSH:动作已提交 {result.get('action', proposal.name)}") + except Exception as error: + button.setEnabled(True) + self.chat.append(f"DSH:动作未执行:{error}") + diff --git a/src/dx_productivity/trial_task_center/ui/main_window.py b/src/dx_productivity/trial_task_center/ui/main_window.py index db5ccda..e1410f6 100644 --- a/src/dx_productivity/trial_task_center/ui/main_window.py +++ b/src/dx_productivity/trial_task_center/ui/main_window.py @@ -94,7 +94,7 @@ class TrialTaskCenterWindow(QMainWindow): self.move_mapping_down_button.clicked.connect(lambda: self._move_mapping(1)) self.plan_panel = ProjectPlanPanel(self) self.run_panel = RunPanel() - self.dsh_button = QPushButton('DSH AI 监管') + self.dsh_button = QPushButton('DSH助手') self.dsh_button.clicked.connect(self._open_dsh) self._log_presenter = TaskLogPresenter(service, self.run_panel, self) self.run_panel.quick_run_button.clicked.connect(self._prepare_quick_run) diff --git a/tests/dsh/test_core.py b/tests/dsh/test_core.py index 95b0acc..b228a54 100644 --- a/tests/dsh/test_core.py +++ b/tests/dsh/test_core.py @@ -1,4 +1,4 @@ -from dx_productivity.dsh.actions import validate_action +from dx_productivity.dsh.actions import validate_action, validate_model_actions from dx_productivity.dsh.client import DshClientError, DshConfig, OpenAICompatibleClient from dx_productivity.dsh.rules import classify from dx_productivity.dsh.snapshot import TaskSnapshot @@ -40,3 +40,14 @@ def test_unknown_action_and_unconfigured_client_fail_closed(): assert str(error) == "dsh_model_not_configured" else: raise AssertionError("unconfigured client accepted") + + +def test_model_actions_are_bound_to_current_task_and_confirmation_is_forced(): + actions = validate_model_actions([{"name": "pause_task", "task_id": "t", "requires_confirmation": False}], task_id="t") + assert actions[0].requires_confirmation is True + try: + validate_model_actions([{"name": "retry_failed", "task_id": "other"}], task_id="t") + except ValueError as error: + assert str(error) == "dsh_action_task_mismatch" + else: + raise AssertionError("cross-task action accepted")