mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-09-05 23:47:41 +08:00
feat(agent): 建立严格工具身份与调用契约 (#6280)
This commit is contained in:
@@ -4,9 +4,14 @@ from app.agent.policy.contracts import (
|
||||
ActionEffect,
|
||||
ActionPolicy,
|
||||
AuthSource,
|
||||
CanonicalInvocation,
|
||||
ConversationKind,
|
||||
DeliveryTarget,
|
||||
ConfirmationMode,
|
||||
ExecutionOutcome,
|
||||
ExecutionReceipt,
|
||||
InboundEnvelope,
|
||||
InboundProvenance,
|
||||
MigrationState,
|
||||
PolicyDecision,
|
||||
PolicyObservation,
|
||||
@@ -14,10 +19,14 @@ from app.agent.policy.contracts import (
|
||||
PrincipalRole,
|
||||
PrincipalType,
|
||||
RecoveryMode,
|
||||
RECEIPT_STATE_TRANSITIONS,
|
||||
ReceiptState,
|
||||
ResultSensitivity,
|
||||
TERMINAL_RECEIPT_STATES,
|
||||
ToolInvocation,
|
||||
ToolOrigin,
|
||||
ToolPolicyContext,
|
||||
ToolRevision,
|
||||
)
|
||||
from app.agent.policy.orchestrator import (
|
||||
DEFAULT_TOOL_POLICY_ORCHESTRATOR,
|
||||
@@ -39,11 +48,16 @@ __all__ = [
|
||||
"ActionPolicy",
|
||||
"AgentToolPolicyOrchestrator",
|
||||
"AuthSource",
|
||||
"CanonicalInvocation",
|
||||
"ConversationKind",
|
||||
"DeliveryTarget",
|
||||
"ConfirmationMode",
|
||||
"DEFAULT_TOOL_POLICY_ORCHESTRATOR",
|
||||
"DEFAULT_TOOL_POLICY_REGISTRY",
|
||||
"ExecutionOutcome",
|
||||
"ExecutionReceipt",
|
||||
"InboundEnvelope",
|
||||
"InboundProvenance",
|
||||
"MigrationState",
|
||||
"PolicyDecision",
|
||||
"PolicyObservation",
|
||||
@@ -52,10 +66,14 @@ __all__ = [
|
||||
"PrincipalType",
|
||||
"REDACTED_VALUE",
|
||||
"RecoveryMode",
|
||||
"RECEIPT_STATE_TRANSITIONS",
|
||||
"ReceiptState",
|
||||
"ResultSensitivity",
|
||||
"TERMINAL_RECEIPT_STATES",
|
||||
"ToolInvocation",
|
||||
"ToolOrigin",
|
||||
"ToolPolicyContext",
|
||||
"ToolRevision",
|
||||
"ToolPolicyRegistry",
|
||||
"call_policy_hook",
|
||||
"sanitize_for_host",
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
"""严格工具调用规范化,不读取设置值或执行工具实现。"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from typing import Any, Mapping
|
||||
|
||||
from pydantic import BaseModel, ValidationError
|
||||
|
||||
from app.agent.policy.contracts import (
|
||||
ActionPolicy,
|
||||
CanonicalInvocation,
|
||||
ToolRevision,
|
||||
)
|
||||
from app.agent.tools.impl._system_setting_utils import (
|
||||
list_setting_specs,
|
||||
resolve_setting_spec,
|
||||
)
|
||||
|
||||
|
||||
class CanonicalizationError(ValueError):
|
||||
"""当前工具 schema 或静态前提无法产生严格调用时的稳定失败。"""
|
||||
|
||||
|
||||
def _stable_json(value: Any) -> str:
|
||||
"""生成拒绝 NaN 且保留 Unicode 的稳定紧凑 JSON。"""
|
||||
try:
|
||||
return json.dumps(
|
||||
value,
|
||||
ensure_ascii=False,
|
||||
allow_nan=False,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
)
|
||||
except (TypeError, ValueError, ValidationError) as error:
|
||||
raise CanonicalizationError("调用参数无法规范化") from error
|
||||
|
||||
|
||||
def _accepted_argument_names(args_schema: type[BaseModel]) -> set[str]:
|
||||
"""返回严格入口可接受的字段名与字符串别名。"""
|
||||
accepted = set(args_schema.model_fields)
|
||||
for field in args_schema.model_fields.values():
|
||||
for alias in (field.alias, field.validation_alias):
|
||||
if isinstance(alias, str):
|
||||
accepted.add(alias)
|
||||
return accepted
|
||||
|
||||
|
||||
def canonicalize_invocation(
|
||||
*,
|
||||
tool: Any,
|
||||
arguments: Mapping[str, Any],
|
||||
policy: ActionPolicy,
|
||||
tool_revision: ToolRevision,
|
||||
) -> CanonicalInvocation:
|
||||
"""使用当前 Pydantic schema 与静态设置定义生成不可变调用摘要。"""
|
||||
tool_name = str(getattr(tool, "name", "") or "")
|
||||
args_schema = getattr(tool, "args_schema", None)
|
||||
if not tool_name or not isinstance(args_schema, type) or not issubclass(
|
||||
args_schema, BaseModel
|
||||
):
|
||||
raise CanonicalizationError("工具缺少严格 Pydantic 参数契约")
|
||||
raw_arguments = dict(arguments or {})
|
||||
unknown_arguments = set(raw_arguments) - _accepted_argument_names(args_schema)
|
||||
if unknown_arguments:
|
||||
raise CanonicalizationError("工具参数校验失败")
|
||||
try:
|
||||
validated = args_schema.model_validate(raw_arguments)
|
||||
normalized = validated.model_dump(
|
||||
mode="json",
|
||||
exclude_unset=False,
|
||||
exclude_none=False,
|
||||
)
|
||||
schema_json = _stable_json(args_schema.model_json_schema())
|
||||
except (TypeError, ValueError) as error:
|
||||
raise CanonicalizationError("工具参数校验失败") from error
|
||||
|
||||
preconditions: tuple[tuple[str, str], ...] = ()
|
||||
setting_key = normalized.get("setting_key")
|
||||
if tool_name == "query_system_settings":
|
||||
if setting_key:
|
||||
spec = resolve_setting_spec(setting_key)
|
||||
if spec is None:
|
||||
raise CanonicalizationError("系统设置项不存在")
|
||||
specs = [spec]
|
||||
else:
|
||||
try:
|
||||
specs = list_setting_specs(
|
||||
group=normalized.get("group"),
|
||||
keyword=normalized.get("keyword"),
|
||||
)
|
||||
except ValueError as error:
|
||||
raise CanonicalizationError("系统设置选择器无效") from error
|
||||
if not specs:
|
||||
raise CanonicalizationError("系统设置选择器没有匹配项")
|
||||
preconditions = tuple(
|
||||
(
|
||||
"setting",
|
||||
f"{spec.source}:{spec.key}:{spec.group}",
|
||||
)
|
||||
for spec in specs
|
||||
)
|
||||
|
||||
payload = {
|
||||
"canonical_version": "p1-g2a2-canonical-v1",
|
||||
"action_subtype": policy.effect.value,
|
||||
"arguments": normalized,
|
||||
"policy_version": policy.policy_version,
|
||||
"preconditions": preconditions,
|
||||
"schema_digest": hashlib.sha256(schema_json.encode("utf-8")).hexdigest(),
|
||||
"tool_name": tool_name,
|
||||
"tool_revision": {
|
||||
"factory": tool_revision.factory,
|
||||
"implementation": tool_revision.implementation,
|
||||
"plugin": tool_revision.plugin,
|
||||
},
|
||||
}
|
||||
canonical_json = _stable_json(payload)
|
||||
return CanonicalInvocation(
|
||||
tool_name=tool_name,
|
||||
arguments=normalized,
|
||||
canonical_json=canonical_json,
|
||||
digest=hashlib.sha256(canonical_json.encode("utf-8")).hexdigest(),
|
||||
policy_version=policy.policy_version,
|
||||
tool_revision=tool_revision,
|
||||
schema_digest=payload["schema_digest"],
|
||||
preconditions=preconditions,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["CanonicalizationError", "canonicalize_invocation"]
|
||||
@@ -2,9 +2,23 @@
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum
|
||||
from types import MappingProxyType
|
||||
from typing import Any, Mapping, MutableMapping, Optional
|
||||
|
||||
|
||||
def _freeze_contract_value(value: Any) -> Any:
|
||||
"""递归冻结确认边界中的容器,避免等待期间被调用方修改。"""
|
||||
if isinstance(value, Mapping):
|
||||
return MappingProxyType(
|
||||
{str(key): _freeze_contract_value(item) for key, item in value.items()}
|
||||
)
|
||||
if isinstance(value, (list, tuple)):
|
||||
return tuple(_freeze_contract_value(item) for item in value)
|
||||
if isinstance(value, set):
|
||||
return frozenset(_freeze_contract_value(item) for item in value)
|
||||
return value
|
||||
|
||||
|
||||
class ToolOrigin(str, Enum):
|
||||
"""工具调用的宿主可信入口。"""
|
||||
|
||||
@@ -35,6 +49,24 @@ class AuthSource(str, Enum):
|
||||
AGENT_TOKEN = "agent_token"
|
||||
|
||||
|
||||
class InboundProvenance(str, Enum):
|
||||
"""入站事实经宿主验证后的可信等级。"""
|
||||
|
||||
WEB_SESSION = "web_session"
|
||||
VERIFIED_ADAPTER = "verified_adapter"
|
||||
ADMIN_INTEGRATION = "admin_integration"
|
||||
UNTRUSTED = "untrusted"
|
||||
|
||||
|
||||
class ConversationKind(str, Enum):
|
||||
"""目标会话的隐私边界。"""
|
||||
|
||||
WEB = "web"
|
||||
PRIVATE = "private"
|
||||
GROUP = "group"
|
||||
UNKNOWN = "unknown"
|
||||
|
||||
|
||||
class PrincipalRole(str, Enum):
|
||||
"""策略授权使用的角色层级。"""
|
||||
|
||||
@@ -99,6 +131,79 @@ class ExecutionOutcome(str, Enum):
|
||||
FAILED = "failed"
|
||||
|
||||
|
||||
class ReceiptState(str, Enum):
|
||||
"""严格执行回执的单向生命周期状态。"""
|
||||
|
||||
WAITING_CONFIRMATION = "waiting_confirmation"
|
||||
VALIDATING = "validating"
|
||||
EXECUTING = "executing"
|
||||
DELIVERING = "delivering"
|
||||
SUCCEEDED = "succeeded"
|
||||
CANCELLED = "cancelled"
|
||||
EXPIRED = "expired"
|
||||
EXPIRED_RESTART = "expired_restart"
|
||||
EXPIRED_ORPHANED = "expired_orphaned"
|
||||
PREPARATION_FAILED = "preparation_failed"
|
||||
PROMPT_DELIVERY_FAILED = "prompt_delivery_failed"
|
||||
VALIDATION_FAILED = "validation_failed"
|
||||
VALIDATION_RECORD_FAILED = "validation_record_failed"
|
||||
EXECUTION_FAILED = "execution_failed"
|
||||
DELIVERY_FAILED = "delivery_failed"
|
||||
UNKNOWN_AFTER_RESTART = "unknown_after_restart"
|
||||
UNKNOWN_ORPHANED = "unknown_orphaned"
|
||||
|
||||
|
||||
TERMINAL_RECEIPT_STATES = frozenset({
|
||||
ReceiptState.SUCCEEDED,
|
||||
ReceiptState.CANCELLED,
|
||||
ReceiptState.EXPIRED,
|
||||
ReceiptState.EXPIRED_RESTART,
|
||||
ReceiptState.EXPIRED_ORPHANED,
|
||||
ReceiptState.PREPARATION_FAILED,
|
||||
ReceiptState.PROMPT_DELIVERY_FAILED,
|
||||
ReceiptState.VALIDATION_FAILED,
|
||||
ReceiptState.VALIDATION_RECORD_FAILED,
|
||||
ReceiptState.EXECUTION_FAILED,
|
||||
ReceiptState.DELIVERY_FAILED,
|
||||
ReceiptState.UNKNOWN_AFTER_RESTART,
|
||||
ReceiptState.UNKNOWN_ORPHANED,
|
||||
})
|
||||
|
||||
|
||||
RECEIPT_STATE_TRANSITIONS = {
|
||||
ReceiptState.WAITING_CONFIRMATION: frozenset({
|
||||
ReceiptState.VALIDATING,
|
||||
ReceiptState.CANCELLED,
|
||||
ReceiptState.EXPIRED,
|
||||
ReceiptState.EXPIRED_RESTART,
|
||||
ReceiptState.EXPIRED_ORPHANED,
|
||||
ReceiptState.PREPARATION_FAILED,
|
||||
ReceiptState.PROMPT_DELIVERY_FAILED,
|
||||
}),
|
||||
ReceiptState.VALIDATING: frozenset({
|
||||
ReceiptState.EXECUTING,
|
||||
ReceiptState.CANCELLED,
|
||||
ReceiptState.EXPIRED,
|
||||
ReceiptState.EXPIRED_RESTART,
|
||||
ReceiptState.EXPIRED_ORPHANED,
|
||||
ReceiptState.VALIDATION_FAILED,
|
||||
ReceiptState.VALIDATION_RECORD_FAILED,
|
||||
}),
|
||||
ReceiptState.EXECUTING: frozenset({
|
||||
ReceiptState.DELIVERING,
|
||||
ReceiptState.EXECUTION_FAILED,
|
||||
ReceiptState.UNKNOWN_AFTER_RESTART,
|
||||
ReceiptState.UNKNOWN_ORPHANED,
|
||||
}),
|
||||
ReceiptState.DELIVERING: frozenset({
|
||||
ReceiptState.SUCCEEDED,
|
||||
ReceiptState.DELIVERY_FAILED,
|
||||
ReceiptState.UNKNOWN_AFTER_RESTART,
|
||||
ReceiptState.UNKNOWN_ORPHANED,
|
||||
}),
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PolicyPrincipal:
|
||||
"""由可信入口建立、不可由工具参数覆盖的调用主体。"""
|
||||
@@ -124,6 +229,62 @@ class ToolInvocation:
|
||||
source: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DeliveryTarget:
|
||||
"""受保护结果的精确宿主路由,actor 与 recipient 不得互相替代。"""
|
||||
|
||||
channel: str
|
||||
source_instance_id: str
|
||||
tenant_or_account_id: str
|
||||
conversation_kind: ConversationKind
|
||||
conversation_id: str
|
||||
recipient_id: str
|
||||
actor_id: str
|
||||
server_session_id: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InboundEnvelope:
|
||||
"""由可信宿主入口创建的不可变入站事实。"""
|
||||
|
||||
provenance: InboundProvenance
|
||||
target: DeliveryTarget
|
||||
inbound_event_id: str
|
||||
raw_text: str = field(repr=False)
|
||||
normalized_text: str = field(repr=False)
|
||||
has_images: bool = False
|
||||
has_audio: bool = False
|
||||
has_files: bool = False
|
||||
is_callback: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ToolRevision:
|
||||
"""严格调用绑定的工具实现、工厂和插件目录版本。"""
|
||||
|
||||
implementation: str
|
||||
factory: str
|
||||
plugin: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CanonicalInvocation:
|
||||
"""经当前工具 schema 校验、可绑定确认与版本前提的调用。"""
|
||||
|
||||
tool_name: str
|
||||
arguments: Mapping[str, Any] = field(repr=False)
|
||||
canonical_json: str = field(repr=False)
|
||||
digest: str
|
||||
policy_version: str
|
||||
tool_revision: ToolRevision
|
||||
schema_digest: str
|
||||
preconditions: tuple[tuple[str, str], ...] = ()
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
"""阻止调用方在确认等待期间修改规范化参数。"""
|
||||
object.__setattr__(self, "arguments", _freeze_contract_value(self.arguments))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ActionPolicy:
|
||||
"""参数级动作策略及其兼容迁移状态。"""
|
||||
@@ -230,9 +391,14 @@ __all__ = [
|
||||
"ActionEffect",
|
||||
"ActionPolicy",
|
||||
"AuthSource",
|
||||
"CanonicalInvocation",
|
||||
"ConfirmationMode",
|
||||
"ConversationKind",
|
||||
"DeliveryTarget",
|
||||
"ExecutionOutcome",
|
||||
"ExecutionReceipt",
|
||||
"InboundEnvelope",
|
||||
"InboundProvenance",
|
||||
"MigrationState",
|
||||
"PolicyDecision",
|
||||
"PolicyObservation",
|
||||
@@ -240,8 +406,12 @@ __all__ = [
|
||||
"PrincipalRole",
|
||||
"PrincipalType",
|
||||
"RecoveryMode",
|
||||
"RECEIPT_STATE_TRANSITIONS",
|
||||
"ReceiptState",
|
||||
"ResultSensitivity",
|
||||
"TERMINAL_RECEIPT_STATES",
|
||||
"ToolInvocation",
|
||||
"ToolOrigin",
|
||||
"ToolPolicyContext",
|
||||
"ToolRevision",
|
||||
]
|
||||
|
||||
@@ -9,6 +9,7 @@ from langchain_core.messages import ToolMessage
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.agent.policy.contracts import (
|
||||
ConfirmationMode,
|
||||
ExecutionOutcome,
|
||||
ExecutionReceipt,
|
||||
MigrationState,
|
||||
@@ -101,6 +102,14 @@ class AgentToolPolicyOrchestrator:
|
||||
shadow=True,
|
||||
reason_code="legacy_shadow_allow",
|
||||
)
|
||||
elif policy.confirmation is ConfirmationMode.REQUIRED:
|
||||
# 严格运行时接管前保持既有调用能力,但不得把敏感动作记为安全读取。
|
||||
decision = PolicyDecision(
|
||||
allowed=True,
|
||||
confirmation_required=False,
|
||||
shadow=True,
|
||||
reason_code="strict_runtime_pending",
|
||||
)
|
||||
else:
|
||||
decision = PolicyDecision(
|
||||
allowed=True,
|
||||
|
||||
@@ -140,10 +140,25 @@ class ToolPolicyRegistry:
|
||||
requires_admin: bool,
|
||||
) -> ActionPolicy:
|
||||
"""根据工具名和宿主权限声明解析当前迁移策略。"""
|
||||
del arguments # 参数级迁移由后续领域 Goal 逐项加入。
|
||||
required_role = (
|
||||
PrincipalRole.SYSTEM_ADMIN if requires_admin else PrincipalRole.USER
|
||||
)
|
||||
if (
|
||||
tool_name == "query_system_settings"
|
||||
and arguments.get("show_secrets") is True
|
||||
):
|
||||
return ActionPolicy(
|
||||
effect=ActionEffect.SENSITIVE_READ,
|
||||
required_role=PrincipalRole.SYSTEM_ADMIN,
|
||||
confirmation=ConfirmationMode.REQUIRED,
|
||||
recovery=RecoveryMode.NONE,
|
||||
result_sensitivity=ResultSensitivity.SECRET,
|
||||
migration_state=MigrationState.ENFORCED,
|
||||
policy_version="p1-g2a2-v1",
|
||||
machine_allowed=True,
|
||||
background_allowed=False,
|
||||
subagent_allowed=False,
|
||||
)
|
||||
if tool_name in self._safe_read_tool_names:
|
||||
return ActionPolicy(
|
||||
effect=ActionEffect.SAFE_READ,
|
||||
|
||||
Reference in New Issue
Block a user