I think Pakistan always knew that the US would lose its war in Afghanistan and Iraq.
The Taliban are a faceless enemy: you kill one and 10 others will join to fight against you because that is the only way to earn a living in many Afghan regions.
So Pakistan also chose to keep contacts with these organisations because eventually, once the US made a mess of the region and left, Pakistan will have to face a probably Taliban/ Al Qaeda government.
I think that was probably the original thinking but as it turns out, the border between Afghanistan and Pakistan is a 2000 kilometers long mountain chain that is impossible to effectively control.
So now both countries have an extremist problem.