const MISSING_AGENT_SESSION_MESSAGE = 'Agent 会话不存在';

/**
 * 提取请求层抛出的错误消息。
 */
export function resolveAgentSessionErrorMessage(error: unknown): string {
  if (error instanceof Error) {
    return error.message;
  }
  if (!error || typeof error !== 'object') {
    return '';
  }
  const payload = error as Record<string, unknown>;
  if (typeof payload.message === 'string') {
    return payload.message;
  }
  const response = payload.response;
  if (!response || typeof response !== 'object') {
    return '';
  }
  const data = (response as Record<string, unknown>).data;
  if (!data || typeof data !== 'object') {
    return '';
  }
  const message = (data as Record<string, unknown>).message;
  return typeof message === 'string' ? message : '';
}

/**
 * 判断请求是否因 Agent 会话已不存在而失败。
 */
export function isMissingAgentSessionError(error: unknown): boolean {
  return resolveAgentSessionErrorMessage(error).includes(
    MISSING_AGENT_SESSION_MESSAGE,
  );
}
