feat: add DSH AI supervision core

This commit is contained in:
阿白叔 committed 2026-10-30 09:22:40 +08:00
1 parent 12895e9868
commit bf14b20a38
13 files changed
+382

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
"""Tool-first AI supervision for the task center."""
from .actions import ActionProposal, validate_action
from .snapshot import TaskSnapshot, redact_snapshot
from .supervisor import DshSupervisor
__all__ = ["ActionProposal", "DshSupervisor", "TaskSnapshot", "redact_snapshot", "validate_action"]
+34
View File
@@ -0,0 +1,34 @@
from __future__ import annotations
from dataclasses import dataclass
from hashlib import sha256
from typing import Any, Mapping
ALLOWED_ACTIONS = {"retry_failed", "pause_task", "refresh_snapshot"}
@dataclass(frozen=True)
class ActionProposal:
name: str
task_id: str
reason: str = ""
requires_confirmation: bool = False
@property
def idempotency_key(self) -> str:
return sha256(f"{self.name}:{self.task_id}".encode()).hexdigest()[:20]
def as_dict(self) -> dict[str, Any]:
return {"name": self.name, "task_id": self.task_id, "reason": self.reason,
"requires_confirmation": self.requires_confirmation, "idempotency_key": self.idempotency_key}
def validate_action(raw: Mapping[str, Any]) -> ActionProposal:
if not isinstance(raw, Mapping) or raw.get("name") not in ALLOWED_ACTIONS:
raise ValueError("unknown_dsh_action")
task_id = str(raw.get("task_id", "")).strip()
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)))
+47
View File
@@ -0,0 +1,47 @@
from __future__ import annotations
import json
import urllib.error
import urllib.request
from dataclasses import dataclass
from typing import Any, Mapping
class DshClientError(RuntimeError):
pass
@dataclass(frozen=True)
class DshConfig:
base_url: str = ""
model: str = ""
api_key: str = ""
timeout: float = 30.0
@property
def configured(self) -> bool:
return bool(self.base_url and self.model and self.api_key)
class OpenAICompatibleClient:
def __init__(self, config: DshConfig):
self.config = config
def chat(self, message: str, snapshot: Mapping[str, Any]) -> dict[str, Any]:
if not self.config.configured:
raise DshClientError("dsh_model_not_configured")
body = json.dumps({"model": self.config.model, "temperature": 0,
"messages": [{"role": "system", "content": "只返回 JSON:{reply,actions}; 不执行任何操作。"},
{"role": "user", "content": json.dumps({"message": message, "snapshot": snapshot}, ensure_ascii=False)}]}).encode()
request = urllib.request.Request(self.config.base_url.rstrip("/") + "/chat/completions", data=body,
headers={"Content-Type": "application/json", "Authorization": f"Bearer {self.config.api_key}"})
try:
with urllib.request.urlopen(request, timeout=self.config.timeout) as response:
payload = json.loads(response.read().decode("utf-8"))
content = payload["choices"][0]["message"]["content"]
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):
raise DshClientError("dsh_model_response_invalid")
return result
+24
View File
@@ -0,0 +1,24 @@
from __future__ import annotations
from .actions import ActionProposal
from .snapshot import TaskSnapshot
def classify(snapshot: TaskSnapshot) -> str:
status = snapshot.status.casefold()
code = snapshot.issue_code.casefold()
if status in {"uncertain", "blocked"} or "uncertain" in code:
return "manual_review"
if status in {"failed", "error"} and code not in {"invalid_rule", "permission_denied"}:
return "retryable"
if status in {"timeout", "timed_out"}:
return "retryable"
if status == "paused":
return "paused"
return "observe"
def automatic_proposal(snapshot: TaskSnapshot) -> ActionProposal | None:
if classify(snapshot) != "retryable":
return None
return ActionProposal("retry_failed", snapshot.task_id, "明确失败且未进入不确定状态")
@@ -0,0 +1,23 @@
from __future__ import annotations
from typing import Any
from .actions import ActionProposal
class DshServiceAdapter:
"""Fixed action bridge; no model supplied values reach the service."""
def __init__(self, service):
self.service = service
def execute(self, proposal: ActionProposal) -> dict[str, Any]:
if proposal.name == "retry_failed":
self.service.prepare_failed_quick_run(proposal.task_id)
return {"status": "accepted", "action": proposal.name, "task_id": proposal.task_id}
if proposal.name == "pause_task":
self.service.pause_task(proposal.task_id)
return {"status": "accepted", "action": proposal.name, "task_id": proposal.task_id}
if proposal.name == "refresh_snapshot":
return {"status": "observed", "action": proposal.name, "task_id": proposal.task_id}
raise ValueError("unknown_dsh_action")
+35
View File
@@ -0,0 +1,35 @@
from __future__ import annotations
from dataclasses import asdict, dataclass, field
from typing import Any, Mapping
@dataclass(frozen=True)
class TaskSnapshot:
task_id: str
status: str
progress: Mapping[str, Any] = field(default_factory=dict)
issue: str = ""
issue_code: str = ""
rules_count: int = 0
def safe_dict(self) -> dict[str, Any]:
return redact_snapshot(asdict(self))
def redact_snapshot(value: Mapping[str, Any]) -> dict[str, Any]:
"""Keep only bounded diagnostic fields; never leak paths, secrets, or payloads."""
progress = value.get("progress") if isinstance(value.get("progress"), Mapping) else {}
safe_progress = {
key: progress[key]
for key in ("completed", "total", "saved_items", "failed_items", "no_match_items")
if key in progress and isinstance(progress[key], (int, float, str, bool, type(None)))
}
return {
"task_id": str(value.get("task_id", ""))[:128],
"status": str(value.get("status", ""))[:32],
"issue": str(value.get("issue", ""))[:500],
"issue_code": str(value.get("issue_code", ""))[:80],
"rules_count": int(value.get("rules_count", 0) or 0),
"progress": safe_progress,
}
+26
View File
@@ -0,0 +1,26 @@
from __future__ import annotations
from collections.abc import Callable
from typing import Any
from .actions import ActionProposal
from .rules import automatic_proposal, classify
from .snapshot import TaskSnapshot
class DshSupervisor:
def __init__(self, action_handler: Callable[[ActionProposal], Any] | None = None):
self.action_handler = action_handler
self.history: list[dict[str, Any]] = []
self._completed: set[str] = set()
def observe(self, snapshot: TaskSnapshot, *, auto: bool = True) -> dict[str, Any]:
proposal = automatic_proposal(snapshot) if auto else None
result: Any = None
if proposal and proposal.idempotency_key not in self._completed and self.action_handler:
result = self.action_handler(proposal)
self._completed.add(proposal.idempotency_key)
record = {"snapshot": snapshot.safe_dict(), "classification": classify(snapshot),
"proposal": proposal.as_dict() if proposal else None, "result": result}
self.history.append(record)
return record