优化: 工具调用标识类型安全加固

This commit is contained in:
lxy
2026-08-10 08:04:30 +08:00
parent 5a1b7a871a
commit 256af4e736
5 changed files with 86 additions and 11 deletions
+67
View File
@@ -84,6 +84,73 @@ impl PartialEq<String> for ExecutionId {
}
}
/// 工具调用 ID(跨 ai_tool_executions / tool_calls 关联键,IPC 边界透明序列化为字符串)
///
/// branded newtype:编译器拒绝把任意 String 当 ToolCallId 传入,防误传(如把
/// execution_id 当 tool_call_id 落库)。serde `transparent` 保证 JSON 形态为纯字符串,
/// 前端零感知。设计同 [`ExecutionId`] / [`ToolCallType`],手写不抽宏(全仓仅 3 个
/// 字符串 newtype,抽 macro_rules 增心智成本无收益)。
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Default)]
#[serde(transparent)]
pub struct ToolCallId(String);
impl ToolCallId {
/// 构造新工具调用 ID
pub fn new(s: impl Into<String>) -> Self {
Self(s.into())
}
}
impl std::fmt::Display for ToolCallId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::ops::Deref for ToolCallId {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
impl From<String> for ToolCallId {
fn from(s: String) -> Self {
Self(s)
}
}
impl From<&str> for ToolCallId {
fn from(s: &str) -> Self {
Self(s.to_owned())
}
}
impl From<ToolCallId> for String {
fn from(id: ToolCallId) -> Self {
id.0
}
}
// ToolCallId 与 &str/String 的比较(测试/匹配中大量使用,与 ExecutionId 对齐)
impl PartialEq<&str> for ToolCallId {
fn eq(&self, other: &&str) -> bool {
self.0 == *other
}
}
impl PartialEq<str> for ToolCallId {
fn eq(&self, other: &str) -> bool {
self.0 == other
}
}
impl PartialEq<String> for ToolCallId {
fn eq(&self, other: &String) -> bool {
self.0 == *other
}
}
/// 决策 ID
pub type DecisionId = String;
/// 节点类型(如 ai / human / ai_self_review)