handlers.js 2.83 KB
/**
 * Claude Stream 消息处理器
 *
 * 后端只做:内部状态管理 + 纯文本流式输出
 * 工具调用等结构化信息通过 acp_event 原样透传,由前端自行解析展示
 */

/**
 * 创建统一的 session_update 事件(纯文本流式块)
 */
function createSessionUpdate(text) {
  return {
    update: {
      sessionUpdate: 'agent_message_chunk',
      content: { type: 'text', text }
    }
  };
}

/**
 * 消息处理器集合
 * key: message.type 或 message.type:message.subtype
 */
const handlers = {
  /**
   * system:init - 初始化消息
   */
  'system:init': (msg, ctx) => {
    ctx.protocol.sessionId = msg.session_id;
    ctx.log(`init 收到, session_id: ${msg.session_id}`);
  },

  /**
   * stream_event - 流式输出事件
   * 只处理纯文本 delta,工具信息通过 acp_event 原样透传
   */
  'stream_event': (msg, ctx) => {
    const event = msg.event;
    if (!event) return;

    ctx.protocol._hasStreamEvents = true;

    if (event.type === 'content_block_delta') {
      if (event.delta?.type === 'text_delta') {
        const text = event.delta.text || '';
        if (text) {
          ctx.appendOutput(text);
          ctx.emit('session_update', createSessionUpdate(text));
        }
      }
    }
  },

  /**
   * assistant - AI 响应消息(完整消息,非流式模式下使用)
   */
  'assistant': (msg, ctx) => {
    if (ctx.protocol._hasStreamEvents) return;
    if (!msg.message?.content) return;

    for (const block of msg.message.content) {
      if (block.type === 'text') {
        ctx.appendOutput(block.text);
        ctx.emit('session_update', createSessionUpdate(block.text));
      }
      // tool_use 等其他 block 类型通过 acp_event 原样透传
    }
  },

  /**
   * user - 用户消息(含工具执行结果)
   * 不做任何转换,原始数据通过 acp_event 透传给前端
   */
  'user': (msg, ctx) => { },

  /**
   * result - 最终结果
   */
  'result': (msg, ctx) => {
    ctx.log(`result: ${msg.subtype}, duration: ${msg.duration_ms}ms`);
  }
};

/**
 * 处理消息的入口函数
 */
function handleMessage(msg, ctx) {
  const exactKey = msg.subtype ? `${msg.type}:${msg.subtype}` : null;
  if (exactKey && handlers[exactKey]) {
    handlers[exactKey](msg, ctx);
    return true;
  }

  if (handlers[msg.type]) {
    handlers[msg.type](msg, ctx);
    return true;
  }

  ctx.log(`未处理的消息类型: ${msg.type}${msg.subtype ? ':' + msg.subtype : ''}`);
  return false;
}

/**
 * 注册自定义处理器
 */
function registerHandler(key, handler) {
  handlers[key] = handler;
}

/**
 * 注册自定义 content block 处理器(保留接口兼容)
 */
function registerContentBlockHandler(type, handler) {
  // no-op: 工具信息不再在后端处理
}

module.exports = {
  handleMessage,
  registerHandler,
  registerContentBlockHandler,
  createSessionUpdate
};