feat: enforce DSH assistant capability boundaries

This commit is contained in:
阿白叔 committed 2026-10-30 09:23:48 +08:00
1 parent b84afbfa8a
commit d667fa6c57
6 files changed
+67 -7

No files matched your search

+2 -2
View File
@@ -1,5 +1,5 @@
# DSH AI 监管助手
# DSH助手
DSH 是任务中心内的工具型监管入口。它先使用本地规则识别失败、超时和不确定状态;明确失败可生成一次性的重试动作。模型只负责解释和提出结构化建议,不能直接调用 CAD、Shell、文件系统或任意网络工具。
打开任务中心的“DSH AI 监管”后,可以查看当前任务状态并进行人工对话。未配置 DeepSeek/OpenAI 兼容接口时,对话会明确提示,但本地监管和固定动作仍然可用。工程写入、规则修改和不确定状态恢复始终需要人工确认。
打开任务中心的“DSH助手”后,可以查看当前任务状态并进行人工对话。未配置 DeepSeek/OpenAI 兼容接口时,对话会明确提示,但本地监管和固定动作仍然可用。模型动作最多 3 个,必须绑定当前任务;未知动作、跨任务参数和非法 JSON 会被拒绝。工程写入、规则修改和不确定状态恢复始终需要人工确认。
+17 -1
View File
@@ -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
+7 -1
View File
@@ -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
@@ -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}")
@@ -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)
+12 -1
View File
@@ -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")