mcpField
A
agent-instinct-system

agent-instinct-system

github.com/itallstartedwithaideaAgent 工作流4478 次安装28 周前更新
代码仓库

关于 agent-instinct-system

agent-instinct-system 是为 Agent 提供分层安全检查的技能,在代码变更、工具调用和输出前验证操作。它通过即时反射、轻量门控和深入评估,拦截受保护文件修改、越权操作等风险。

主要功能

  1. 01分层的行动前检查
  2. 02受保护文件与操作校验
  3. 03范围、语法和依赖验证
  4. 04任务对齐与影响评估
  5. 05执行后审计反馈

适用场景

  1. 01防止 Agent 删除受保护文件
  2. 02在生产操作前验证预算上限
  3. 03限制操作在指定任务范围内

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/itallstartedwithaidea/agent-skills --skill agent-instinct-system

安装后在 Claude Code 中输入/agent-instinct-system确认已加载。

详细介绍

Agent Instinct System

Agent Skills™ 的组成部分,由 googleadsagent.ai™ 提供

描述

Agent Instinct System 实现了预认知反射——在每次代码更改、工具调用或生成输出之前触发的自动安全检查与验证。正如生物反射能比有意识的思考更快地保护生物体免受伤害,Agent 本能也能比刻意推理更快地保护代码库和系统免受损害。这些本能在特定任务逻辑之下运行,构成一个通用安全层,无论 Agent 正在执行什么任务,该安全层都会激活。

该系统为 googleadsagent.ai™ 的 Buddy™ Agent 开发。在此场景中,一次错误的 Google Ads API 调用就可能耗尽客户整月的预算,因此本能系统会强制执行绝不能违反的不变量。修改出价前会检查预算上限。破坏性操作需要确认信号。删除文件前会根据保护列表进行验证。这些检查会自动执行,无需 Agent “记得”去做。

本能系统分为三个层级:反射(即时、零成本的检查,例如“此文件是否在保护列表中”)、关卡(轻量级验证,例如“此更改是否通过代码检查工具”)和评估(成本较高的检查,例如“此修改是否符合已说明的任务”)。每个层级都会增加延迟,但也能发现越来越隐蔽的问题。

适用场景

  • Agent 在生产系统上运行,错误会造成实际后果
  • 除单一验证步骤外,还需要纵深防御
  • 多个 Agent 或团队成员同时处理同一代码库
  • Agent 处理破坏性操作(删除、部署、API 修改)
  • 合规要求规定必须在执行操作前验证 AI 生成的更改
  • 希望从源头上杜绝整类错误,而不是事后发现

工作原理

graph TD
    A[Agent Intent] --> B[Tier 1: Reflexes]
    B -->|Block| C[Immediate Rejection]
    B -->|Pass| D[Tier 2: Gates]
    D -->|Block| E[Rejection + Guidance]
    D -->|Pass| F[Tier 3: Assessments]
    F -->|Block| G[Rejection + Alternative]
    F -->|Pass| H[Action Execution]
    H --> I[Post-Action Audit]
    I --> J[Instinct Learning]
    J --> K{New Pattern?}
    K -->|Yes| L[Add Reflex/Gate]
    K -->|No| M[Log + Continue]

当 Agent 形成执行操作的意图(写入文件、调用工具、生成输出)时,该意图会依次通过各个本能层级。第 1 层反射是硬编码检查,会在微秒内执行:受保护文件列表、禁止的操作模式、预算上限检查。第 2 层关卡会运行轻量级验证:语法检查、依赖项验证、范围验证。第 3 层评估会执行更深入的分析:任务一致性验证、影响估算、副作用预测。执行后,操作后审计会将反馈送回本能系统,使其能够从险些造成问题的情况中学习新的保护模式。

实现

本能引擎核心:

type InstinctTier = "reflex" | "gate" | "assessment";

interface Instinct {
  name: string;
  tier: InstinctTier;
  check(intent: AgentIntent): Promise<InstinctResult>;
}

interface InstinctResult {
  allow: boolean;
  reason?: string;
  alternative?: string;
}

class InstinctEngine {
  private instincts: Map<InstinctTier, Instinct[]> = new Map([
    ["reflex", []],
    ["gate", []],
    ["assessment", []],
  ]);

  register(instinct: Instinct): void {
    this.instincts.get(instinct.tier)!.push(instinct);
  }

  async evaluate(intent: AgentIntent): Promise<InstinctResult> {
    for (const tier of ["reflex", "gate", "assessment"] as InstinctTier[]) {
      for (const instinct of this.instincts.get(tier)!) {
        const result = await instinct.check(intent);
        if (!result.allow) {
          return { ...result, reason: `[${instinct.name}] ${result.reason}` };
        }
      }
    }
    return { allow: true };
  }
}

内置反射:

const PROTECTED_FILES_REFLEX: Instinct = {
  name: "protected-files",
  tier: "reflex",
  async check(intent) {
    const protectedPatterns = [
      /\.env($|\.)/,
      /credentials\./,
      /secrets?\./,
      /\.pem$/,
      /id_rsa/,
      /package-lock\.json$/,
      /yarn\.lock$/,
    ];
    if (intent.type === "file_write" || intent.type === "file_delete") {
      const blocked = protectedPatterns.some(p => p.test(intent.target));
      if (blocked) {
        return { allow: false, reason: `"${intent.target}" is a protected file` };
      }
    }
    return { allow: true };
  },
};

const DESTRUCTIVE_OP_REFLEX: Instinct = {
  name: "destructive-operation",
  tier: "reflex",
  async check(intent) {
    const destructive = ["rm -rf", "DROP TABLE", "DELETE FROM", "git push --force"];
    if (intent.type === "shell_command") {
      const cmd = intent.content.toLowerCase();
      const match = destructive.find(d => cmd.includes(d.toLowerCase()));
      if (match) {
        return {
          allow: false,
          reason: `Destructive operation detected: "${match}"`,
          alternative: "Use a safer alternative or request explicit confirmation",
        };
      }
    }
    return { allow: true };
  },
};

const BUDGET_CEILING_REFLEX: Instinct = {
  name: "budget-ceiling",
  tier: "reflex",
  async check(intent) {
    if (intent.type === "api_call" && intent.metadata?.estimatedCost) {
      const sessionBudget = intent.metadata.sessionBudget || 10.0;
      const spent = intent.metadata.sessionSpent || 0;
      if (spent + intent.metadata.estimatedCost > sessionBudget) {
        return {
          allow: false,
          reason: `Would exceed session budget ($${spent} + $${intent.metadata.estimatedCost} > $${sessionBudget})`,
        };
      }
    }
    return { allow: true };
  },
};

关卡:范围验证:

class ScopeValidationGate:
    """Ensures the agent's action is within the stated task scope."""

    def __init__(self, allowed_paths: list[str], allowed_operations: list[str]):
        self.allowed_paths = [re.compile(p) for p in allowed_paths]
        self.allowed_operations = set(allowed_operations)

    async def check(self, intent):
        if intent["type"] not in self.allowed_operations:
            return {
                "allow": False,
                "reason": f"Operation '{intent['type']}' not in allowed set: {self.allowed_operations}",
            }
        if intent.get("target"):
            if not any(p.match(intent["target"]) for p in self.allowed_paths):
                return {
                    "allow": False,
                    "reason": f"Path '{intent['target']}' outside allowed scope",
                    "alternative": f"Allowed paths: {[p.pattern for p in self.allowed_paths]}",
                }
        return {"allow": True}

最佳实践

  1. 让反射机制零成本运行 — 第 1 层反射必须在 1ms 内执行完毕,且不进行任何 I/O;任何需要网络调用或模型推理的操作都应归入更高层级。
  2. 让拒绝具有可操作性 — 每个被拦截的意图都应说明原因,并在可能的情况下提供 Agent 可采取的替代操作。
  3. 从拒绝列表开始,逐步转向允许列表 — 先拦截已知的危险操作,然后逐步收紧规则,只允许明确安全的操作。
  4. 记录所有本能机制的触发情况 — 所有被拦截和被允许的意图都应记录下来,以供审计和本能机制学习。
  5. 绝不因任务“可信”而跳过本能机制 — 本能机制系统是一张安全网;为了方便而绕过它,会使其完全失去作用。
  6. 根据事故推导新的本能机制 — 每次生产事故都应催生至少一种新的反射机制或关卡,以防止事故重演。
  7. 使用对抗性意图测试本能机制 — 构造旨在绕过每种本能机制的意图,并验证它们能否被拦截。
  8. 对本能机制配置进行版本管理 — 跟踪各环境(dev/staging/prod)中启用的本能机制,并审计变更。

平台兼容性

功能Claude CodeCursorCodexGemini CLI
操作前钩子✅ PreToolUse✅ Rules✅ Instructions✅ System prompts
文件保护✅ 完整✅ 完整✅ 沙箱✅ 完整
Shell 命令过滤✅ 完整✅ 完整✅ 沙箱✅ 完整
预算强制执行✅ 自定义钩子✅ 扩展✅ 自定义✅ 自定义
操作后审计✅ PostToolUse✅ Rules✅ 自定义✅ 自定义

相关技能

  • 对抗性韧性 - 通过分层防御抵御提示注入和数据泄露,与本能级保护相辅相成
  • 验证循环 - 操作后评估流程,在本能机制批准操作后验证输出
  • 自我修复 Agent - 当本能机制关卡检测到故障时触发的自主错误恢复机制

关键词

agent-instincts, pre-flight-checks, safety-gates, reflexes, destructive-operation-prevention, scope-validation, budget-ceiling, protected-files, defense-in-depth, agent-skills


© 2026 googleadsagent.ai™ | Agent Skills™ | MIT License

评论

支持 Markdown