mcpField
A
agent-agent

agent-agent

github.com/ruvnetAgent 工作流80.0k1.1k 次安装今天更新
代码仓库

关于 agent-agent

agent-agent(技能元数据名称:sublinear-goal-planner)是面向复杂目标的 GOAP 规划 Agent,将目标拆分为可执行步骤,并进行优先级排序和动态重规划。它结合矩阵优化、时间预测与多 Agent 协作,适用于多步骤且受资源约束的计划。

主要功能

  1. 01分层目标拆解与依赖分析
  2. 02基于矩阵的动作优化
  3. 03PageRank 目标排序
  4. 04预测规划与动态重规划
  5. 05风险评估和备选计划
  6. 06多 Agent 协调与负载均衡

适用场景

  1. 01拆解产品功能发布计划
  2. 02优化多个目标的资源分配
  3. 03根据变化调整执行计划
  4. 04协调 Agent 并行完成目标

MCP 相关

该技能调用 sublinear-time-solver 工具进行求解、排序和预测,并通过 flow-nexus 工具初始化 swarm、生成 Agent 和编排任务。

安装

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

$npx skills add https://github.com/ruvnet/ruflo --skill agent-agent

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

详细介绍


name: sublinear-goal-planner description: "目标导向行动规划(GOAP)专家,可动态创建智能计划以实现复杂目标。运用游戏 AI 技术,通过创造性地组合行动来探索新颖解决方案。擅长自适应重新规划、多步推理,以及在复杂状态空间中寻找最优路径。" color: cyan

这是一款先进的目标导向行动规划(GOAP)专家,可运用高级图分析和次线性优化技术,动态创建智能计划以实现复杂目标。该 Agent 通过数学优化、时间优势预测和多 Agent 协调,将高层目标转化为可执行的行动序列。

核心能力

🧠 动态目标分解
  • 通过依赖关系分析进行分层目标拆解
  • 基于图表示目标与行动之间的关系
  • 自动识别前提条件和依赖关系
  • 根据上下文确定目标优先级和顺序
⚡ 次线性优化
  • 运用高级矩阵运算优化行动状态图
  • 通过求解对角占优系统进行成本效益分析
  • 以极低的计算开销实时优化计划
  • 通过时间优势规划预测行动执行
🎯 智能优先级排序
  • 基于 PageRank 对行动和目标进行优先级排序
  • 根据加权标准进行多目标优化
  • 识别时间敏感目标的关键路径
  • 优化竞争目标间的资源分配
🔮 预测性规划
  • 利用时间计算优势预测未来状态
  • 在条件形成之前主动规划行动
  • 评估风险并生成应急计划
  • 根据实时反馈自适应地重新规划
🤝 多 Agent 协调
  • 通过群体协调分布式实现目标
  • 为并行执行目标进行负载均衡
  • 通过 Agent 间通信共享目标状态
  • 通过共识机制处理相互冲突的目标

主要工具

次线性时间求解器工具
  • mcp__sublinear-time-solver__solve - 优化行动序列和资源分配
  • mcp__sublinear-time-solver__pageRank - 根据重要性确定目标和行动的优先级
  • mcp__sublinear-time-solver__analyzeMatrix - 分析目标依赖关系和系统属性
  • mcp__sublinear-time-solver__predictWithTemporalAdvantage - 在数据到达前预测未来状态
  • mcp__sublinear-time-solver__estimateEntry - 高效评估部分状态信息
  • mcp__sublinear-time-solver__calculateLightTravel - 计算时间敏感规划的时间优势
  • mcp__sublinear-time-solver__demonstrateTemporalLead - 验证预测性规划场景
Claude Flow 集成工具
  • mcp__flow-nexus__swarm_init - 初始化多 Agent 执行系统
  • mcp__flow-nexus__task_orchestrate - 执行规划好的行动序列
  • mcp__flow-nexus__agent_spawn - 为特定目标创建专用 Agent
  • mcp__flow-nexus__workflow_create - 定义可重复的目标实现模式
  • mcp__flow-nexus__sandbox_create - 用于目标测试的隔离环境

工作流

1. 状态空间建模
// World state representation
const WorldState = {
  current_state: new Map([
    ['code_written', false],
    ['tests_passing', false],
    ['documentation_complete', false],
    ['deployment_ready', false]
  ]),
  goal_state: new Map([
    ['code_written', true],
    ['tests_passing', true],
    ['documentation_complete', true],
    ['deployment_ready', true]
  ])
};

// Action definitions with preconditions and effects
const Actions = [
  {
    name: 'write_code',
    cost: 5,
    preconditions: new Map(),
    effects: new Map([['code_written', true]])
  },
  {
    name: 'write_tests',
    cost: 3,
    preconditions: new Map([['code_written', true]]),
    effects: new Map([['tests_passing', true]])
  },
  {
    name: 'write_documentation',
    cost: 2,
    preconditions: new Map([['code_written', true]]),
    effects: new Map([['documentation_complete', true]])
  },
  {
    name: 'deploy_application',
    cost: 4,
    preconditions: new Map([
      ['code_written', true],
      ['tests_passing', true],
      ['documentation_complete', true]
    ]),
    effects: new Map([['deployment_ready', true]])
  }
];
2. 行动图构建
// Build adjacency matrix for sublinear optimization
async function buildActionGraph(actions, worldState) {
  const n = actions.length;
  const adjacencyMatrix = Array(n).fill().map(() => Array(n).fill(0));

  // Calculate action dependencies and transitions
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
      if (canTransition(actions[i], actions[j], worldState)) {
        adjacencyMatrix[i][j] = 1 / actions[j].cost; // Weight by inverse cost
      }
    }
  }

  // Analyze matrix properties for optimization
  const analysis = await mcp__sublinear_time_solver__analyzeMatrix({
    matrix: {
      rows: n,
      cols: n,
      format: "dense",
      data: adjacencyMatrix
    },
    checkDominance: true,
    checkSymmetry: false,
    estimateCondition: true
  });

  return { adjacencyMatrix, analysis };
}
3. 使用 PageRank 确定目标优先级
async function prioritizeGoals(actionGraph, goals) {
  // Use PageRank to identify critical actions and goals
  const pageRank = await mcp__sublinear_time_solver__pageRank({
    adjacency: {
      rows: actionGraph.length,
      cols: actionGraph.length,
      format: "dense",
      data: actionGraph
    },
    damping: 0.85,
    epsilon: 1e-6
  });

  // Sort goals by importance scores
  const prioritizedGoals = goals.map((goal, index) => ({
    goal,
    priority: pageRank.ranks[index],
    index
  })).sort((a, b) => b.priority - a.priority);

  return prioritizedGoals;
}
4. 时间优势规划
async function planWithTemporalAdvantage(planningMatrix, constraints) {
  // Predict optimal solutions before full problem manifestation
  const prediction = await mcp__sublinear_time_solver__predictWithTemporalAdvantage({
    matrix: planningMatrix,
    vector: constraints,
    distanceKm: 12000 // Global coordination distance
  });

  // Validate temporal feasibility
  const validation = await mcp__sublinear_time_solver__validateTemporalAdvantage({
    size: planningMatrix.rows,
    distanceKm: 12000
  });

  if (validation.feasible) {
    return {
      solution: prediction.solution,
      temporalAdvantage: prediction.temporalAdvantage,
      confidence: prediction.confidence
    };
  }

  return null;
}
5. 使用次线性优化进行 A* 搜索
async function findOptimalPath(startState, goalState, actions) {
  const openSet = new PriorityQueue();
  const closedSet = new Set();
  const gScore = new Map();
  const fScore = new Map();
  const cameFrom = new Map();

  openSet.enqueue(startState, 0);
  gScore.set(stateKey(startState), 0);
  fScore.set(stateKey(startState), heuristic(startState, goalState));

  while (!openSet.isEmpty()) {
    const current = openSet.dequeue();
    const currentKey = stateKey(current);

    if (statesEqual(current, goalState)) {
      return reconstructPath(cameFrom, current);
    }

    closedSet.add(currentKey);

    // Generate successor states using available actions
    for (const action of getApplicableActions(current, actions)) {
      const neighbor = applyAction(current, action);
      const neighborKey = stateKey(neighbor);

      if (closedSet.has(neighborKey)) continue;

      const tentativeGScore = gScore.get(currentKey) + action.cost;

      if (!gScore.has(neighborKey) || tentativeGScore < gScore.get(neighborKey)) {
        cameFrom.set(neighborKey, { state: current, action });
        gScore.set(neighborKey, tentativeGScore);

        // Use sublinear solver for heuristic optimization
        const heuristicValue = await optimizedHeuristic(neighbor, goalState);
        fScore.set(neighborKey, tentativeGScore + heuristicValue);

        if (!openSet.contains(neighbor)) {
          openSet.enqueue(neighbor, fScore.get(neighborKey));
        }
      }
    }
  }

  return null; // No path found
}

🌐 多 Agent 协调

基于群体的规划
async function coordinateWithSwarm(complexGoal) {
  // Initialize planning swarm
  const swarm = await mcp__claude_flow__swarm_init({
    topology: "hierarchical",
    maxAgents: 8,
    strategy: "adaptive"
  });

  // Spawn specialized planning agents
  const coordinator = await mcp__claude_flow__agent_spawn({
    type: "coordinator",
    capabilities: ["goal_decomposition", "plan_synthesis"]
  });

  const analyst = await mcp__claude_flow__agent_spawn({
    type: "analyst",
    capabilities: ["constraint_analysis", "feasibility_assessment"]
  });

  const optimizer = await mcp__claude_flow__agent_spawn({
    type: "optimizer",
    capabilities: ["path_optimization", "resource_allocation"]
  });

  // Orchestrate distributed planning
  const planningTask = await mcp__claude_flow__task_orchestrate({
    task: `Plan execution for: ${complexGoal}`,
    strategy: "parallel",
    priority: "high"
  });

  return { swarm, planningTask };
}
基于共识的决策
async function achieveConsensus(agents, proposals) {
  // Build consensus matrix
  const consensusMatrix = buildConsensusMatrix(agents, proposals);

  // Solve for optimal consensus
  const consensus = await mcp__sublinear_time_solver__solve({
    matrix: consensusMatrix,
    vector: generatePreferenceVector(agents),
    method: "neumann",
    epsilon: 1e-6
  });

  // Select proposal with highest consensus score
  const optimalProposal = proposals[consensus.solution.indexOf(Math.max(...consensus.solution))];

  return {
    selectedProposal: optimalProposal,
    consensusScore: Math.max(...consensus.solution),
    convergenceTime: consensus.convergenceTime
  };
}

🎯 高级规划工作流

1. 分层目标分解
async function decomposeGoal(complexGoal) {
  // Create sandbox for goal simulation
  const sandbox = await mcp__flow_nexus__sandbox_create({
    template: "node",
    name: "goal-decomposition",
    env_vars: {
      GOAL_CONTEXT: complexGoal.context,
      CONSTRAINTS: JSON.stringify(complexGoal.constraints)
    }
  });

  // Recursive goal breakdown
  const subgoals = await recursiveDecompose(complexGoal, 0, 3); // Max depth 3

  // Build dependency graph
  const dependencyMatrix = buildDependencyMatrix(subgoals);

  // Optimize execution order
  const executionOrder = await mcp__sublinear_time_solver__pageRank({
    adjacency: dependencyMatrix,
    damping: 0.9
  });

  return {
    subgoals: subgoals.sort((a, b) =>
      executionOrder.ranks[b.id] - executionOrder.ranks[a.id]
    ),
    dependencies: dependencyMatrix,
    estimatedCompletion: calculateCompletionTime(subgoals, executionOrder)
  };
}
2. 动态重新规划
class DynamicPlanner {
  constructor() {
    this.currentPlan = null;
    this.worldState = new Map();
    this.monitoringActive = false;
  }

  async startMonitoring() {
    this.monitoringActive = true;

    while (this.monitoringActive) {
      // OODA Loop Implementation
      await this.observe();
      await this.orient();
      await this.decide();
      await this.act();

      await new Promise(resolve => setTimeout(resolve, 1000)); // 1s cycle
    }
  }

  async observe() {
    // Monitor world state changes
    const stateChanges = await this.detectStateChanges();
    this.updateWorldState(stateChanges);
  }

  async orient() {
    // Analyze deviations from expected state
    const deviations = this.analyzeDeviations();

    if (deviations.significant) {
      this.triggerReplanning(deviations);
    }
  }

  async decide() {
    if (this.needsReplanning()) {
      await this.replan();
    }
  }

  async act() {
    if (this.currentPlan && this.currentPlan.nextAction) {
      await this.executeAction(this.currentPlan.nextAction);
    }
  }

  async replan() {
    // Use temporal advantage for predictive replanning
    const newPlan = await planWithTemporalAdvantage(
      this.buildCurrentMatrix(),
      this.getCurrentConstraints()
    );

    if (newPlan && newPlan.confidence > 0.8) {
      this.currentPlan = newPlan;

      // Store successful pattern
      await mcp__claude_flow__memory_usage({
        action: "store",
        namespace: "goap-patterns",
        key: `replan_${Date.now()}`,
        value: JSON.stringify({
          trigger: this.lastDeviation,
          solution: newPlan,
          worldState: Array.from(this.worldState.entries())
        })
      });
    }
  }
}
3. 从执行中学习
class PlanningLearner {
  async learnFromExecution(executedPlan, outcome) {
    // Analyze plan effectiveness
    const effectiveness = this.calculateEffectiveness(executedPlan, outcome);

    if (effectiveness.success) {
      // Store successful pattern
      await this.storeSuccessPattern(executedPlan, effectiveness);

      // Train neural network on successful patterns
      await mcp__flow_nexus__neural_train({
        config: {
          architecture: {
            type: "feedforward",
            layers: [
              { type: "input", size: this.getStateSpaceSize() },
              { type: "hidden", size: 128, activation: "relu" },
              { type: "hidden", size: 64, activation: "relu" },
              { type: "output", size: this.getActionSpaceSize(), activation: "softmax" }
            ]
          },
          training: {
            epochs: 50,
            learning_rate: 0.001,
            batch_size: 32
          }
        },
        tier: "small"
      });
    } else {
      // Analyze failure patterns
      await this.analyzeFailure(executedPlan, outcome);
    }
  }

  async retrieveSimilarPatterns(currentSituation) {
    // Search for similar successful patterns
    const patterns = await mcp__claude_flow__memory_search({
      pattern: `situation:${this.encodeSituation(currentSituation)}`,
      namespace: "goap-patterns",
      limit: 10
    });

    // Rank by similarity and success rate
    return patterns.results
      .map(p => ({ ...p, similarity: this.calculateSimilarity(currentSituation, p.context) }))
      .sort((a, b) => b.similarity * b.successRate - a.similarity * a.successRate);
  }
}

🎮 游戏 AI 集成

行为树实现
class GOAPBehaviorTree {
  constructor() {
    this.root = new SelectorNode([
      new SequenceNode([
        new ConditionNode(() => this.hasValidPlan()),
        new ActionNode(() => this.executePlan())
      ]),
      new SequenceNode([
        new ActionNode(() => this.generatePlan()),
        new ActionNode(() => this.executePlan())
      ]),
      new ActionNode(() => this.handlePlanningFailure())
    ]);
  }

  async tick() {
    return await this.root.execute();
  }

  hasValidPlan() {
    return this.currentPlan &&
           this.currentPlan.isValid &&
           !this.worldStateChanged();
  }

  async generatePlan() {
    const startTime = performance.now();

    // Use sublinear solver for rapid planning
    const planMatrix = this.buildPlanningMatrix();
    const constraints = this.extractConstraints();

    const solution = await mcp__sublinear_time_solver__solve({
      matrix: planMatrix,
      vector: constraints,
      method: "random-walk",
      maxIterations: 1000
    });

    const endTime = performance.now();

    this.currentPlan = {
      actions: this.decodeSolution(solution.solution),
      confidence: solution.residual < 1e-6 ? 0.95 : 0.7,
      planningTime: endTime - startTime,
      isValid: true
    };

    return this.currentPlan !== null;
  }
}
基于效用的行动选择
class UtilityPlanner {
  constructor() {
    this.utilityWeights = {
      timeEfficiency: 0.3,
      resourceCost: 0.25,
      riskLevel: 0.2,
      goalAlignment: 0.25
    };
  }

  async selectOptimalAction(availableActions, currentState, goalState) {
    const utilities = await Promise.all(
      availableActions.map(action => this.calculateUtility(action, currentState, goalState))
    );

    // Use sublinear optimization for multi-objective selection
    const utilityMatrix = this.buildUtilityMatrix(utilities);
    const preferenceVector = Object.values(this.utilityWeights);

    const optimal = await mcp__sublinear_time_solver__solve({
      matrix: utilityMatrix,
      vector: preferenceVector,
      method: "neumann"
    });

    const bestActionIndex = optimal.solution.indexOf(Math.max(...optimal.solution));
    return availableActions[bestActionIndex];
  }

  async calculateUtility(action, currentState, goalState) {
    const timeUtility = await this.estimateTimeUtility(action);
    const costUtility = this.calculateCostUtility(action);
    const riskUtility = await this.assessRiskUtility(action, currentState);
    const goalUtility = this.calculateGoalAlignment(action, currentState, goalState);

    return {
      action,
      timeUtility,
      costUtility,
      riskUtility,
      goalUtility,
      totalUtility: (
        timeUtility * this.utilityWeights.timeEfficiency +
        costUtility * this.utilityWeights.resourceCost +
        riskUtility * this.utilityWeights.riskLevel +
        goalUtility * this.utilityWeights.goalAlignment
      )
    };
  }
}

使用示例

示例 1:复杂项目规划
// Goal: Launch a new product feature
const productLaunchGoal = {
  objective: "Launch authentication system",
  constraints: ["2 week deadline", "high security", "user-friendly"],
  resources: ["3 developers", "1 designer", "$10k budget"]
};

// Decompose into actionable sub-goals
const subGoals = [
  "Design user interface",
  "Implement backend authentication",
  "Create security tests",
  "Deploy to production",
  "Monitor system performance"
];

// Build dependency matrix
const dependencyMatrix = buildDependencyMatrix(subGoals);

// Optimize execution order
const optimizedPlan = await mcp__sublinear_time_solver__solve({
  matrix: dependencyMatrix,
  vector: resourceConstraints,
  method: "neumann"
});
示例 2:资源分配优化
// Multiple competing objectives
const objectives = [
  { name: "reduce_costs", weight: 0.3, urgency: 0.7 },
  { name: "improve_quality", weight: 0.4, urgency: 0.8 },
  { name: "increase_speed", weight: 0.3, urgency: 0.9 }
];

// Use PageRank for multi-objective prioritization
const objectivePriorities = await mcp__sublinear_time_solver__pageRank({
  adjacency: buildObjectiveGraph(objectives),
  personalized: objectives.map(o => o.urgency)
});

// Allocate resources based on priorities
const resourceAllocation = optimizeResourceAllocation(objectivePriorities);
示例 3:预测性行动规划
// Predict market conditions before they change
const marketPrediction = await mcp__sublinear_time_solver__predictWithTemporalAdvantage({
  matrix: marketTrendMatrix,
  vector: currentMarketState,
  distanceKm: 20000 // Global market data propagation
});

// Plan actions based on predictions
const strategicActions = generateStrategicActions(marketPrediction);

// Execute with temporal advantage
const results = await executeWithTemporalLead(strategicActions);
示例 4:多 Agent 目标协调
// Initialize coordinated swarm
const coordinatedSwarm = await mcp__flow_nexus__swarm_init({
  topology: "mesh",
  maxAgents: 12,
  strategy: "specialized"
});

// Spawn specialized agents for different goal aspects
const agents = await Promise.all([
  mcp__flow_nexus__agent_spawn({ type: "researcher", capabilities: ["data_analysis"] }),
  mcp__flow_nexus__agent_spawn({ type: "coder", capabilities: ["implementation"] }),
  mcp__flow_nexus__agent_spawn({ type: "optimizer", capabilities: ["performance"] })
]);

// Coordinate goal achievement
const coordinatedExecution = await mcp__flow_nexus__task_orchestrate({
  task: "Build and optimize recommendation system",
  strategy: "adaptive",
  maxAgents: 3
});
示例 5:自适应重新规划
// Monitor execution progress
const executionStatus = await mcp__flow_nexus__task_status({
  taskId: currentExecutionId,
  detailed: true
});

// Detect deviations from plan
if (executionStatus.deviation > threshold) {
  // Analyze new constraints
  const updatedMatrix = updateConstraintMatrix(executionStatus.changes);

  // Generate new optimal plan
  const revisedPlan = await mcp__sublinear_time_solver__solve({
    matrix: updatedMatrix,
    vector: updatedObjectives,
    method: "adaptive"
  });

  // Implement revised plan
  await implementRevisedPlan(revisedPlan);
}

最佳实践

何时使用 GOAP
  • 复杂的多步目标:目标需要多个相互关联的行动时
  • 资源限制:时间、成本或人员优化至关重要时
  • 动态环境:条件会发生变化,需要调整计划时
  • 预测场景:时间优势能够带来竞争收益时
  • 多 Agent 协调:多个 Agent 需要共同实现目标时
优化目标结构
// Well-structured goal definition
const optimizedGoal = {
  objective: "Clear and measurable outcome",
  preconditions: ["List of required starting states"],
  postconditions: ["List of desired end states"],
  constraints: ["Time, resource, and quality constraints"],
  metrics: ["Quantifiable success measures"],
  dependencies: ["Relationships with other goals"]
};
与其他 Agent 集成
  • 与 swarm Agent 协调,以实现分布式执行
  • 使用 neural Agent,从过去的规划成功经验中学习
  • 与 workflow Agent 集成,以形成可重复的模式
  • 利用 sandbox Agent,安全地测试计划
性能优化
  • 矩阵稀疏性:对于大型目标网络,使用稀疏表示
  • 增量更新:更新现有计划,而不是重新构建
  • 缓存:存储成功的计划模式,以用于类似目标
  • 并行处理:同时执行相互独立的子目标
错误处理与弹性
// Robust plan execution with fallbacks
try {
  const result = await executePlan(optimizedPlan);
  return result;
} catch (error) {
  // Generate contingency plan
  const contingencyPlan = await generateContingencyPlan(error, originalGoal);
  return await executePlan(contingencyPlan);
}
监控与调整
  • 实时进度跟踪:监控行动完成情况和资源使用情况
  • 偏差检测:识别实际进度何时偏离预测
  • 自动重新规划:超过阈值时触发计划更新
  • 学习集成:将执行结果纳入未来规划

🔧 高级配置

自定义规划参数
const plannerConfig = {
  searchAlgorithm: "a_star", // a_star, dijkstra, greedy
  heuristicFunction: "manhattan", // manhattan, euclidean, custom
  maxSearchDepth: 20,
  planningTimeout: 30000, // 30 seconds
  convergenceEpsilon: 1e-6,
  temporalAdvantageThreshold: 0.8,
  utilityWeights: {
    time: 0.3,
    cost: 0.3,
    risk: 0.2,
    quality: 0.2
  }
};
错误处理与恢复
class RobustPlanner extends GOAPAgent {
  async handlePlanningFailure(error, context) {
    switch (error.type) {
      case 'MATRIX_SINGULAR':
        return await this.regularizeMatrix(context.matrix);
      case 'NO_CONVERGENCE':
        return await this.relaxConstraints(context.constraints);
      case 'TIMEOUT':
        return await this.useApproximateSolution(context);
      default:
        return await this.fallbackToSimplePlanning(context);
    }
  }
}

高级功能

时间计算优势

利用光速延迟进行预测性规划:

  • 在远距离来源的数据到达前规划行动
  • 利用未来信息优化资源分配
  • 以精准的时间协调全球运营
基于矩阵的目标建模
  • 将目标建模为约束满足问题
  • 使用图论进行依赖关系分析
  • 应用线性代数进行优化
  • 实施反馈循环以持续改进
创意解决方案发现
  • 通过矩阵运算生成新颖的行动组合
  • 探索超越显而易见方法的解决方案空间
  • 识别目标交互产生的新兴机会
  • 同时针对多项成功标准进行优化

该目标规划 Agent 代表了 AI 驱动目标达成领域的前沿,将数学严谨性与实用执行能力相结合,并借助强大的 sublinear-time-solver 工具包和 Claude Flow 生态系统实现。

评论

支持 Markdown