返回知识库
0

第八章:上下文与人类协作

本章目标:帮助你理解用户交互(Approval/Question)、Sandbox Escalation、Context Guard Plan 机制,以及 dsh 如何实现人类与 Agent 的协作。阅读本章后,你应该能回答"Agent 如何请求用户批准"以及"如何管理 Agent 的执行上下文"。


8.1 用户交互层

8.1.1 架构概览

预览
源码

interaction/ 能力

interaction/ (Service Definition)

user-approval/ (Provider)

user-questions/ (Provider)

commands/ (Consumer)

ask-user/ (Consumer)

graph TB
    subgraph "interaction/ 能力"
        A["interaction/ (Service Definition)"]
        B["user-approval/ (Provider)"]
        C["user-questions/ (Provider)"]
        D["commands/ (Consumer)"]
        E["ask-user/ (Consumer)"]
    end

    A --> B
    A --> C
    D --> A
    E --> A

8.1.2 Approval 服务

当 Agent 需要执行敏感操作时,会请求用户批准:

// 来自 packages/interaction/user-approval/src/index.ts
class ApprovalService {
  /** 请求批准 */
  async request(options: ApprovalRequest): Promise<ApprovalResult> {
    // 1. 构建批准请求
    const request = {
      id: generateRequestId(),
      type: options.type,
      description: options.description,
      risk: options.risk,
      details: options.details
    }
    
    // 2. 发送事件
    ctx.emit('approval/request', request)
    
    // 3. 等待用户响应
    const result = await waitForApproval(request.id)
    
    return result
  }
}

8.1.3 ApprovalRequest

interface ApprovalRequest {
  /** 请求 ID */
  id: string
  /** 请求类型 */
  type: 'tool-execution' | 'file-modification' | 'network-access' | 'process-spawn'
  /** 描述 */
  description: string
  /** 风险等级 */
  risk: 'low' | 'medium' | 'high' | 'critical'
  /** 详细信息 */
  details: Record<string, unknown>
}

8.1.4 ApprovalResult

interface ApprovalResult {
  /** 是否批准 */
  approved: boolean
  /** 用户选择 */
  choice: 'always' | 'once' | 'never'
  /** 备注 */
  note?: string
}

8.2 User Questions

8.2.1 概念

Agent 可以向用户提问以获取更多信息:

// 来自 packages/interaction/user-questions/src/index.ts
class UserQuestionService {
  /** 提问 */
  async ask(options: QuestionOptions): Promise<QuestionResult> {
    // 1. 构建问题
    const question = {
      id: generateQuestionId(),
      question: options.question,
      type: options.type,  // 'text' | 'choice' | 'confirm'
      options: options.choices
    }
    
    // 2. 发送事件
    ctx.emit('question/ask', question)
    
    // 3. 等待用户回答
    const answer = await waitForAnswer(question.id)
    
    return answer
  }
}

8.2.2 问题类型

type QuestionType = 'text' | 'choice' | 'confirm'

interface QuestionOptions {
  /** 问题文本 */
  question: string
  /** 问题类型 */
  type: QuestionType
  /** 选择题选项 */
  choices?: string[]
  /** 默认值 */
  default?: string | boolean
}

8.3 Sandbox Escalation

8.3.1 概念

Sandbox Escalation 允许 Agent 在需要时请求提升权限:

预览
源码

批准

拒绝

Agent 执行

需要权限?

请求 Escalation

用户批准

提升权限

拒绝执行

正常执行

graph TB
    A[Agent 执行] --> B{需要权限?}
    B -->|"是"| C[请求 Escalation]
    C --> D[用户批准]
    D -->|"批准"| E[提升权限]
    D -->|"拒绝"| F[拒绝执行]
    B -->|"否"| G[正常执行]

8.3.2 EscalationApprover

// 来自 packages/sandbox/sandbox/src/escalation.ts
interface EscalationApprover {
  /** 请求权限提升 */
  request(options: EscalationRequest): Promise<EscalationResult>
}

interface EscalationRequest {
  /** 请求的权限 */
  permissions: string[]
  /** 原因 */
  reason: string
  /** 风险等级 */
  risk: 'low' | 'medium' | 'high'
}

interface EscalationResult {
  /** 是否批准 */
  approved: boolean
  /** 授予的权限 */
  granted: string[]
}

8.3.3 沙箱执行

// 来自 packages/sandbox/sandbox-local/src/index.ts
class LocalSandboxProvider {
  /** 在沙箱中执行命令 */
  async confine(command: string, options: SandboxOptions): Promise<SandboxResult> {
    // 1. 解析命令
    const [cmd, ...args] = this.parseCommand(command)
    
    // 2. 应用限制
    const confinedArgs = this.applyRestrictions(args, options.restrictions)
    
    // 3. 执行
    const result = await this.subprocess.spawn(cmd, confinedArgs, {
      cwd: options.cwd,
      env: options.env,
      timeout: options.timeout
    })
    
    return result
  }
}

8.4 Context 管理

8.4.1 上下文插件

dsh 提供多个上下文插件来管理 Agent 的执行上下文:

预览
源码
graph TB
    subgraph "context/ 能力"
        A["context/ (Service Definition)"]
        B["agent-instructions/ (Provider)"]
        C["time-context/ (Provider)"]
        D["references/ (Provider)"]
    end

    A --> B
    A --> C
    A --> D
graph TB
    subgraph "context/ 能力"
        A["context/ (Service Definition)"]
        B["agent-instructions/ (Provider)"]
        C["time-context/ (Provider)"]
        D["references/ (Provider)"]
    end

    A --> B
    A --> C
    A --> D

8.4.2 Agent Instructions

// 来自 packages/context/agent-instructions/src/index.ts
class AgentInstructionsService {
  /** 获取指令 */
  getInstructions(agentId: string): string {
    // 从配置或存储中获取 Agent 指令
    return this.instructions.get(agentId) ?? ''
  }
  
  /** 设置指令 */
  setInstructions(agentId: string, instructions: string): void {
    this.instructions.set(agentId, instructions)
  }
}

8.4.3 Time Context

// 来自 packages/context/time-context/src/index.ts
class TimeContextService {
  /** 获取当前时间上下文 */
  getTimeContext(): TimeContext {
    return {
      now: new Date(),
      timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
      locale: Intl.DateTimeFormat().resolvedOptions().locale
    }
  }
}

8.4.4 References

// 来自 packages/context/references/src/index.ts
class ReferencesService {
  /** 添加引用 */
  addReference(reference: Reference): void {
    this.references.push(reference)
  }
  
  /** 获取所有引用 */
  getReferences(): Reference[] {
    return this.references
  }
}

interface Reference {
  /** 引用类型 */
  type: 'file' | 'url' | 'code' | 'document'
  /** 引用内容 */
  content: string
  /** 元数据 */
  metadata: Record<string, unknown>
}

8.5 Guard 机制

8.5.1 概念

Guard 机制提供循环卫生检查和工具超时强制执行:

预览
源码
graph TB
    subgraph "guard/ 能力"
        A["guard/ (Service Definition)"]
        B["repeat-call-guard/ (Provider)"]
        C["tool-timeout-guard/ (Provider)"]
    end

    A --> B
    A --> C
graph TB
    subgraph "guard/ 能力"
        A["guard/ (Service Definition)"]
        B["repeat-call-guard/ (Provider)"]
        C["tool-timeout-guard/ (Provider)"]
    end

    A --> B
    A --> C

8.5.2 Repeat Call Guard

防止 Agent 重复调用相同的工具:

// 来自 packages/guard/repeat-call-guard/src/index.ts
class RepeatCallGuard {
  private callHistory = new Map<string, number>()
  
  /** 检查是否重复调用 */
  check(toolName: string, params: Record<string, unknown>): GuardResult {
    const key = this.buildKey(toolName, params)
    const count = this.callHistory.get(key) ?? 0
    
    if (count >= this.maxRepeats) {
      return {
        allowed: false,
        reason: `Tool "${toolName}" has been called ${count} times with the same parameters`
      }
    }
    
    this.callHistory.set(key, count + 1)
    return { allowed: true }
  }
}

8.5.3 Tool Timeout Guard

强制执行工具执行超时:

// 来自 packages/guard/tool-timeout-guard/src/index.ts
class ToolTimeoutGuard {
  /** 包装工具执行,添加超时 */
  async wrapExecution<T>(
    toolName: string,
    execution: () => Promise<T>,
    timeoutMs: number
  ): Promise<T> {
    return Promise.race([
      execution(),
      new Promise<never>((_, reject) => {
        setTimeout(() => {
          reject(new Error(`Tool "${toolName}" timed out after ${timeoutMs}ms`))
        }, timeoutMs)
      })
    ])
  }
}

8.6 Plan 机制

8.6.1 概念

Plan 机制允许 Agent 创建和管理执行计划:

预览
源码
graph TB
    subgraph "plan/ 能力"
        A["plan/ (Service Definition)"]
        B["plan-local/ (Provider)"]
        C["tool-plan/ (Consumer)"]
    end

    A --> B
    C --> A
graph TB
    subgraph "plan/ 能力"
        A["plan/ (Service Definition)"]
        B["plan-local/ (Provider)"]
        C["tool-plan/ (Consumer)"]
    end

    A --> B
    C --> A

8.6.2 Plan 状态

interface Plan {
  /** Plan ID */
  id: string
  /** Plan 标题 */
  title: string
  /** Plan 步骤 */
  steps: PlanStep[]
  /** 当前状态 */
  status: 'draft' | 'active' | 'completed' | 'failed'
  /** 创建时间 */
  createdAt: Date
  /** 更新时间 */
  updatedAt: Date
}

interface PlanStep {
  /** 步骤 ID */
  id: string
  /** 步骤描述 */
  description: string
  /** 步骤状态 */
  status: 'pending' | 'in-progress' | 'completed' | 'failed'
  /** 依赖的步骤 */
  dependsOn?: string[]
}

8.6.3 Plan 管理

// 创建 Plan
const plan = ctx.plan.create({
  title: '实现用户认证',
  steps: [
    { id: '1', description: '设计 API 接口' },
    { id: '2', description: '实现数据库模型', dependsOn: ['1'] },
    { id: '3', description: '实现认证逻辑', dependsOn: ['2'] },
    { id: '4', description: '编写测试', dependsOn: ['3'] }
  ]
})

// 更新步骤状态
ctx.plan.updateStep(plan.id, '1', { status: 'completed' })

// 获取当前计划
const currentPlan = ctx.plan.getCurrent()

8.7 交互流程示例

8.7.1 工具执行审批流程

预览
源码
sequenceDiagram
    participant Agent
    participant Guard
    participant Approval
    participant User
    participant Tool

    Agent->>Guard: check(toolName, params)
    Guard-->>Agent: allowed = true
    Agent->>Approval: request(tool execution)
    Approval->>User: 显示审批请求
    User->>Approval: 批准
    Approval-->>Agent: approved = true
    Agent->>Tool: execute(toolName, params)
    Tool-->>Agent: result
sequenceDiagram
    participant Agent
    participant Guard
    participant Approval
    participant User
    participant Tool

    Agent->>Guard: check(toolName, params)
    Guard-->>Agent: allowed = true
    Agent->>Approval: request(tool execution)
    Approval->>User: 显示审批请求
    User->>Approval: 批准
    Approval-->>Agent: approved = true
    Agent->>Tool: execute(toolName, params)
    Tool-->>Agent: result

8.7.2 用户提问流程

预览
源码
sequenceDiagram
    participant Agent
    participant Questions
    participant User

    Agent->>Questions: ask({question, type})
    Questions->>User: 显示问题
    User->>Questions: 回答
    Questions-->>Agent: answer
    Agent->>Agent: 使用答案继续执行
sequenceDiagram
    participant Agent
    participant Questions
    participant User

    Agent->>Questions: ask({question, type})
    Questions->>User: 显示问题
    User->>Questions: 回答
    Questions-->>Agent: answer
    Agent->>Agent: 使用答案继续执行

8.8 配置

8.8.1 Approval 配置

# cordis.patch.yml
- id: user-approval
  config:
    # 审批模式
    mode: 'interactive'  # 'interactive' | 'auto-approve' | 'auto-deny'
    
    # 自动批准的工具列表
    autoApprove:
      - 'file_read'
      - 'bash'
    
    # 自动拒绝的工具列表
    autoDeny:
      - 'system_command'

8.8.2 Guard 配置

# cordis.patch.yml
- id: guard
  config:
    # 重复调用限制
    repeatCall:
      maxRepeats: 3
    
    # 工具超时
    toolTimeout:
      defaultMs: 30000
      overrides:
        bash: 60000
        file_write: 10000

8.9 小结

概念一句话解释
ApprovalAgent 请求用户批准敏感操作
User QuestionsAgent 向用户提问获取信息
Sandbox EscalationAgent 请求提升权限
Context管理 Agent 的执行上下文
Guard循环卫生和工具超时强制执行
PlanAgent 创建和管理执行计划

下一步第九章:持久化与数据平面——深入理解 Session 生命周期、日志格式、持久化后端、查询、Compaction 和 Python SDK 对接。

DeepSeek-Harness / 08-上下文与人类协作 0 0 iliuqi
2026-09-04T07:48:53.263702153Z 2026-09-04T07:57:35.388643249Z