South Africa left-arm spinner Senuran Muthusamy took 6-117 on Monday, including three wickets in four balls, as Pakistan collapsed from 362-5 to 378 all out on day two of the first Test in Lahore.
Pakistan famously used patio heaters and industrial fans to produce dry, turning tracks in their 2-1 series win over England last year.
Pakistan were 91-3 in reply, but a magnificent 260-run fourth wicket stand between Agha (134), who scored his maiden ODI ton, and Mohammad Rizwan (122 not out) took Pakistan to victory with six balls to spare.
Left-handed opening batter Ayub made a sparkling 101 off 94 balls in a Pakistan total of 308 for nine.
Pakistan narrowly lost by one wicket on Friday, their fourth straight defeat after two wins in six matches.