1011 lines
39 KiB
Markdown
1011 lines
39 KiB
Markdown
# 灵隙协议实现规范:人工介入(HiL)三级升级机制
|
||
|
||
> 版本:1.0.0 | 层级:实现层
|
||
|
||
---
|
||
|
||
## 目录
|
||
|
||
1. [升级级别定义](#1-升级级别定义)
|
||
2. [HiL 状态流转](#2-hil-状态流转)
|
||
3. [HiL 请求结构](#3-hil-请求结构)
|
||
4. [升级判定规则](#4-升级判定规则)
|
||
5. [人工响应结构](#5-人工响应结构)
|
||
6. [超时与降级策略](#6-超时与降级策略)
|
||
7. [通知渠道规范](#7-通知渠道规范)
|
||
8. [审计与日志](#8-审计与日志)
|
||
|
||
---
|
||
|
||
## 1. 升级级别定义
|
||
|
||
HiL(Human-in-the-Loop)三级升级机制根据决策的重要性、紧急程度和风险等级,将人工介入分为三个级别。
|
||
|
||
### 1.1 级别总览
|
||
|
||
| 级别 | 名称 | 默认超时 | 紧急超时 | 决策者 | 适用场景 |
|
||
|-----|------|---------|---------|-------|---------|
|
||
| **Level 1** | Agent 建议 + 人确认 | 24 小时 | — | 任务发起人 / 值班人 | 信息缺失、创意方向、用户主动请求 |
|
||
| **Level 2** | 必须人工决策 | 12 小时 | 2 小时 | 领域负责人 / 审核专员 | 品牌风格、合规审查、能力不足、高风险操作 |
|
||
| **Level 3** | 专家 / 管理层决策 | 72 小时 | 24 小时 | 专家委员会 / 管理层 | 战略决策、重大争议、跨系统冲突 |
|
||
|
||
### 1.2 Level 1:Agent 建议 + 人确认
|
||
|
||
**定位**:低风险、低成本的快速确认。Agent 提供建议方案,人类只需确认或微调。
|
||
|
||
**触发条件**:
|
||
|
||
| 触发代码 | 场景描述 | 示例 |
|
||
|---------|---------|------|
|
||
| `INFO_MISSING` | Agent 缺少关键信息,需要人类补充 | 客户未提供明确的需求规格 |
|
||
| `CREATIVE_DIRECTION` | 创意方向需人类确认 | Logo 设计方案初选 |
|
||
| `USER_REQUESTED` | 用户主动要求人工介入 | 用户明确要求"请人工审核" |
|
||
| `CONTENT_REVIEW` | 内容发布前快速确认 | 推文、公告文案确认 |
|
||
| `PREFERENCE_CONFIRM` | 偏好确认 | 颜色、字体等视觉偏好选择 |
|
||
|
||
**行为规范**:
|
||
|
||
- Agent 必须提供明确的建议值(`SuggestedValue`)
|
||
- 人类可执行的操作:**批准**、**修改后批准**、**拒绝并说明原因**
|
||
- 超时默认策略:**自动以 Agent 建议值继续执行**
|
||
- 升级频率限制:同一任务单日不超过 5 次 Level 1 升级
|
||
|
||
### 1.3 Level 2:必须人工决策
|
||
|
||
**定位**:中高风险,必须由具备相应领域知识的人类做出决策,Agent 不可自行决定。
|
||
|
||
**触发条件**:
|
||
|
||
| 触发代码 | 场景描述 | 示例 |
|
||
|---------|---------|------|
|
||
| `BRAND_STYLE` | 品牌风格相关决策 | 品牌色调、VI 元素使用 |
|
||
| `COMPLIANCE` | 合规要求判定 | 数据隐私法规、行业合规 |
|
||
| `CAPABILITY_LACKING` | Agent 能力不足以完成任务 | 需要特定领域专家的判断 |
|
||
| `HIGH_COST_RISK` | 高成本或高风险操作 | 预算超过阈值、涉及敏感操作 |
|
||
| `RESOURCE_DEADLOCK` | 资源死锁或竞争 | 多个 Agent 争夺同一资源 |
|
||
| `SENSITIVE_CONTENT` | 敏感内容判定 | 涉及政治、色情、暴力等内容 |
|
||
| `THIRD_PARTY_ESCALATION` | 第三方系统接入审批 | 外部 API 调用、数据交换审批 |
|
||
|
||
**行为规范**:
|
||
|
||
- Agent 必须提供完整的决策上下文(`Context`),包括推理过程和依据
|
||
- Agent 应提供至少 2 个可选方案(`Options`),并分析各自的优缺点
|
||
- 人类可执行的操作:**批准某一方案**、**驳回并要求补充信息**、**修改方案后执行**
|
||
- 超时默认策略:**升级至 Level 3**(不可自动通过或拒绝)
|
||
- 紧急模式下(`HIGH_COST_RISK`、`SENSITIVE_CONTENT`),超时缩短为 **2 小时**
|
||
|
||
### 1.4 Level 3:专家 / 管理层决策
|
||
|
||
**定位**:最高级别的决策层级,涉及战略方向、重大争议和跨系统冲突,必须由专家委员会或管理层做出最终裁决。
|
||
|
||
**触发条件**:
|
||
|
||
| 触发代码 | 场景描述 | 示例 |
|
||
|---------|---------|------|
|
||
| `STRATEGIC_DECISION` | 战略级决策 | 产品方向、市场策略、合作伙伴选择 |
|
||
| `MAJOR_DISPUTE` | 重大争议 | Agent 之间无法达成共识,且影响重大 |
|
||
| `CROSS_SYSTEM_CONFLICT` | 跨系统冲突 | 两个独立系统间的数据或资源冲突 |
|
||
| `LEVEL2_TIMEOUT_ESCALATED` | Level 2 超时升级 | Level 2 超时后自动升级 |
|
||
| `POLICY_EXCEPTION` | 策略例外申请 | 需要突破既定策略的特殊情况 |
|
||
| `CRISIS_RESPONSE` | 危机响应 | 安全事件、数据泄露、服务中断 |
|
||
|
||
**行为规范**:
|
||
|
||
- Agent 必须提供完整的背景报告,包括事件时间线、影响范围、可选方案及风险评估
|
||
- 需要至少 **2 位** 具备相应权限的决策者参与
|
||
- 决策方式:**投票制**(简单多数或加权投票,根据场景配置)
|
||
- 超时默认策略:**任务挂起**(不自动执行任何操作),等待人工跟进
|
||
- 所有 Level 3 决策必须记录完整的审计日志
|
||
|
||
### 1.5 级别间关系
|
||
|
||
```
|
||
Level 1 ──超时──→ 自动以建议值执行
|
||
│
|
||
├──复杂情况──→ Level 2
|
||
│
|
||
Level 2 ──超时──→ Level 3
|
||
│
|
||
├──驳回并要求补充──→ Level 1 / Level 2(重新提交)
|
||
│
|
||
Level 3 ──超时──→ 任务挂起(等待人工)
|
||
│
|
||
└──决策完成──→ 任务继续执行或终止
|
||
```
|
||
|
||
---
|
||
|
||
## 2. HiL 状态流转
|
||
|
||
### 2.1 状态定义
|
||
|
||
```go
|
||
type HILStatus string
|
||
|
||
const (
|
||
// 初始状态:请求已创建,尚未进入人工队列
|
||
HILStatusPending HILStatus = "pending"
|
||
|
||
// 等待状态:请求已进入人工队列,等待分配决策者
|
||
HILStatusWaiting HILStatus = "waiting"
|
||
|
||
// 决策中:决策者正在审阅中,尚未给出结论
|
||
HILStatusDeciding HILStatus = "deciding"
|
||
|
||
// 已批准:决策者批准了 Agent 的建议或某一方案
|
||
HILStatusApproved HILStatus = "approved"
|
||
|
||
// 已拒绝:决策者拒绝了所有方案
|
||
HILStatusRejected HILStatus = "rejected"
|
||
|
||
// 超时:在截止时间前未收到人工响应
|
||
HILStatusTimeout HILStatus = "timeout"
|
||
|
||
// 已升级:当前级别无法处理,升级至更高级别
|
||
HILStatusEscalated HILStatus = "escalated"
|
||
)
|
||
```
|
||
|
||
### 2.2 状态流转图
|
||
|
||
```
|
||
┌─────────────────────────────────────┐
|
||
│ 创建请求 │
|
||
│ HILStatusPending │
|
||
└────────────────┬────────────────────┘
|
||
│
|
||
▼
|
||
┌─────────────────────────────────────┐
|
||
│ 进入人工队列 │
|
||
│ HILStatusWaiting │
|
||
└────────────────┬────────────────────┘
|
||
│
|
||
┌───────────┴───────────┐
|
||
│ 分配决策者 │
|
||
▼ ▼
|
||
┌────────────────────────┐ ┌────────────────────┐
|
||
│ 决策者开始审阅 │ │ 超时未分配 │
|
||
│ HILStatusDeciding │ │ HILStatusTimeout │
|
||
└──────────┬─────────────┘ └─────────┬──────────┘
|
||
│ │
|
||
┌────────────┼────────────┬─────────────┘
|
||
▼ ▼ ▼
|
||
┌──────────┐ ┌──────────┐ ┌──────────────┐
|
||
│ 批准 │ │ 拒绝 │ │ 升级 │
|
||
│ Approved │ │ Rejected │ │ Escalated │
|
||
└──────────┘ └──────────┘ └──────┬───────┘
|
||
│
|
||
▼
|
||
┌────────────────────┐
|
||
│ 进入更高级别流程 │
|
||
│ Pending/Waiting │
|
||
└────────────────────┘
|
||
```
|
||
|
||
### 2.3 状态转移矩阵
|
||
|
||
| 当前状态 \ 目标状态 | pending | waiting | deciding | approved | rejected | timeout | escalated |
|
||
|-------------------|---------|---------|----------|----------|----------|---------|-----------|
|
||
| **pending** | — | ✔️ 入队 | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||
| **waiting** | ❌ | — | ✔️ 分配决策者 | ❌ | ❌ | ✔️ 超时未分配 | ✔️ 手动升级 |
|
||
| **deciding** | ❌ | ❌ | — | ✔️ 批准方案 | ✔️ 拒绝方案 | ✔️ 决策超时 | ✔️ 无法决策 |
|
||
| **approved** | ❌ | ❌ | ❌ | — | ❌ | ❌ | ❌ |
|
||
| **rejected** | ❌ | ❌ | ❌ | ❌ | — | ❌ | ❌ |
|
||
| **timeout** | ❌ | ❌ | ❌ | ❌ | ❌ | — | ✔️ 超时升级 |
|
||
| **escalated** | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | — |
|
||
|
||
### 2.4 状态流转 Hook
|
||
|
||
```go
|
||
// HILStatusHook - 状态变更回调接口
|
||
type HILStatusHook interface {
|
||
// OnStatusChanged - 状态变更时触发
|
||
OnStatusChanged(ctx context.Context, req *HILRequest, oldStatus, newStatus HILStatus) error
|
||
|
||
// OnEscalated - 升级时触发
|
||
OnEscalated(ctx context.Context, req *HILRequest, fromLevel, toLevel int) error
|
||
|
||
// OnTimeout - 超时时触发
|
||
OnTimeout(ctx context.Context, req *HILRequest) error
|
||
|
||
// OnDecisionMade - 决策完成时触发
|
||
OnDecisionMade(ctx context.Context, req *HILRequest, resp *HILResponse) error
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 3. HiL 请求结构
|
||
|
||
### 3.1 HILRequest
|
||
|
||
```go
|
||
type HILRequest struct {
|
||
// 基础标识
|
||
ID string `json:"id"` // 请求唯一 ID(UUID)
|
||
TaskID string `json:"task_id"` // 关联任务 ID
|
||
ParentRequestID string `json:"parent_request_id,omitempty"` // 父请求 ID(升级时关联)
|
||
|
||
// 升级信息
|
||
EscalationType EscalationType `json:"escalation_type"` // 升级类型
|
||
EscalationLevel int `json:"escalation_level"` // 升级级别(1/2/3)
|
||
SourceSystemID string `json:"source_system_id"` // 发起方系统 ID
|
||
SourceAgentID string `json:"source_agent_id"` // 发起方 Agent ID
|
||
|
||
// 决策内容
|
||
Reason HILReason `json:"reason"` // 介入原因
|
||
Context HILContext `json:"context"` // 决策上下文
|
||
Options []HILOption `json:"options"` // 可选方案(至少 1 个)
|
||
SuggestedValue any `json:"suggested_value"` // Agent 建议值
|
||
|
||
// 时间与状态
|
||
CreatedAt time.Time `json:"created_at"` // 创建时间
|
||
Deadline time.Time `json:"deadline"` // 截止时间
|
||
RespondedAt *time.Time `json:"responded_at,omitempty"` // 响应时间
|
||
Status HILStatus `json:"status"` // 当前状态
|
||
StatusHistory []StatusEntry `json:"status_history"` // 状态变更历史
|
||
|
||
// 响应
|
||
Response *HILResponse `json:"response,omitempty"` // 人工响应
|
||
AssignedTo []string `json:"assigned_to,omitempty"` // 指定决策者 ID 列表
|
||
AssignedRoles []string `json:"assigned_roles,omitempty"` // 指定决策角色
|
||
|
||
// 元数据
|
||
Priority int `json:"priority"` // 优先级(1-5,5 最高)
|
||
Tags map[string]string `json:"tags,omitempty"` // 自定义标签
|
||
Notified bool `json:"notified"` // 是否已发送通知
|
||
}
|
||
|
||
// EscalationType - 升级类型
|
||
type EscalationType string
|
||
|
||
const (
|
||
EscalationP2P EscalationType = "P2P" // 点对点升级
|
||
EscalationGROUP EscalationType = "GROUP" // 群组内升级
|
||
EscalationInterGROUP EscalationType = "INTER_GROUP" // 跨群组升级
|
||
EscalationSYSTEM EscalationType = "SYSTEM" // 系统级升级
|
||
)
|
||
|
||
// StatusEntry - 状态变更记录
|
||
type StatusEntry struct {
|
||
FromStatus HILStatus `json:"from_status"` // 原状态
|
||
ToStatus HILStatus `json:"to_status"` // 新状态
|
||
ChangedBy string `json:"changed_by"` // 变更者
|
||
Reason string `json:"reason"` // 变更原因
|
||
Timestamp time.Time `json:"timestamp"` // 变更时间
|
||
}
|
||
```
|
||
|
||
### 3.2 HILReason
|
||
|
||
```go
|
||
type HILReason struct {
|
||
Code HILReasonCode `json:"code"` // 原因代码
|
||
Message string `json:"message"` // 人类可读的描述
|
||
Detail string `json:"detail"` // 详细说明
|
||
Confidence int `json:"confidence"` // Agent 置信度(0-100)
|
||
TriggerEvent string `json:"trigger_event,omitempty"` // 触发事件标识
|
||
}
|
||
|
||
// HILReasonCode - 原因代码枚举
|
||
type HILReasonCode string
|
||
|
||
const (
|
||
// Level 1 原因
|
||
ReasonInfoMissing HILReasonCode = "INFO_MISSING" // 信息缺失
|
||
ReasonCreativeDirection HILReasonCode = "CREATIVE_DIRECTION" // 创意方向
|
||
ReasonUserRequested HILReasonCode = "USER_REQUESTED" // 用户请求
|
||
ReasonContentReview HILReasonCode = "CONTENT_REVIEW" // 内容审核
|
||
ReasonPreferenceConfirm HILReasonCode = "PREFERENCE_CONFIRM" // 偏好确认
|
||
|
||
// Level 2 原因
|
||
ReasonBrandStyle HILReasonCode = "BRAND_STYLE" // 品牌风格
|
||
ReasonCompliance HILReasonCode = "COMPLIANCE" // 合规要求
|
||
ReasonCapabilityLacking HILReasonCode = "CAPABILITY_LACKING" // 能力不足
|
||
ReasonHighCostRisk HILReasonCode = "HIGH_COST_RISK" // 高成本风险
|
||
ReasonResourceDeadlock HILReasonCode = "RESOURCE_DEADLOCK" // 资源死锁
|
||
ReasonSensitiveContent HILReasonCode = "SENSITIVE_CONTENT" // 敏感内容
|
||
ReasonThirdPartyEsc HILReasonCode = "THIRD_PARTY_ESCALATION" // 第三方介入
|
||
|
||
// Level 3 原因
|
||
ReasonStrategicDecision HILReasonCode = "STRATEGIC_DECISION" // 战略决策
|
||
ReasonMajorDispute HILReasonCode = "MAJOR_DISPUTE" // 重大争议
|
||
ReasonCrossSystemConflict HILReasonCode = "CROSS_SYSTEM_CONFLICT" // 跨系统冲突
|
||
ReasonLevel2TimeoutEsc HILReasonCode = "LEVEL2_TIMEOUT_ESCALATED" // Level 2 超时升级
|
||
ReasonPolicyException HILReasonCode = "POLICY_EXCEPTION" // 策略例外
|
||
ReasonCrisisResponse HILReasonCode = "CRISIS_RESPONSE" // 危机响应
|
||
)
|
||
```
|
||
|
||
### 3.3 HILContext
|
||
|
||
```go
|
||
type HILContext struct {
|
||
// 任务上下文
|
||
TaskType string `json:"task_type"` // 任务类型
|
||
TaskDescription string `json:"task_description"` // 任务描述
|
||
TaskPayload any `json:"task_payload"` // 任务载荷摘要
|
||
|
||
// 决策上下文
|
||
CurrentState any `json:"current_state"` // 当前状态
|
||
AffectedFields []string `json:"affected_fields"` // 受影响字段列表
|
||
Constraints map[string]interface{} `json:"constraints"` // 约束条件
|
||
|
||
// Agent 推理
|
||
ReasoningChain string `json:"reasoning_chain"` // Agent 推理链摘要
|
||
ConfidenceScore float64 `json:"confidence_score"` // 整体置信度(0.0-1.0)
|
||
Alternatives []string `json:"alternatives"` // 已排除的替代方案
|
||
|
||
// 风险信息
|
||
RiskLevel string `json:"risk_level"` // 风险等级(low/mid/high/critical)
|
||
RiskAssessment string `json:"risk_assessment"` // 风险评估
|
||
ImpactScope string `json:"impact_scope"` // 影响范围
|
||
|
||
// 附件
|
||
Attachments []ContextAttachment `json:"attachments,omitempty"` // 附件列表
|
||
}
|
||
|
||
// ContextAttachment - 上下文附件
|
||
type ContextAttachment struct {
|
||
Name string `json:"name"` // 附件名
|
||
Type string `json:"type"` // 附件类型(image/document/data)
|
||
URL string `json:"url"` // 附件 URL
|
||
Description string `json:"description"` // 附件描述
|
||
Size int64 `json:"size"` // 附件大小(字节)
|
||
}
|
||
```
|
||
|
||
### 3.4 HILOption
|
||
|
||
```go
|
||
type HILOption struct {
|
||
// 选项标识
|
||
ID string `json:"id"` // 选项 ID
|
||
Field string `json:"field"` // 对应字段名
|
||
|
||
// 选项内容
|
||
Value any `json:"value"` // 候选值
|
||
Label string `json:"label"` // 人类可读的显示标签
|
||
Description string `json:"description"` // 详细描述
|
||
|
||
// 分析信息
|
||
ProsCons string `json:"pros_cons"` // 优缺点分析
|
||
Confidence int `json:"confidence"` // Agent 置信度(0-100)
|
||
EstimatedCost string `json:"estimated_cost,omitempty"` // 预估成本
|
||
RiskNote string `json:"risk_note,omitempty"` // 风险提示
|
||
|
||
// 元数据
|
||
IsDefault bool `json:"is_default"` // 是否为默认推荐
|
||
Source string `json:"source"` // 来源(agent/human/auto)
|
||
}
|
||
|
||
// HILOptionSet - 选项集合(工具方法)
|
||
type HILOptionSet struct {
|
||
Options []HILOption `json:"options"`
|
||
}
|
||
|
||
func (s *HILOptionSet) GetDefault() *HILOption {
|
||
for _, opt := range s.Options {
|
||
if opt.IsDefault {
|
||
return &opt
|
||
}
|
||
}
|
||
if len(s.Options) > 0 {
|
||
return &s.Options[0]
|
||
}
|
||
return nil
|
||
}
|
||
|
||
func (s *HILOptionSet) GetByID(id string) *HILOption {
|
||
for _, opt := range s.Options {
|
||
if opt.ID == id {
|
||
return &opt
|
||
}
|
||
}
|
||
return nil
|
||
}
|
||
```
|
||
|
||
### 3.5 请求结构示例
|
||
|
||
```json
|
||
{
|
||
"id": "hil-a1b2c3d4-e5f6-7890-abcd-ef1234567890",
|
||
"task_id": "task-20260628-001",
|
||
"parent_request_id": "",
|
||
"escalation_type": "P2P",
|
||
"escalation_level": 2,
|
||
"source_system_id": "sys-creative-001",
|
||
"source_agent_id": "agent-designer-v3",
|
||
|
||
"reason": {
|
||
"code": "BRAND_STYLE",
|
||
"message": "品牌风格决策:需要确认视觉元素是否符合品牌规范",
|
||
"detail": "Agent 在生成 banner 设计稿时,对主色调使用存在不确定性。当前候选色 #3366FF 与品牌指南中规定的 Primary-500 存在偏差(偏差值 #2244DD)。",
|
||
"confidence": 72,
|
||
"trigger_event": "brand_style_check_failed"
|
||
},
|
||
|
||
"context": {
|
||
"task_type": "banner_design",
|
||
"task_description": "为夏季促销活动生成一张 1200x628 的社交媒体 banner",
|
||
"task_payload": { "campaign": "summer_sale_2026", "format": "social_media" },
|
||
"affected_fields": ["color_primary", "color_secondary", "typography"],
|
||
"constraints": { "budget_level": "standard" },
|
||
"reasoning_chain": "1. 分析品牌指南 V3.2 → 2. 检测到主色偏差 → 3. 计算偏差值 → 4. 需要人工确认",
|
||
"confidence_score": 0.72,
|
||
"risk_level": "mid",
|
||
"risk_assessment": "颜色偏差不会导致功能问题,但可能影响品牌一致性"
|
||
},
|
||
|
||
"options": [
|
||
{
|
||
"id": "opt-1",
|
||
"field": "color_primary",
|
||
"value": "#3366FF",
|
||
"label": "推荐方案:使用 #3366FF",
|
||
"description": "基于夏季活力主题的微调版本,与品牌色系相近",
|
||
"pros_cons": "优点:更符合夏季活动调性;缺点:与品牌指南有微小偏差",
|
||
"confidence": 72,
|
||
"is_default": true
|
||
},
|
||
{
|
||
"id": "opt-2",
|
||
"field": "color_primary",
|
||
"value": "#2244DD",
|
||
"label": "保守方案:严格遵循品牌色 #2244DD",
|
||
"description": "100% 符合品牌指南 V3.2 规定的 Primary-500",
|
||
"pros_cons": "优点:完全合规;缺点:与夏季活力主题契合度较低",
|
||
"confidence": 95,
|
||
"is_default": false
|
||
}
|
||
],
|
||
|
||
"suggested_value": { "color_primary": "#3366FF" },
|
||
|
||
"status": "pending",
|
||
"priority": 3,
|
||
"assigned_roles": ["brand_manager", "creative_director"]
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 4. 升级判定规则
|
||
|
||
### 4.1 需要人工介入的代码映射表
|
||
|
||
```go
|
||
// hilRequiredCodes - 需要人工介入的原因代码映射表
|
||
// true = 必须人工介入,Agent 不可自行决策
|
||
// false = 可由 Agent 自行决策(默认值)
|
||
var hilRequiredCodes = map[HILReasonCode]bool{
|
||
// Level 1
|
||
ReasonInfoMissing: true,
|
||
ReasonCreativeDirection: true,
|
||
ReasonUserRequested: true,
|
||
ReasonContentReview: true,
|
||
ReasonPreferenceConfirm: true,
|
||
|
||
// Level 2
|
||
ReasonBrandStyle: true,
|
||
ReasonCompliance: true,
|
||
ReasonCapabilityLacking: true,
|
||
ReasonHighCostRisk: true,
|
||
ReasonResourceDeadlock: true,
|
||
ReasonSensitiveContent: true,
|
||
ReasonThirdPartyEsc: true,
|
||
|
||
// Level 3
|
||
ReasonStrategicDecision: true,
|
||
ReasonMajorDispute: true,
|
||
ReasonCrossSystemConflict: true,
|
||
ReasonLevel2TimeoutEsc: true,
|
||
ReasonPolicyException: true,
|
||
ReasonCrisisResponse: true,
|
||
}
|
||
```
|
||
|
||
### 4.2 升级级别映射表
|
||
|
||
```go
|
||
// levelMap - 原因代码到升级级别的映射
|
||
// 决定升级到 Level 1 / 2 / 3
|
||
var levelMap = map[HILReasonCode]int{
|
||
// ── Level 1 ──
|
||
ReasonInfoMissing: 1,
|
||
ReasonCreativeDirection: 1,
|
||
ReasonUserRequested: 1,
|
||
ReasonContentReview: 1,
|
||
ReasonPreferenceConfirm: 1,
|
||
|
||
// ── Level 2 ──
|
||
ReasonBrandStyle: 2,
|
||
ReasonCompliance: 2,
|
||
ReasonCapabilityLacking: 2,
|
||
ReasonHighCostRisk: 2,
|
||
ReasonResourceDeadlock: 2,
|
||
ReasonSensitiveContent: 2,
|
||
ReasonThirdPartyEsc: 2,
|
||
|
||
// ── Level 3 ──
|
||
ReasonStrategicDecision: 3,
|
||
ReasonMajorDispute: 3,
|
||
ReasonCrossSystemConflict: 3,
|
||
ReasonLevel2TimeoutEsc: 3,
|
||
ReasonPolicyException: 3,
|
||
ReasonCrisisResponse: 3,
|
||
}
|
||
```
|
||
|
||
### 4.3 完整判定规则表
|
||
|
||
| 原因代码 | 中文说明 | 是否必须 HiL | 升级级别 | 默认超时 | 超时策略 |
|
||
|---------|---------|:----------:|:-------:|---------|---------|
|
||
| `INFO_MISSING` | 信息缺失 | ✔️ | 1 | 24h | 以建议值继续 |
|
||
| `CREATIVE_DIRECTION` | 创意方向 | ✔️ | 1 | 24h | 以建议值继续 |
|
||
| `USER_REQUESTED` | 用户请求 | ✔️ | 1 | 24h | 以建议值继续 |
|
||
| `CONTENT_REVIEW` | 内容审核 | ✔️ | 1 | 24h | 以建议值继续 |
|
||
| `PREFERENCE_CONFIRM` | 偏好确认 | ✔️ | 1 | 24h | 以建议值继续 |
|
||
| `BRAND_STYLE` | 品牌风格 | ✔️ | 2 | 12h | 升级至 Level 3 |
|
||
| `COMPLIANCE` | 合规要求 | ✔️ | 2 | 12h | 升级至 Level 3 |
|
||
| `CAPABILITY_LACKING` | 能力不足 | ✔️ | 2 | 12h | 升级至 Level 3 |
|
||
| `HIGH_COST_RISK` | 高成本风险 | ✔️ | 2 | 2h(紧急) | 升级至 Level 3 |
|
||
| `RESOURCE_DEADLOCK` | 资源死锁 | ✔️ | 2 | 12h | 升级至 Level 3 |
|
||
| `SENSITIVE_CONTENT` | 敏感内容 | ✔️ | 2 | 2h(紧急) | 升级至 Level 3 |
|
||
| `THIRD_PARTY_ESCALATION` | 第三方介入 | ✔️ | 2 | 12h | 升级至 Level 3 |
|
||
| `STRATEGIC_DECISION` | 战略决策 | ✔️ | 3 | 72h | 任务挂起 |
|
||
| `MAJOR_DISPUTE` | 重大争议 | ✔️ | 3 | 72h | 任务挂起 |
|
||
| `CROSS_SYSTEM_CONFLICT` | 跨系统冲突 | ✔️ | 3 | 72h | 任务挂起 |
|
||
| `LEVEL2_TIMEOUT_ESCALATED` | Level 2 超时 | ✔️ | 3 | 72h | 任务挂起 |
|
||
| `POLICY_EXCEPTION` | 策略例外 | ✔️ | 3 | 72h | 任务挂起 |
|
||
| `CRISIS_RESPONSE` | 危机响应 | ✔️ | 3 | 24h(紧急) | 任务挂起 |
|
||
|
||
### 4.4 动态判定函数
|
||
|
||
```go
|
||
// DetermineHiLLevel - 根据原因代码和上下文判定升级级别
|
||
// 返回:是否需要 HiL、升级级别、建议超时时间
|
||
func DetermineHiLLevel(reasonCode HILReasonCode, ctx context.Context) (required bool, level int, timeout time.Duration) {
|
||
// 是否必须 HiL
|
||
required = hilRequiredCodes[reasonCode]
|
||
|
||
if !required {
|
||
return false, 0, 0
|
||
}
|
||
|
||
// 判定升级级别
|
||
level = levelMap[reasonCode]
|
||
if level == 0 {
|
||
level = 1 // 默认 Level 1
|
||
}
|
||
|
||
// 根据上下文调整超时
|
||
timeout = getDefaultTimeout(level)
|
||
|
||
// 紧急模式判定:高风险场景缩短超时
|
||
if isEmergencyMode(ctx, reasonCode) {
|
||
timeout = getEmergencyTimeout(level)
|
||
}
|
||
|
||
return required, level, timeout
|
||
}
|
||
|
||
func getDefaultTimeout(level int) time.Duration {
|
||
switch level {
|
||
case 1:
|
||
return 24 * time.Hour
|
||
case 2:
|
||
return 12 * time.Hour
|
||
case 3:
|
||
return 72 * time.Hour
|
||
default:
|
||
return 24 * time.Hour
|
||
}
|
||
}
|
||
|
||
func getEmergencyTimeout(level int) time.Duration {
|
||
switch level {
|
||
case 2:
|
||
return 2 * time.Hour
|
||
case 3:
|
||
return 24 * time.Hour
|
||
default:
|
||
return getDefaultTimeout(level)
|
||
}
|
||
}
|
||
|
||
// isEmergencyMode - 判断是否为紧急模式
|
||
func isEmergencyMode(ctx context.Context, reasonCode HILReasonCode) bool {
|
||
emergencyCodes := map[HILReasonCode]bool{
|
||
ReasonHighCostRisk: true,
|
||
ReasonSensitiveContent: true,
|
||
ReasonCrisisResponse: true,
|
||
}
|
||
return emergencyCodes[reasonCode]
|
||
}
|
||
```
|
||
|
||
### 4.5 阈值配置表
|
||
|
||
| 配置项 | 默认值 | 说明 |
|
||
|-------|-------|------|
|
||
| `hil.max_level1_per_task` | 5 | 单任务最大 Level 1 升级次数 |
|
||
| `hil.max_level2_per_task` | 3 | 单任务最大 Level 2 升级次数 |
|
||
| `hil.max_level3_per_task` | 1 | 单任务最大 Level 3 升级次数 |
|
||
| `hil.cost_threshold_high` | 1000 | 高成本阈值(SYN 代币) |
|
||
| `hil.confidence_threshold` | 60 | Agent 置信度阈值(低于此值建议升级) |
|
||
| `hil.max_pending_requests` | 50 | 最大待处理请求数(超出后拒绝新请求) |
|
||
| `hil.emergency_mode_enabled` | true | 是否启用紧急模式 |
|
||
| `hil.auto_approve_on_timeout_level1` | true | Level 1 超时是否自动以建议值通过 |
|
||
|
||
---
|
||
|
||
## 5. 人工响应结构
|
||
|
||
### 5.1 HILResponse
|
||
|
||
```go
|
||
type HILResponse struct {
|
||
// 决策标识
|
||
DecisionID string `json:"decision_id"` // 决策唯一 ID
|
||
RequestID string `json:"request_id"` // 关联请求 ID
|
||
|
||
// 决策者信息
|
||
UserID string `json:"user_id"` // 决策用户 ID
|
||
UserName string `json:"user_name"` // 用户名
|
||
UserRole string `json:"user_role"` // 用户角色
|
||
UserAvatar string `json:"user_avatar,omitempty"` // 用户头像 URL
|
||
|
||
// 决策内容
|
||
Action DecisionAction `json:"action"` // 决策动作
|
||
Decision HILDecision `json:"decision"` // 决策内容
|
||
Notes string `json:"notes"` // 备注说明
|
||
|
||
// 元数据
|
||
Timestamp time.Time `json:"timestamp"` // 决策时间
|
||
Duration time.Duration `json:"duration"` // 决策耗时
|
||
Source string `json:"source"` // 响应渠道(web/mobile/api/email)
|
||
}
|
||
|
||
// DecisionAction - 决策动作枚举
|
||
type DecisionAction string
|
||
|
||
const (
|
||
ActionApprove DecisionAction = "approve" // 批准建议值或默认方案
|
||
ActionReject DecisionAction = "reject" // 拒绝所有方案
|
||
ActionModify DecisionAction = "modify" // 修改后批准
|
||
ActionSelect DecisionAction = "select" // 选择某一方案
|
||
ActionDefer DecisionAction = "defer" // 暂缓决策,需要更多信息
|
||
ActionEscalate DecisionAction = "escalate" // 手动升级
|
||
)
|
||
```
|
||
|
||
### 5.2 HILDecision
|
||
|
||
```go
|
||
type HILDecision struct {
|
||
// 批准的字段(Action = approve 时使用)
|
||
// key = 字段名, value = 批准的值
|
||
ApprovedFields map[string]interface{} `json:"approved_fields,omitempty"`
|
||
|
||
// 修改的字段(Action = modify 时使用)
|
||
// 与 ApprovedFields 的区别:ModifiedFields 包含人类手动调整的值
|
||
ModifiedFields map[string]interface{} `json:"modified_fields,omitempty"`
|
||
|
||
// 选中的选项 ID(Action = select 时使用)
|
||
SelectedOption string `json:"selected_option,omitempty"`
|
||
|
||
// 拒绝原因(Action = reject 时使用)
|
||
RejectionReason string `json:"rejection_reason,omitempty"`
|
||
|
||
// 附加指令(Action = modify/defer 时使用)
|
||
Instructions string `json:"instructions,omitempty"`
|
||
|
||
// 决策影响评估
|
||
Impact *DecisionImpact `json:"impact,omitempty"`
|
||
}
|
||
|
||
// DecisionImpact - 决策影响评估
|
||
type DecisionImpact struct {
|
||
EstimatedCost float64 `json:"estimated_cost"` // 预估成本
|
||
EstimatedTime string `json:"estimated_time"` // 预估耗时
|
||
AffectedSystems []string `json:"affected_systems"` // 受影响系统
|
||
RollbackPossible bool `json:"rollback_possible"` // 是否可回滚
|
||
RollbackPlan string `json:"rollback_plan,omitempty"` // 回滚方案
|
||
}
|
||
```
|
||
|
||
### 5.3 决策动作对照表
|
||
|
||
| 动作 | 适用级别 | 含义 | 后续流程 |
|
||
|------|---------|------|---------|
|
||
| `approve` | 1 / 2 / 3 | 批准 Agent 的建议值或默认方案 | 任务继续执行 |
|
||
| `reject` | 1 / 2 / 3 | 拒绝所有方案 | 任务终止或返回修改 |
|
||
| `modify` | 1 / 2 | 修改建议值后批准 | 按修改后的值执行 |
|
||
| `select` | 2 / 3 | 从多个方案中选择一个 | 按选中方案执行 |
|
||
| `defer` | 2 / 3 | 暂缓决策,要求补充信息 | 返回等待状态,Agent 补充信息 |
|
||
| `escalate` | 1 / 2 | 手动升级至更高级别 | 进入更高级别的流程 |
|
||
|
||
### 5.4 响应处理函数
|
||
|
||
```go
|
||
// ProcessHILResponse - 处理人工响应
|
||
// 返回:是否需要触发后续操作、错误信息
|
||
func ProcessHILResponse(ctx context.Context, resp *HILResponse) (bool, error) {
|
||
switch resp.Action {
|
||
case ActionApprove:
|
||
return handleApprove(ctx, resp)
|
||
case ActionReject:
|
||
return handleReject(ctx, resp)
|
||
case ActionModify:
|
||
return handleModify(ctx, resp)
|
||
case ActionSelect:
|
||
return handleSelect(ctx, resp)
|
||
case ActionDefer:
|
||
return handleDefer(ctx, resp)
|
||
case ActionEscalate:
|
||
return handleEscalate(ctx, resp)
|
||
default:
|
||
return false, fmt.Errorf("unknown decision action: %s", resp.Action)
|
||
}
|
||
}
|
||
|
||
func handleApprove(ctx context.Context, resp *HILResponse) (bool, error) {
|
||
// 1. 更新请求状态为 approved
|
||
// 2. 应用 approved_fields 到任务
|
||
// 3. 触发任务继续执行
|
||
// 4. 记录审计日志
|
||
return true, nil
|
||
}
|
||
|
||
func handleModify(ctx context.Context, resp *HILResponse) (bool, error) {
|
||
// 1. 更新请求状态为 approved
|
||
// 2. 将 modified_fields 合并到任务参数
|
||
// 3. 记录原始值与修改值到审计日志
|
||
// 4. 触发任务继续执行
|
||
return true, nil
|
||
}
|
||
|
||
func handleSelect(ctx context.Context, resp *HILResponse) (bool, error) {
|
||
// 1. 验证 selected_option 存在
|
||
// 2. 更新请求状态为 approved
|
||
// 3. 提取选中选项的值并应用到任务
|
||
// 4. 触发任务继续执行
|
||
return true, nil
|
||
}
|
||
|
||
func handleReject(ctx context.Context, resp *HILResponse) (bool, error) {
|
||
// 1. 更新请求状态为 rejected
|
||
// 2. 记录拒绝原因
|
||
// 3. 通知任务发起方
|
||
// 4. 根据策略决定任务终止或重新提交
|
||
return true, nil
|
||
}
|
||
|
||
func handleDefer(ctx context.Context, resp *HILResponse) (bool, error) {
|
||
// 1. 更新请求状态为 pending(重新进入队列)
|
||
// 2. 记录 instructions 为补充信息要求
|
||
// 3. 通知 Agent 补充信息
|
||
// 4. 更新 deadline
|
||
return true, nil
|
||
}
|
||
|
||
func handleEscalate(ctx context.Context, resp *HILResponse) (bool, error) {
|
||
// 1. 更新当前请求状态为 escalated
|
||
// 2. 创建新的升级请求(level + 1)
|
||
// 3. 关联 parent_request_id
|
||
// 4. 通知更高级别的决策者
|
||
return true, nil
|
||
}
|
||
```
|
||
|
||
### 5.5 响应示例
|
||
|
||
```json
|
||
{
|
||
"decision_id": "dec-9876-5432-1098",
|
||
"request_id": "hil-a1b2c3d4-e5f6-7890-abcd-ef1234567890",
|
||
"user_id": "user-zhangsan-001",
|
||
"user_name": "张三",
|
||
"user_role": "brand_manager",
|
||
"action": "modify",
|
||
"decision": {
|
||
"modified_fields": {
|
||
"color_primary": "#3377FF",
|
||
"color_secondary": "#FF7722"
|
||
},
|
||
"instructions": "主色调调整为 #3377FF(介于推荐和保守方案之间),辅助色使用 #FF7722 突出促销氛围。请按此配色重新生成设计稿。",
|
||
"impact": {
|
||
"estimated_cost": 0,
|
||
"estimated_time": "15min",
|
||
"affected_systems": ["creative-engine", "brand-assets"],
|
||
"rollback_possible": true,
|
||
"rollback_plan": "恢复至修改前的配色方案即可"
|
||
}
|
||
},
|
||
"notes": "颜色调整合理,注意保持整体的视觉平衡。",
|
||
"timestamp": "2026-06-28T14:30:00+08:00",
|
||
"duration": 1800000000000,
|
||
"source": "web"
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 6. 超时与降级策略
|
||
|
||
### 6.1 超时处理矩阵
|
||
|
||
| 级别 | 超时时间 | 超时动作 | 说明 |
|
||
|-----|---------|---------|------|
|
||
| Level 1 | 24h | 自动批准(以 Agent 建议值执行) | 低风险场景,Agent 建议值视为默认 |
|
||
| Level 1(紧急) | 4h | 自动批准 | 任务优先级高时缩短超时 |
|
||
| Level 2 | 12h | 升级至 Level 3 | 不可自动决策,必须由更高级别介入 |
|
||
| Level 2(紧急) | 2h | 升级至 Level 3 | 高风险场景快速升级 |
|
||
| Level 3 | 72h | 任务挂起 | 不做任何自动操作,等待人工 |
|
||
| Level 3(紧急) | 24h | 任务挂起 + 通知管理层 | 危机场景需尽快响应 |
|
||
|
||
### 6.2 超时监控
|
||
|
||
```go
|
||
// HILTimeoutWatcher - 超时监控器
|
||
type HILTimeoutWatcher struct {
|
||
mu sync.RWMutex
|
||
timers map[string]*time.Timer
|
||
onTimeout func(ctx context.Context, req *HILRequest)
|
||
}
|
||
|
||
func NewHILTimeoutWatcher(onTimeout func(ctx context.Context, req *HILRequest)) *HILTimeoutWatcher {
|
||
return &HILTimeoutWatcher{
|
||
timers: make(map[string]*time.Timer),
|
||
onTimeout: onTimeout,
|
||
}
|
||
}
|
||
|
||
func (w *HILTimeoutWatcher) Register(req *HILRequest) {
|
||
w.mu.Lock()
|
||
defer w.mu.Unlock()
|
||
|
||
timeout := time.Until(req.Deadline)
|
||
timer := time.AfterFunc(timeout, func() {
|
||
ctx := context.Background()
|
||
w.onTimeout(ctx, req)
|
||
})
|
||
w.timers[req.ID] = timer
|
||
}
|
||
|
||
func (w *HILTimeoutWatcher) Cancel(reqID string) {
|
||
w.mu.Lock()
|
||
defer w.mu.Unlock()
|
||
|
||
if timer, ok := w.timers[reqID]; ok {
|
||
timer.Stop()
|
||
delete(w.timers, reqID)
|
||
}
|
||
}
|
||
```
|
||
|
||
### 6.3 超时通知策略
|
||
|
||
| 级别 | 超时前提醒 | 提醒方式 | 超时后通知 |
|
||
|-----|-----------|---------|-----------|
|
||
| Level 1 | 超时前 4h | 站内通知 | 通知请求发起人 |
|
||
| Level 2 | 超时前 2h、30min | 站内通知 + 邮件 | 通知请求发起人 + 升级接收人 |
|
||
| Level 3 | 超时前 24h、4h、30min | 站内通知 + 邮件 + 短信 | 通知管理层 + 升级委员会 |
|
||
|
||
---
|
||
|
||
## 7. 通知渠道规范
|
||
|
||
### 7.1 通知渠道配置
|
||
|
||
```go
|
||
type HILNotificationConfig struct {
|
||
// 渠道启用状态
|
||
InAppEnabled bool `json:"in_app_enabled"` // 站内通知
|
||
EmailEnabled bool `json:"email_enabled"` // 邮件通知
|
||
SMSEnabled bool `json:"sms_enabled"` // 短信通知
|
||
WebhookEnabled bool `json:"webhook_enabled"` // Webhook 通知
|
||
|
||
// 各渠道的级别阈值
|
||
InAppLevel int `json:"in_app_level"` // 站内通知最低级别(1)
|
||
EmailLevel int `json:"email_level"` // 邮件通知最低级别(2)
|
||
SMSLevel int `json:"sms_level"` // 短信通知最低级别(3)
|
||
WebhookURL string `json:"webhook_url,omitempty"` // Webhook URL
|
||
|
||
// 通知模板
|
||
TitleTemplate string `json:"title_template"` // 标题模板
|
||
BodyTemplate string `json:"body_template"` // 内容模板
|
||
}
|
||
|
||
// HILNotification - 通知消息结构
|
||
type HILNotification struct {
|
||
ID string `json:"id"`
|
||
RequestID string `json:"request_id"`
|
||
Channels []string `json:"channels"` // 通知渠道列表
|
||
Title string `json:"title"`
|
||
Body string `json:"body"`
|
||
Level int `json:"level"`
|
||
Recipients []string `json:"recipients"`
|
||
Status string `json:"status"` // sent/delivered/failed
|
||
CreatedAt time.Time `json:"created_at"`
|
||
}
|
||
```
|
||
|
||
### 7.2 渠道-级别对照表
|
||
|
||
| 级别 | 站内通知 | 邮件 | 短信 | Webhook |
|
||
|-----|:-------:|:----:|:----:|:-------:|
|
||
| Level 1 | ✔️ | ❌ | ❌ | 可选 |
|
||
| Level 2 | ✔️ | ✔️ | ❌ | 可选 |
|
||
| Level 3 | ✔️ | ✔️ | ✔️(紧急) | ✔️ |
|
||
| 紧急模式 | ✔️ | ✔️ | ✔️ | ✔️ |
|
||
|
||
---
|
||
|
||
## 8. 审计与日志
|
||
|
||
### 8.1 审计记录结构
|
||
|
||
```go
|
||
type HILAuditLog struct {
|
||
LogID string `json:"log_id"` // 审计日志 ID
|
||
RequestID string `json:"request_id"` // 关联请求 ID
|
||
TaskID string `json:"task_id"` // 关联任务 ID
|
||
|
||
// 事件信息
|
||
EventType string `json:"event_type"` // 事件类型
|
||
EventData map[string]interface{} `json:"event_data"` // 事件数据
|
||
Timestamp time.Time `json:"timestamp"` // 事件时间
|
||
|
||
// 操作者
|
||
ActorID string `json:"actor_id"` // 操作者 ID
|
||
ActorType string `json:"actor_type"` // 操作者类型(agent/human/system)
|
||
ActorRole string `json:"actor_role"` // 操作者角色
|
||
|
||
// 变更记录
|
||
Changes []FieldChange `json:"changes"` // 字段变更记录
|
||
|
||
// 完整性
|
||
Checksum string `json:"checksum"` // 日志校验和
|
||
Signature string `json:"signature"` // 数字签名
|
||
}
|
||
|
||
type FieldChange struct {
|
||
Field string `json:"field"` // 字段名
|
||
OldValue interface{} `json:"old_value"` // 旧值
|
||
NewValue interface{} `json:"new_value"` // 新值
|
||
Reason string `json:"reason"` // 变更原因
|
||
}
|
||
```
|
||
|
||
### 8.2 审计事件类型
|
||
|
||
| 事件类型 | 说明 | 记录内容 |
|
||
|---------|------|---------|
|
||
| `hil.request.created` | 请求创建 | 请求完整内容、发起方信息 |
|
||
| `hil.request.assigned` | 分配决策者 | 决策者 ID、角色 |
|
||
| `hil.request.status_changed` | 状态变更 | 原状态、新状态、变更原因 |
|
||
| `hil.request.notified` | 发送通知 | 通知渠道、接收人列表 |
|
||
| `hil.request.timeout` | 超时触发 | 超时级别、触发策略 |
|
||
| `hil.request.escalated` | 升级触发 | 原级别、新级别、升级原因 |
|
||
| `hil.decision.submitted` | 决策提交 | 决策完整内容、决策者信息 |
|
||
| `hil.decision.applied` | 决策应用 | 应用字段、变更值 |
|
||
| `hil.request.completed` | 请求完成 | 最终状态、耗时 |
|
||
|
||
### 8.3 审计日志保留策略
|
||
|
||
| 级别 | 保留期限 | 存储方式 |
|
||
|-----|---------|---------|
|
||
| Level 1 | 90 天 | 热存储 |
|
||
| Level 2 | 180 天 | 热存储 |
|
||
| Level 3 | 365 天 | 热存储 + 冷备份 |
|
||
| 紧急模式 | 730 天 | 热存储 + 冷备份 + 加密归档 |
|
||
|
||
---
|
||
|
||
> 本文档基于 [06-implementation-details.md](../v0/06-implementation-details.md#5-人工介入hil三级升级机制) 第5章扩展编写,是灵隙协议实现规范的一部分。
|
||
>
|
||
> 相关文档:[raw-protocol.md](01_raw-protocol.md) | [a2a-protocol.md](02_a2a-protocol.md) | [a2n-protocol.md](03_a2n-protocol.md)
|