Protocol.js 2.19 KB
/**
 * Protocol - 协议层抽象基类
 *
 * 定义协议层接口,所有协议实现(ACP、MCP等)都需要实现这个接口。
 * 这确保了不同协议有一致的对外接口。
 */

const { EventEmitter } = require('events');

/**
 * 协议基类
 *
 * Events:
 * - 'session:update': 会话状态更新
 * - 'stream:update': 流式内容更新
 * - 'permission:request': 权限请求
 * - 'error': 错误
 * - 'disconnected': 断开连接
 * - 'output': 标准输出
 * - 'stderr': 标准错误
 */
class Protocol extends EventEmitter {
  constructor(config, options = {}) {
    super();
    this.config = config;
    this.options = {
      defaultTimeout: 60000,
      promptTimeout: 0, // 0 = 无超时,任务可能持续数小时
      ...options,
    };
    this.isConnected = false;
    this.sessionId = null;
  }

  /**
   * 协议名称
   * @returns {string}
   */
  get name() {
    throw new Error('Protocol.name getter must be implemented');
  }

  /**
   * 连接到后端
   * @param {string} workingDir - 工作目录
   * @returns {Promise<void>}
   */
  async connect(workingDir) {
    throw new Error('Protocol.connect() must be implemented');
  }

  /**
   * 初始化协议(握手)
   * @returns {Promise<object>}
   */
  async initialize() {
    throw new Error('Protocol.initialize() must be implemented');
  }

  /**
   * 创建新会话
   * @param {object} options - 会话选项
   * @returns {Promise<{ sessionId: string }>}
   */
  async newSession(options = {}) {
    throw new Error('Protocol.newSession() must be implemented');
  }

  /**
   * 发送消息
   * @param {string} text - 消息文本
   * @param {string[]} files - 相关文件路径
   * @returns {Promise<object>}
   */
  async sendPrompt(text, files = []) {
    throw new Error('Protocol.sendPrompt() must be implemented');
  }

  /**
   * 响应权限请求
   * @param {number|string} requestId - 请求 ID
   * @param {string} optionId - 选项 ID
   */
  respondPermission(requestId, optionId) {
    throw new Error('Protocol.respondPermission() must be implemented');
  }

  /**
   * 断开连接
   */
  disconnect() {
    throw new Error('Protocol.disconnect() must be implemented');
  }
}

module.exports = { Protocol };