Files
makemd/docs/01_Architecture/19_Agent_Features_Plan.md
wurenzhi 15ee1758f5 refactor: 重构项目结构并优化类型定义
- 移除extension模块,将功能迁移至node-agent
- 修复类型导出问题,使用export type明确类型导出
- 统一数据库连接方式,从直接导入改为使用config/database
- 更新文档中的项目结构描述
- 添加多个服务的实用方法,如getForecast、getBalances等
- 修复类型错误和TS1205警告
- 优化RedisService调用方式
- 添加新的实体类型定义
- 更新审计日志格式,统一字段命名
2026-03-21 15:04:06 +08:00

21 KiB

Agent功能方案

创建日期: 2026-03-20
状态: 设计中
优先级: 最高


1. Agent架构总览

1.1 Agent类型

┌─────────────────────────────────────────────────────────────────────────────┐
│                           Agent 功能架构                                     │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │                     Node Agent (Playwright)                          │   │
│  │  ┌─────────────────────────────────────────────────────────────┐   │   │
│  │  │                    平台采集 Agent                             │   │   │
│  │  │  - TikTok Shop  - Temu  - Amazon  - Shopee  - AliExpress    │   │   │
│  │  └─────────────────────────────────────────────────────────────┘   │   │
│  │  ┌─────────────────────────────────────────────────────────────┐   │   │
│  │  │                    自动化操作 Agent                           │   │   │
│  │  │  - 刊登  - 定价  - 订单处理  - 广告投放  - 库存同步           │   │   │
│  │  └─────────────────────────────────────────────────────────────┘   │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                              │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │                     AI Agent (智能决策)                              │   │
│  │  ┌─────────────────────────────────────────────────────────────┐   │   │
│  │  │                    决策 Agent                                │   │   │
│  │  │  - 选品决策  - 定价决策  - 库存决策  - 营销决策              │   │   │
│  │  └─────────────────────────────────────────────────────────────┘   │   │
│  │  ┌─────────────────────────────────────────────────────────────┐   │   │
│  │  │                    分析 Agent                                │   │   │
│  │  │  - 趋势分析  - 竞品分析  - 利润分析  - 风险分析              │   │   │
│  │  └─────────────────────────────────────────────────────────────┘   │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                              │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │                     Operation Agent (运营代理)                       │   │
│  │  ┌─────────────────────────────────────────────────────────────┐   │   │
│  │  │                    任务编排 Agent                            │   │   │
│  │  │  - 任务调度  - 依赖管理  - 失败重试  - 结果上报              │   │   │
│  │  └─────────────────────────────────────────────────────────────┘   │   │
│  │  ┌─────────────────────────────────────────────────────────────┐   │   │
│  │  │                    监控 Agent                                │   │   │
│  │  │  - 健康检查  - 性能监控  - 异常告警  - 自动恢复              │   │   │
│  │  └─────────────────────────────────────────────────────────────┘   │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘

2. Node Agent (平台执行代理)

2.1 核心能力

能力 描述 技术实现
无API平台采集 TikTok Shop, Temu, 1688等无API平台 Playwright浏览器自动化
自动化操作 刊登、定价、订单处理、广告投放 平台适配器封装
反检测 指纹隔离、代理IP、行为模拟 多浏览器上下文
多实例并发 支持多店铺同时运行 任务队列 + 并发控制

2.2 任务类型定义

export enum TaskType {
  // 采集类任务
  COLLECT_PRODUCT = 'COLLECT_PRODUCT',       // 商品采集
  COLLECT_ORDER = 'COLLECT_ORDER',           // 订单采集
  COLLECT_AD = 'COLLECT_AD',                 // 广告数据采集
  COLLECT_INVENTORY = 'COLLECT_INVENTORY',   // 库存数据采集
  
  // 操作类任务
  PUBLISH_PRODUCT = 'PUBLISH_PRODUCT',       // 商品刊登
  UPDATE_PRICE = 'UPDATE_PRICE',             // 价格更新
  PROCESS_ORDER = 'PROCESS_ORDER',           // 订单处理
  SYNC_INVENTORY = 'SYNC_INVENTORY',         // 库存同步
  MANAGE_AD = 'MANAGE_AD',                   // 广告管理
  
  // 客服类任务
  REPLY_MESSAGE = 'REPLY_MESSAGE',           // 消息回复
  HANDLE_RETURN = 'HANDLE_RETURN',           // 退货处理
  ISSUE_REFUND = 'ISSUE_REFUND',             // 退款处理
}

export interface NodeTask {
  taskId: string;
  traceId: string;
  tenantId: string;
  shopId: string;
  type: TaskType;
  platform: string;
  params: Record<string, any>;
  priority: 'HIGH' | 'MEDIUM' | 'LOW';
  timeout: number;
  retryCount: number;
  createdAt: number;
}

2.3 平台适配器

export interface IPlatformAdapter {
  platform: string;
  
  // 采集方法
  collectProduct(params: CollectParams): Promise<ProductData[]>;
  collectOrder(params: CollectParams): Promise<OrderData[]>;
  collectInventory(params: CollectParams): Promise<InventoryData[]>;
  
  // 操作方法
  publishProduct(product: ProductData): Promise<PublishResult>;
  updatePrice(productId: string, price: number): Promise<UpdateResult>;
  processOrder(orderId: string, action: OrderAction): Promise<ProcessResult>;
  
  // 认证方法
  login(credentials: Credentials): Promise<LoginResult>;
  checkSession(): Promise<boolean>;
  logout(): Promise<void>;
}

// 平台适配器工厂
export class PlatformAdapterFactory {
  static create(platform: string): IPlatformAdapter {
    switch (platform) {
      case 'tiktok': return new TikTokAdapter();
      case 'temu': return new TemuAdapter();
      case 'amazon': return new AmazonAdapter();
      case 'shopee': return new ShopeeAdapter();
      case 'aliexpress': return new AliExpressAdapter();
      case '1688': return new Ali1688Adapter();
      default: throw new Error(`Unsupported platform: ${platform}`);
    }
  }
}

2.4 反检测策略

export interface AntiDetectionConfig {
  // 浏览器指纹
  fingerprint: {
    userAgent: string;
    viewport: { width: number; height: number };
    timezone: string;
    language: string;
    platform: string;
    webgl: { vendor: string; renderer: string };
    canvas: string;
  };
  
  // 代理配置
  proxy: {
    server: string;
    username?: string;
    password?: string;
  };
  
  // 行为模拟
  behavior: {
    mouseMovement: boolean;
    randomDelay: { min: number; max: number };
    scrollBehavior: 'smooth' | 'auto';
    typingSpeed: { min: number; max: number };
  };
  
  // 会话隔离
  isolation: {
    profileDir: string;
    cookies: boolean;
    localStorage: boolean;
    sessionStorage: boolean;
  };
}

2.5 任务执行流程

1. 任务接收
   └── 从Hub拉取任务 → 验证任务参数 → 加入执行队列

2. 环境准备
   └── 创建浏览器上下文 → 应用反检测配置 → 登录平台

3. 任务执行
   └── 获取平台适配器 → 执行具体操作 → 捕获结果/异常

4. 结果上报
   └── 生成执行报告 → 上报结果到Hub → 清理环境

5. 异常处理
   └── 捕获异常 → 判断是否重试 → 上报失败原因

3. AI Agent (智能决策代理)

3.1 决策Agent

3.1.1 选品决策Agent

export class ProductSelectionAgent {
  /**
   * 执行选品决策
   */
  async execute(params: {
    tenantId: string;
    platforms: string[];
    categories: string[];
    constraints: SelectionConstraints;
  }): Promise<SelectionResult> {
    // 1. 数据采集
    const products = await this.collectProducts(params);
    
    // 2. 特征提取
    const features = await this.extractFeatures(products);
    
    // 3. 评分计算
    const scores = await this.calculateScores(features);
    
    // 4. 排序筛选
    const selected = this.rankAndFilter(scores, params.constraints);
    
    // 5. 生成建议
    return this.generateRecommendations(selected);
  }
  
  /**
   * 评分维度
   */
  private scoringWeights = {
    profitRate: 0.3,      // 利润率
    salesVolume: 0.2,     // 销量
    competition: 0.15,    // 竞争度
    trend: 0.15,          // 趋势
    rating: 0.1,          // 评分
    supplier: 0.1,        // 供应商可靠性
  };
}

3.1.2 定价决策Agent

export class PricingDecisionAgent {
  /**
   * 执行定价决策
   */
  async execute(params: {
    productId: string;
    platform: string;
    strategy: 'MAX_PROFIT' | 'MAX_VOLUME' | 'BALANCED';
    constraints: PricingConstraints;
  }): Promise<PricingResult> {
    // 1. 成本分析
    const costs = await this.analyzeCosts(params.productId);
    
    // 2. 竞品分析
    const competitors = await this.analyzeCompetitors(params.productId, params.platform);
    
    // 3. 需求预测
    const demand = await this.predictDemand(params.productId);
    
    // 4. 价格优化
    const optimalPrice = await this.optimizePrice({
      costs,
      competitors,
      demand,
      strategy: params.strategy,
      constraints: params.constraints,
    });
    
    // 5. 风险评估
    const risk = this.assessRisk(optimalPrice, costs);
    
    return {
      recommendedPrice: optimalPrice.price,
      expectedProfit: optimalPrice.profit,
      expectedVolume: optimalPrice.volume,
      riskLevel: risk.level,
      confidence: optimalPrice.confidence,
    };
  }
}

3.1.3 库存决策Agent

export class InventoryDecisionAgent {
  /**
   * 执行库存决策
   */
  async execute(params: {
    tenantId: string;
    skuId: string;
    warehouseId: string;
  }): Promise<InventoryDecision> {
    // 1. 销量预测
    const forecast = await InventoryForecastService.getForecast(params.tenantId);
    
    // 2. 安全库存计算
    const safetyStock = this.calculateSafetyStock(forecast);
    
    // 3. 补货点计算
    const reorderPoint = this.calculateReorderPoint(forecast, safetyStock);
    
    // 4. 补货量计算
    const reorderQuantity = this.calculateReorderQuantity(forecast);
    
    // 5. 生成建议
    return {
      currentStock: await this.getCurrentStock(params.skuId),
      forecastedDemand: forecast,
      safetyStock,
      reorderPoint,
      reorderQuantity,
      recommendation: this.generateRecommendation({
        currentStock: await this.getCurrentStock(params.skuId),
        reorderPoint,
        reorderQuantity,
      }),
    };
  }
}

3.2 分析Agent

3.2.1 趋势分析Agent

export class TrendAnalysisAgent {
  /**
   * 分析市场趋势
   */
  async analyze(params: {
    category: string;
    platform: string;
    timeRange: { start: Date; end: Date };
  }): Promise<TrendAnalysis> {
    // 1. 数据采集
    const data = await this.collectTrendData(params);
    
    // 2. 时间序列分析
    const timeSeries = this.analyzeTimeSeries(data);
    
    // 3. 趋势识别
    const trends = this.identifyTrends(timeSeries);
    
    // 4. 预测
    const predictions = this.predictTrends(trends);
    
    return {
      currentTrend: trends.current,
      predictedTrend: predictions,
      seasonality: timeSeries.seasonality,
      opportunities: this.identifyOpportunities(trends),
      risks: this.identifyRisks(trends),
    };
  }
}

3.2.2 竞品分析Agent

export class CompetitorAnalysisAgent {
  /**
   * 分析竞争对手
   */
  async analyze(params: {
    productId: string;
    platform: string;
  }): Promise<CompetitorAnalysis> {
    // 1. 识别竞品
    const competitors = await this.identifyCompetitors(params.productId);
    
    // 2. 价格对比
    const priceComparison = this.comparePrices(params.productId, competitors);
    
    // 3. 销量对比
    const salesComparison = await this.compareSales(params.productId, competitors);
    
    // 4. 策略分析
    const strategies = this.analyzeStrategies(competitors);
    
    return {
      competitors,
      priceComparison,
      salesComparison,
      strategies,
      recommendations: this.generateRecommendations({
        priceComparison,
        salesComparison,
        strategies,
      }),
    };
  }
}

4. Operation Agent (运营代理)

4.1 任务编排Agent

export class TaskOrchestrationAgent {
  private taskQueue: PriorityQueue<NodeTask>;
  private executor: TaskExecutor;
  
  /**
   * 提交任务
   */
  async submitTask(task: NodeTask): Promise<string> {
    // 1. 验证任务
    this.validateTask(task);
    
    // 2. 检查依赖
    await this.checkDependencies(task);
    
    // 3. 加入队列
    await this.taskQueue.enqueue(task);
    
    // 4. 触发执行
    this.triggerExecution();
    
    return task.taskId;
  }
  
  /**
   * 执行任务
   */
  private async executeTask(task: NodeTask): Promise<TaskResult> {
    try {
      // 1. 预处理
      await this.preProcess(task);
      
      // 2. 执行
      const result = await this.executor.execute(task);
      
      // 3. 后处理
      await this.postProcess(task, result);
      
      // 4. 上报结果
      await this.reportResult(task, result);
      
      return result;
    } catch (error) {
      // 异常处理
      await this.handleError(task, error);
      throw error;
    }
  }
}

4.2 监控Agent

export class MonitoringAgent {
  /**
   * 健康检查
   */
  async healthCheck(): Promise<HealthStatus> {
    return {
      status: 'healthy',
      checks: {
        database: await this.checkDatabase(),
        redis: await this.checkRedis(),
        queue: await this.checkQueue(),
        agents: await this.checkAgents(),
      },
      timestamp: Date.now(),
    };
  }
  
  /**
   * 性能监控
   */
  async monitorPerformance(): Promise<PerformanceMetrics> {
    return {
      cpu: await this.getCpuUsage(),
      memory: await this.getMemoryUsage(),
      network: await this.getNetworkStats(),
      tasks: await this.getTaskStats(),
      latency: await this.getLatencyStats(),
    };
  }
  
  /**
   * 异常告警
   */
  async alertAnomaly(anomaly: Anomaly): Promise<void> {
    // 1. 记录异常
    await this.recordAnomaly(anomaly);
    
    // 2. 发送通知
    await this.sendNotification(anomaly);
    
    // 3. 尝试自动恢复
    if (anomaly.autoRecoverable) {
      await this.attemptRecovery(anomaly);
    }
  }
}

5. Agent协作模式

5.1 协作流程

用户请求 → AI Agent (决策) → Operation Agent (编排) → Node Agent (执行)
                ↓                    ↓                    ↓
            决策结果            任务调度              执行结果
                ↓                    ↓                    ↓
            ←────────────────── 结果反馈 ──────────────────

5.2 消息协议

export interface AgentMessage {
  messageId: string;
  traceId: string;
  from: string;
  to: string;
  type: 'REQUEST' | 'RESPONSE' | 'NOTIFICATION' | 'ERROR';
  payload: any;
  timestamp: number;
}

export interface DecisionRequest {
  decisionType: 'SELECTION' | 'PRICING' | 'INVENTORY' | 'MARKETING';
  context: Record<string, any>;
  constraints: Record<string, any>;
}

export interface ExecutionRequest {
  taskId: string;
  taskType: TaskType;
  platform: string;
  params: Record<string, any>;
}

6. Agent配置管理

6.1 全局配置

export interface AgentGlobalConfig {
  // Hub配置
  hub: {
    url: string;
    apiKey: string;
    timeout: number;
  };
  
  // 并发配置
  concurrency: {
    maxConcurrent: number;
    perShop: number;
    perPlatform: number;
  };
  
  // 重试配置
  retry: {
    maxAttempts: number;
    backoff: 'LINEAR' | 'EXPONENTIAL';
    baseInterval: number;
  };
  
  // 超时配置
  timeout: {
    default: number;
    collect: number;
    publish: number;
    process: number;
  };
  
  // 监控配置
  monitoring: {
    healthCheckInterval: number;
    metricsInterval: number;
    alertThresholds: Record<string, number>;
  };
}

6.2 店铺级配置

export interface ShopAgentConfig {
  shopId: string;
  platform: string;
  
  // 代理配置
  proxy: {
    enabled: boolean;
    server: string;
    username?: string;
    password?: string;
  };
  
  // 指纹配置
  fingerprint: {
    userAgent: string;
    viewport: { width: number; height: number };
    timezone: string;
    language: string;
  };
  
  // 行为配置
  behavior: {
    randomDelay: { min: number; max: number };
    mouseMovement: boolean;
    typingSpeed: { min: number; max: number };
  };
  
  // 任务配置
  tasks: {
    autoCollect: boolean;
    collectInterval: number;
    autoSync: boolean;
    syncInterval: number;
  };
}

7. 实现优先级

P0 - 核心Agent (立即完成)

  1. Node Agent基础框架

    • 任务调度器
    • 平台适配器接口
    • 反检测基础能力
  2. AI决策Agent

    • 选品决策
    • 定价决策
    • 库存决策

P1 - 重要Agent (近期完成)

  1. 平台适配器

    • TikTok Shop适配器
    • Temu适配器
    • Amazon适配器
  2. 分析Agent

    • 趋势分析
    • 竞品分析
    • 利润分析

P2 - 增强Agent (后续完成)

  1. 监控Agent

    • 健康检查
    • 性能监控
    • 异常告警
  2. 高级功能

    • 自动恢复
    • 智能调度
    • 策略优化

8. 相关文档


最后更新: 2026-03-20