How do chess engines decide which best line to play when the game outcome is within their horizon? Inspired by the Hot Network Question "In this puzzle, why does white play dxe5?", when a chess engine is in a position that it can definitively call lost, drawn, or won, what policy is used to decide among lines that lead to the same outcome?

In a won position, the answer seems easy: play the line that leads to checkmate fastest.  But in a lost or drawn position, the engine's opponent may not realize the situation, so it should continue fighting, ideally playing a complicated line and setting traps in hopes of swindling a draw or win.  But it is not clear to me how the code could identify such a line from a game tree and evaluation scores alone.

(In a game with time controls, the answer may be more complicated; I am okay with an answer that ignores considerations of time pressure.)
If the engine can choose between getting mated in 2 or mated in 3, it'll choose the line where it is mated in 3 (even though the mate in 2 might be 'more difficult' to spot for humans).

It can't really set traps, because it doesn't know what things might be difficult to spot for a human (or other engine) opponent. It just evaluates the position, without really knowing it's playing a game against somebody; a notable exception is the implementation of contempt, basically a slight modification of the evaluation in order to prevent drawing too early.

For example, in Stockfish, scores for won or lost positions are computed with the function mated_in (and, more rarely, its negated form mate_in).  As you can see in the code, a loss is scored as a large negative value plus the number of ply until the loss, so the engine favors winning lines that are fast and losing lines that are slow.

The tie-breaking for draws is usually arbitrary.  For instance, in Stockfish, scores for drawn positions are either the constant VALUE_DRAW or computed by the function value_draw to be VALUE_DRAW plus one or plus two.  The bonus depends on the thread's node counter, which is essentially up to luck, so the variations in scores for drawn positions are not really based on the positions themselves.  This small bit of noise in draw scoring is more to keep the search from fixating on certain three-fold repetitions than to help it choose among lines.