Galaxies occupy different regions of the [OIII]$lambda5007$/H$beta$-versus-[NII]$lambda6584$/H$alpha$ emission-line ratio diagram in the distant and local Universe. We investigate the origin of this intriguing result by modelling self-consistently, for the first time, nebular emission from young stars, accreting black holes (BHs) and older, post-asymptotic-giant-branch (post-AGB) stellar populations in galaxy formation simulations in a full cosmological context. In post-processing, we couple new-generation nebular-emission models with high-resolution, cosmological zoom-in simulations of massive galaxies to explore which galaxy physical properties drive the cosmic evolution of the optical-line ratios [OIII]$lambda5007$/H$beta$, [NII]$lambda6584$/H$alpha$, [SII]$lambdalambda6717,6731$/H$alpha$ and [OI]$lambda6300$/H$alpha$. The line ratios of simulated galaxies agree well with observations of both star-forming and active local SDSS galaxies. Towards higher redshifts, at fixed galaxy stellar mass, the average [OIII]/H$beta$ increases and [NII]/H$alpha$, [SII]/H$alpha$ and [OI]/H$alpha$ decrease -- widely consistent with observations. At fixed stellar mass, we identify star formation history, which controls nebular emission from young stars via the ionization parameter, as the primary driver of the cosmic evolution of [OIII]/H$beta$ and [NII]/H$alpha$. For [SII]/H$alpha$ and [OI]/H$alpha$, this applies only to redshifts above $z=1.5$, the evolution at lower redshift being driven in roughly equal parts by nebular emission from AGN and post-AGB stars. Instead, changes in the hardness of ionizing radiation, ionized-gas density, the prevalence of BH accretion relative to star formation and the dust-to-metal mass ratio (whose impact on the gas-phase N/O ratio we model at fixed O/H) play at most a minor role in the cosmic evolution of simulated galaxy line ratios.