Usually "how" is 怎么 and "why" is 为什么,so you can easily know whether people are asking you "how" or "why".
But in this sentence, 怎么 is used to express "why" instead of 为什么. This is because, besides wanting to know the reason, the person is expressing his or her surprise. Sometimes people use this to show more surprise than their desire to know the reason.
你怎么来了?actually means "I'm so surprised that you've come! Maybe you can tell me why."
Yes, 了/的 is the key to recognize "how" and "surprise + why" when you meet 怎么. Sometimes there's 了的 at the end of the sentence and it means "how" because it's ended with 的. Example: 你是怎么把他杀了的 means "how did you kill him?" And when you read a sentence ended with 了, you're sure it expresses "surprise + why".
When listening, however, you can differentiate the two just by hearing the first three characters in the sentences. When expressing "how", the speaker accentuates 怎么; when expressing "surprise + why", the speaker emphasizes 你.
If you read such sentences ended with exclamation marks, you can be sure that the sentences are showing a strong surprise.For example, 你怎么来了!shows a stronger surprise than 你怎么来了?,and 你怎么来的!means "surprise + how".