The massive cores of the giant planets are thought to have formed in a gas disk by the accretion of pebble-sized particles whose accretional cross-section was enhanced by aerodynamic gas drag1,2. A commonly held view is that the terrestrial planet system formed later (30-200 Myr after the dispersal of the gas disk) by giant collisions of tens of lunar- to Mars-sized protoplanets3,4. Here we propose, instead, that the terrestrial planets of the Solar System formed earlier by the gas-driven convergent migration of protoplanets towards ~1 au. To investigate situations in which convergent migration occurs and determine the thermal structure of the gas and pebble disks in the terrestrial planet zone, we developed a radiation-hydrodynamic model with realistic opacities5,6. We find that protoplanets grow in the first 10 Myr by mutual collisions and pebble accretion, and gain orbital eccentricities by gravitational scattering and the hot-trail effect7,8. The orbital structure of the inner Solar System is well reproduced in our simulations, including its tight mass concentration at 0.7-1 au and the small sizes of Mercury and Mars. The early-stage protosolar disk temperature exceeds 1,500 K inside 0.4 au, implying that Mercury grew in a highly reducing environment next to the evaporation lines of iron and silicates, influencing Mercury's bulk composition9. A dissipating gas disk, however, is cold, and pebbles drifting from larger heliocentric distances would deliver volatile elements.