_launchers.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  1. """Source-install launchers shared by setup, installers, and Windows repair.
  2. Launchers execute store Python in isolated mode. They set the install's
  3. default home and load hermes_bootstrap before the entry point. Bootstrap
  4. reads the selected dependency generation at each start.
  5. Windows uses distlib executables or a command-file fallback. POSIX uses
  6. an executable shell wrapper. The standalone writer requires PM's store
  7. interpreter before it publishes either command.
  8. """
  9. from __future__ import annotations
  10. from contextlib import suppress
  11. import json
  12. import os
  13. import shlex
  14. import sys
  15. from pathlib import Path
  16. if __name__ == "__main__":
  17. sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
  18. from pm.environments import owning_home_root, store_root
  19. # ``sys`` attribute a launcher sets before ``import hermes_bootstrap``: pin HERMES_HOME to the
  20. # install's default root once the launch-time repair ran (``hermes_bootstrap._pin_launcher_home``).
  21. PIN_DEFAULT_HOME_FLAG = "_hermes_pin_default_home"
  22. def _inline_string_literal(value: str) -> str:
  23. """Keep inline Python source intact through Windows PowerShell's native argv quoting."""
  24. if os.name != "nt":
  25. return repr(value)
  26. escaped = value.encode("unicode_escape").decode("ascii")
  27. return "'" + escaped.replace("'", "\\x27").replace('"', "\\x22") + "'"
  28. def runtime_command(repo_root: Path, args=(), *, module: str = "hermes_cli.main",
  29. code: str | None = None, python: str | Path | None = None,
  30. home: str | Path | None = None) -> list[str]:
  31. """An installation-bound command, safe to persist across dependency GC.
  32. Store Python owns the ABI; bootstrap selects and leases dependencies at
  33. child start. Nix and developer interpreters retain their external owner.
  34. No selected generation or ambient PYTHONPATH is captured in the command.
  35. """
  36. root = Path(repo_root).resolve()
  37. python = python or resolve_store_python(root) or Path(sys.executable)
  38. entry = f"exec({_inline_string_literal(code)})" if code is not None else (
  39. f"runpy.run_module({_inline_string_literal(module)}, run_name='__main__', alter_sys=True)")
  40. # A literal home is pinned up front; the default one needs ``hermes_constants`` from the
  41. # checkout, so it is pinned only after ``hermes_bootstrap``'s launch-time repair (see
  42. # ``_launcher_script``), here again for a bootstrap that predates that hook.
  43. if home is not None:
  44. pin, settle = (f"os.environ['HERMES_HOME'] = os.environ.get('HERMES_HOME') or "
  45. f"{_inline_string_literal(str(home))}; "), ""
  46. else:
  47. pin = f"sys.{PIN_DEFAULT_HOME_FLAG} = True; "
  48. settle = ("os.environ.get('HERMES_HOME') or os.environ.__setitem__('HERMES_HOME', "
  49. "str(__import__('hermes_constants').get_default_hermes_root())); ")
  50. bootstrap = (
  51. "import os, sys, runpy; "
  52. "os.environ.pop('PYTHONHOME', None); os.environ.pop('PYTHONPATH', None); "
  53. "os.environ.pop('VIRTUAL_ENV', None); "
  54. f"sys.path.insert(0, {_inline_string_literal(str(root))}); "
  55. + pin
  56. + "import hermes_bootstrap; "
  57. + settle
  58. + entry
  59. )
  60. return [str(python), "-I", "-c", bootstrap, *args]
  61. def print_runtime_command(repo_root: Path, argv: list[str]) -> None:
  62. """Machine boundary for consumers holding the exact published launcher."""
  63. import argparse
  64. parser = argparse.ArgumentParser(description="Resolve this installation's launch command.")
  65. parser.add_argument("--module", default="hermes_cli.main")
  66. parser.add_argument("args", nargs=argparse.REMAINDER)
  67. options = parser.parse_args(argv)
  68. args = options.args[1:] if options.args[:1] == ["--"] else options.args
  69. print(json.dumps(runtime_command(repo_root, args, module=options.module)))
  70. def installation_command(repo_root: Path, args=(), *, module: str = "hermes_cli.main",
  71. python: str | Path | None = None, home: str | Path | None = None) -> list[str]:
  72. """Persist a source launcher, never the versioned tool it currently uses.
  73. External/Nix installs retain their externally owned interpreter contract.
  74. Source installation/update publication refreshes the local launcher when
  75. the managed Python pin changes.
  76. """
  77. root = Path(repo_root)
  78. if resolve_store_python(root) is None:
  79. return runtime_command(root, args, module=module, python=python, home=home)
  80. prefix = [] if module == "hermes_cli.main" else ["--run-module", module]
  81. return [str(root / ".hermes" / "bin" / "hermes"), *prefix, *args]
  82. #: Launcher command names — keep in lockstep with scripts/install.ps1
  83. #: Publish-UserCommand and hermes_cli/_install_repair.py.
  84. WINDOWS_BIN_LAUNCHERS = ("hermes", "hermes-acp")
  85. #: command name -> (entry module, callable) — mirrors pyproject.toml
  86. #: [project.scripts].
  87. ENTRY_POINTS = {
  88. "hermes": ("hermes_cli.main", "main"),
  89. "hermes-acp": ("acp_adapter.entry", "main"),
  90. }
  91. def _is_windows() -> bool:
  92. return os.name == "nt"
  93. def resolve_store_python(repo_root: Path, *, publication: bool = False) -> Path | None:
  94. """Read PM's committed Python tool, without adopting unrecorded bytes.
  95. Callers that PERSIST the result in a launcher (``stage_launcher`` and the
  96. publication gates below) pass ``publication=True``: the tree's own store
  97. wins over an inherited ``HERMES_RUNTIME_DIR``. The override names a store
  98. for the running process (an e2e fixture, a desktop toolchain) that a later
  99. scratch cleanup may delete, leaving the launcher to exit 127 forever
  100. (#131745). It still supplies the store when the tree records none.
  101. """
  102. if publication:
  103. own = _store_python(store_root(repo_root, honor_runtime_override=False))
  104. if own is not None:
  105. return own
  106. return _store_python(store_root(repo_root))
  107. def _store_python(runtime: Path) -> Path | None:
  108. rel = "python.exe" if _is_windows() else "bin/python3"
  109. facts = runtime / "facts.json"
  110. if facts.is_file():
  111. try:
  112. packages = json.loads(facts.read_text(encoding="utf-8-sig")).get(
  113. "packages", {}
  114. )
  115. entry = (packages.get("python") or {}).get("entry")
  116. except (OSError, ValueError):
  117. entry = None
  118. if entry:
  119. candidate = runtime / entry / rel
  120. if candidate.is_file():
  121. return candidate
  122. return None
  123. def _load_script_maker():
  124. """distlib's ScriptMaker — standalone first, then pip's vendored copy."""
  125. try:
  126. from distlib.scripts import ScriptMaker
  127. return ScriptMaker
  128. except ImportError:
  129. pass
  130. try:
  131. from pip._vendor.distlib.scripts import ScriptMaker
  132. return ScriptMaker
  133. except ImportError:
  134. return None
  135. def _store_script_maker(python_exe: Path):
  136. """ScriptMaker from the pip that ships with the interpreter being bound.
  137. A launch activates only the dependency environment, which carries no
  138. distlib and drops the store's site-packages, so the update that repins
  139. Python could only publish a .cmd and retire hermes.exe -- which Desktop's
  140. backend sweep, shortcuts and terminal profiles name. python-build-standalone
  141. ships pip (the installer mints the first hermes.exe through it), and its
  142. vendored distlib is self-contained. It loads under a private name so the
  143. store's pip never answers an ``import pip`` in this process."""
  144. package = Path(python_exe).parent / "Lib" / "site-packages" / "pip" / "_vendor" / "distlib"
  145. if not (package / "scripts.py").is_file():
  146. return None
  147. import hashlib
  148. import importlib
  149. import importlib.util
  150. # One private package per store copy: a later repin's pip never reuses the first one's.
  151. name = f"_hermes_store_distlib_{hashlib.sha256(str(package).encode()).hexdigest()[:12]}"
  152. try:
  153. if name not in sys.modules:
  154. spec = importlib.util.spec_from_file_location(
  155. name, package / "__init__.py", submodule_search_locations=[str(package)])
  156. if spec is None or spec.loader is None:
  157. return None
  158. sys.modules[name] = importlib.util.module_from_spec(spec)
  159. spec.loader.exec_module(sys.modules[name])
  160. return importlib.import_module(f"{name}.scripts").ScriptMaker
  161. except (ImportError, OSError, SyntaxError, AttributeError): # a torn or foreign pip: mint a .cmd
  162. sys.modules.pop(name, None)
  163. return None
  164. def exe_is_venv_bound(exe: Path, venv_dir: Path | None) -> bool:
  165. """True when an existing launcher exe embeds the venv interpreter —
  166. i.e. it is a copied venv console-script trampoline from the pre-pm
  167. installer, which boots through ``venv\\Scripts\\python.exe`` and must be
  168. replaced. distlib launchers append the interpreter shebang after the zip
  169. payload; both encodings are scanned to be safe."""
  170. if venv_dir is None:
  171. return False
  172. needles = set()
  173. for interpreter in (
  174. venv_dir / "Scripts" / "hermes.exe",
  175. venv_dir / "Scripts" / "hermes-acp.exe",
  176. venv_dir / "Scripts" / "python.exe",
  177. venv_dir / "bin" / "python3",
  178. venv_dir / "bin" / "hermes",
  179. venv_dir / "bin" / "hermes-acp",
  180. ):
  181. for enc in ("utf-8", "utf-16-le"):
  182. try:
  183. needles.add(str(interpreter).encode(enc))
  184. except Exception:
  185. continue
  186. try:
  187. data = Path(exe).read_bytes()
  188. except OSError:
  189. return False
  190. return any(needle in data for needle in needles)
  191. def _write_atomic(target: Path, write) -> Path | None:
  192. """Stage under a pid-suffixed name then os.replace, so a concurrent
  193. process start never sees a torn launcher."""
  194. staging = target.with_name(f"{target.name}.stage.{os.getpid()}")
  195. try:
  196. write(staging)
  197. os.replace(staging, target)
  198. return target
  199. except OSError:
  200. try:
  201. staging.unlink()
  202. except OSError:
  203. pass
  204. return None
  205. def mint_launcher(
  206. name: str,
  207. repo_root: Path,
  208. out_dir: Path,
  209. python_exe: Path,
  210. site_packages: Path | None,
  211. ) -> Path | None:
  212. """Write a native launcher with the shared bootstrap script, or return None."""
  213. module, func = ENTRY_POINTS[name]
  214. out_dir = Path(out_dir)
  215. script = _launcher_script(name, Path(repo_root), site_packages)
  216. if not _is_windows():
  217. return _mint_shell_launcher(name, out_dir, python_exe, script)
  218. script_maker_cls = _load_script_maker() or _store_script_maker(python_exe)
  219. if script_maker_cls is not None:
  220. class _PathedScriptMaker(script_maker_cls): # type: ignore[misc,valid-type]
  221. def _get_script_text(self, entry):
  222. return script
  223. import tempfile
  224. from zipfile import BadZipFile, ZipFile
  225. def make(directory: Path) -> list[str]:
  226. maker = _PathedScriptMaker(None, str(directory), add_launchers=True)
  227. maker.executable = str(python_exe)
  228. maker.variants = {""}
  229. maker.clobber = True
  230. return maker.make(f"{name} = {module}:{func}", {"interpreter_args": ["-I"]})
  231. # distlib's exe ZIP records the current time, so byte equality cannot
  232. # detect an unchanged launcher. Compare its loader + shebang and script;
  233. # leave an active executable alone when only the ZIP timestamp changed.
  234. with tempfile.TemporaryDirectory(prefix=f".{name}-", dir=out_dir) as staging:
  235. try:
  236. candidate = next((Path(p) for p in make(Path(staging))
  237. if Path(p).suffix.lower() == ".exe"), None)
  238. except Exception:
  239. candidate = None
  240. if candidate is not None:
  241. target = out_dir / candidate.name
  242. try:
  243. with ZipFile(target) as old, ZipFile(candidate) as new:
  244. if (old.namelist() == new.namelist() == ["__main__.py"]
  245. and target.read_bytes()[:old.infolist()[0].header_offset]
  246. == candidate.read_bytes()[:new.infolist()[0].header_offset]
  247. and old.read("__main__.py") == new.read("__main__.py")):
  248. return target
  249. except (OSError, BadZipFile, KeyError):
  250. pass
  251. # For changed launchers, distlib's .deleteme replacement can
  252. # move an executable Windows still has mapped in memory.
  253. try:
  254. written = make(out_dir)
  255. except Exception:
  256. written = []
  257. for path in written:
  258. if Path(path).suffix.lower() == ".exe":
  259. return Path(path)
  260. # distlib ran but produced no exe (unexpected) — fall through to cmd.
  261. # A prepared app environment need not include distlib, even when the
  262. # installer used it to publish a native exe. Keep that executable if its
  263. # embedded interpreter and script still match; replacing it with a cmd
  264. # would require unlinking the currently running exe on Windows.
  265. existing = out_dir / f"{name}.exe"
  266. from zipfile import BadZipFile, ZipFile
  267. try:
  268. with ZipFile(existing) as archive:
  269. if archive.namelist() == ["__main__.py"]:
  270. prefix = existing.read_bytes()[:archive.infolist()[0].header_offset]
  271. shebangs = (f"#!{python_exe} -I\n".encode(),
  272. f'#!"{python_exe}" -I\n'.encode())
  273. # Vendored distlib trails the shebang with an extra CRLF
  274. # before the zip; compare the shebang line itself.
  275. tail = prefix.rstrip(b"\r\n")
  276. if (any(tail.endswith(shebang.rstrip(b"\r\n")) for shebang in shebangs)
  277. and archive.read("__main__.py") == script.encode("utf-8")):
  278. return existing
  279. except (OSError, BadZipFile, KeyError):
  280. pass
  281. # The script is data to Python, not interpolated shell source.
  282. import base64
  283. encoded = base64.b64encode(script.encode("utf-8")).decode("ascii")
  284. code = f"import base64; exec(base64.b64decode('{encoded}'))"
  285. body = (
  286. "@echo off\r\n"
  287. f'"{python_exe}" -I -c "{code}" %*\r\n'
  288. )
  289. return _write_atomic(out_dir / f"{name}.cmd", lambda p: p.write_text(body, encoding="utf-8"))
  290. # A killed move can tear the repair's own code (``hermes_bootstrap``, ``hermes_cli``). With the
  291. # marker still there, a launcher whose checkout import failed runs the copy of the repair that the
  292. # updater published beside the marker (``update_cmd_commit.publish_recovery_closure``) once every
  293. # file hashes to the blob id its manifest names; a missing, torn or foreign closure (or none, from
  294. # an updater predating it) is rebuilt from git's objects at the marker's ``pre`` with the recorded
  295. # git or an absolute PATH entry (never one from the current directory) and verified the same way.
  296. # Stdlib plus that copy only, under the same claim and checkout lock (a live writer still refuses,
  297. # which exits 1 with the repair's own reason), then a relaunch from the restored tree.
  298. _CLOSURE_REPAIR = """\
  299. def _hermes_closure_repair():
  300. import contextlib, hashlib, io, shutil, subprocess
  301. from pathlib import Path
  302. root = Path(__ROOT__)
  303. git = root / '.git'
  304. try:
  305. if git.is_file():
  306. text = git.read_text(encoding='utf-8-sig').strip()
  307. git = root / text[7:].strip() if text.startswith('gitdir:') else git
  308. fields = dict(line.partition('=')[::2] for line in (git / __MARKER__).read_text(encoding='utf-8-sig').splitlines())
  309. except OSError:
  310. return
  311. pre = fields.get('pre', '').strip()
  312. if not re.fullmatch('[0-9a-f]{40}|[0-9a-f]{64}', pre):
  313. return
  314. closure = git / __CLOSURE_DIR__ / pre
  315. files = (*__CLOSURE__, __INIT__)
  316. def blob_id(data):
  317. return hashlib.new('sha1' if len(pre) == 40 else 'sha256', b'blob %d\\0' % len(data) + data).hexdigest()
  318. def verified():
  319. try:
  320. listed = dict(line.split(' ', 1)[::-1] for line in (closure / __MANIFEST__).read_text(encoding='utf-8-sig').splitlines())
  321. return (set(listed) == set(files) and listed[__INIT__] == blob_id(b'')
  322. and all(blob_id((closure / rel).read_bytes()) == oid for rel, oid in listed.items()))
  323. except (OSError, ValueError):
  324. return False
  325. if not verified():
  326. exe = fields.get('git', '').strip()
  327. if not (os.path.isabs(exe) and os.path.isfile(exe)):
  328. names = ('git.exe',) if os.name == 'nt' else ('git',)
  329. exe = next((os.path.join(d, n) for d in os.environ.get('PATH', '').split(os.pathsep) if os.path.isabs(d)
  330. for n in names if os.path.isfile(os.path.join(d, n))), '')
  331. if not exe:
  332. return
  333. def git_out(*args):
  334. done = subprocess.run([exe, '--no-replace-objects', '-C', str(root), *args], capture_output=True, timeout=60,
  335. stdin=subprocess.DEVNULL, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
  336. if done.returncode != 0:
  337. raise OSError(done.stderr)
  338. return done.stdout
  339. staging = closure.with_name('.%s.%d.launch' % (pre, os.getpid()))
  340. try:
  341. ids = {}
  342. for entry in git_out('ls-tree', '-z', '--full-tree', pre, '--', *__CLOSURE__).split(b'\\0'):
  343. meta, _, rel = entry.decode('utf-8', 'replace').partition('\\t')
  344. if meta.split()[1:2] == ['blob']:
  345. ids[rel] = meta.split()[2]
  346. blobs = {__INIT__: b''}
  347. for rel in __CLOSURE__:
  348. blobs[rel] = git_out('cat-file', 'blob', ids[rel])
  349. if blob_id(blobs[rel]) != ids[rel]: # an object that inflates to bytes pre never had
  350. raise OSError('%s does not hash to %s' % (rel, ids[rel]))
  351. blobs[__MANIFEST__] = ''.join('%s %s\\n' % (blob_id(data), rel) for rel, data in blobs.items()).encode('utf-8')
  352. for rel, data in blobs.items():
  353. (staging / rel).parent.mkdir(parents=True, exist_ok=True)
  354. (staging / rel).write_bytes(data)
  355. shutil.rmtree(closure, ignore_errors=True)
  356. os.replace(staging, closure)
  357. except (OSError, KeyError, subprocess.SubprocessError):
  358. pass
  359. finally:
  360. shutil.rmtree(staging, ignore_errors=True)
  361. if not verified():
  362. return
  363. for name in [n for n in sys.modules if n.split('.')[0] in ('hermes_cli', 'hermes_bootstrap', 'hermes_constants', 'pm')]:
  364. del sys.modules[name]
  365. tree = os.path.normcase(os.path.realpath(root))
  366. sys.path[:] = [str(closure)] + [p for p in sys.path if p and os.path.normcase(os.path.realpath(p)) != tree
  367. and not os.path.normcase(os.path.realpath(p)).startswith(tree + os.sep)]
  368. sys.dont_write_bytecode = True
  369. said = io.StringIO()
  370. restored = False
  371. try:
  372. with contextlib.redirect_stderr(said):
  373. from hermes_cli import _early_recovery
  374. restored = _early_recovery.restore_interrupted_pull(root)
  375. except Exception as exc:
  376. said.write('hermes: the checkout cannot start after an interrupted `hermes update`, and it was not '
  377. 'repaired: %s\\n' % (exc,))
  378. if restored:
  379. sys.stderr.write('hermes: the checkout could not start after an interrupted `hermes update`; '
  380. 'repaired it with the recovery code saved before the update.\\n' + said.getvalue())
  381. _early_recovery.relaunch_after_restore()
  382. sys.stderr.write(said.getvalue() or 'hermes: the checkout cannot start after an interrupted `hermes update`; '
  383. 'launch again once the update that owns it finishes.\\n')
  384. raise SystemExit(1)
  385. """
  386. def _launcher_script(name: str, repo_root: Path, dependencies: Path | None) -> str:
  387. module, func = ENTRY_POINTS[name]
  388. # Profile boot repairs shared launchers: their default must stay at the
  389. # install's dependency root, not whichever profile triggered publication.
  390. #
  391. # The launch-time repair of a checkout a killed update left torn (``hermes_bootstrap`` ->
  392. # ``_early_recovery.restore_interrupted_pull``) runs before ANY other checkout module is
  393. # imported: a merge killed while writing ``hermes_constants.py`` must not stop every launch
  394. # before the repair. The default-home pin (which needs ``hermes_constants``) happens inside
  395. # ``hermes_bootstrap`` right after the repair (``_PIN_DEFAULT_HOME``), and here again for a
  396. # bootstrap that predates that hook.
  397. root = str(repo_root.resolve())
  398. from hermes_cli._early_recovery import (
  399. INTERRUPTED_PULL_MARKER,
  400. RECOVERY_CLOSURE,
  401. RECOVERY_CLOSURE_DIR,
  402. RECOVERY_CLOSURE_INIT,
  403. RECOVERY_CLOSURE_MANIFEST,
  404. )
  405. closure_repair = (_CLOSURE_REPAIR.replace("__MARKER__", repr(INTERRUPTED_PULL_MARKER))
  406. .replace("__CLOSURE_DIR__", repr(RECOVERY_CLOSURE_DIR))
  407. .replace("__MANIFEST__", repr(RECOVERY_CLOSURE_MANIFEST))
  408. .replace("__INIT__", repr(RECOVERY_CLOSURE_INIT))
  409. .replace("__CLOSURE__", repr(RECOVERY_CLOSURE))
  410. .replace("__ROOT__", repr(root))) # last: a path is never re-substituted
  411. return (
  412. # The repair's own stdlib, bound before the checkout root goes on sys.path: a stdlib-named
  413. # file in the tree must not run in its place ahead of the closure's verification. The first
  414. # line stays the shape gateway.status._BOOTSTRAPS recognises as this launcher (#124318).
  415. "import os, re, sys\n"
  416. "import contextlib, hashlib, io, pathlib, shutil, subprocess\n"
  417. "os.environ.pop('PYTHONHOME', None)\n"
  418. "os.environ.pop('PYTHONPATH', None)\n"
  419. f"sys.path.insert(0, {root!r})\n"
  420. + closure_repair +
  421. "if sys.argv[1:2] == ['--print-runtime-command']:\n"
  422. " sys.dont_write_bytecode = True\n"
  423. " from pathlib import Path\n"
  424. " try:\n"
  425. " from hermes_cli import _early_recovery\n"
  426. " except Exception as exc:\n"
  427. " if _hermes_closure_repair() or not isinstance(exc, ImportError):\n"
  428. " raise\n"
  429. " _early_recovery = None # a tree without the repair: the imports below report real damage\n"
  430. f" if _early_recovery is not None and _early_recovery.restore_interrupted_pull(Path({root!r})):\n"
  431. " _early_recovery.relaunch_after_restore()\n"
  432. " from hermes_constants import get_default_hermes_root\n"
  433. " os.environ['HERMES_HOME'] = os.environ.get('HERMES_HOME') or str(get_default_hermes_root())\n"
  434. " from hermes_cli._launchers import print_runtime_command\n"
  435. f" print_runtime_command(Path({root!r}), sys.argv[2:])\n"
  436. " sys.exit(0)\n"
  437. f"sys.{PIN_DEFAULT_HOME_FLAG} = True\n"
  438. "try:\n"
  439. " import hermes_bootstrap\n"
  440. "except Exception:\n"
  441. " _hermes_closure_repair()\n"
  442. " raise\n"
  443. "if not os.environ.get('HERMES_HOME'):\n"
  444. " from hermes_constants import get_default_hermes_root\n"
  445. " os.environ['HERMES_HOME'] = str(get_default_hermes_root())\n"
  446. "if sys.argv[1:2] == ['--run-module']:\n"
  447. " import runpy\n"
  448. " if len(sys.argv) < 3: sys.exit('hermes: --run-module needs a module')\n"
  449. " module = sys.argv.pop(2)\n"
  450. " del sys.argv[1]\n"
  451. " runpy.run_module(module, run_name='__main__', alter_sys=True)\n"
  452. " sys.exit(0)\n"
  453. f"from {module} import {func}\n"
  454. "sys.argv[0] = re.sub(r'(-script\\.pyw|\\.exe)?$', '', sys.argv[0])\n"
  455. f"sys.exit({func}())\n"
  456. )
  457. def _write_shell(target: Path, command: list[str]) -> Path | None:
  458. body = f'#!/bin/sh\nexec {shlex.join(command)} "$@"\n'
  459. try:
  460. if not target.is_symlink() and target.read_bytes() == body.encode("utf-8"):
  461. if os.access(target, os.X_OK):
  462. return target
  463. except OSError:
  464. pass
  465. def write(staging: Path) -> None:
  466. staging.write_text(body, encoding="utf-8", newline="\n")
  467. staging.chmod(0o755)
  468. return _write_atomic(target, write)
  469. def _mint_shell_launcher(name: str, out_dir: Path, python_exe: Path, script: str) -> Path | None:
  470. return _write_shell(out_dir / name, [str(python_exe), "-I", "-c", script])
  471. def _owns_launcher(target: Path, root: Path) -> bool:
  472. """Recognize our old source/venv launchers, never a mere mention in a comment."""
  473. if target.is_symlink():
  474. return target.resolve().is_relative_to(root)
  475. try:
  476. tokens = shlex.split(target.read_text(encoding="utf-8-sig"), comments=True)
  477. except (OSError, UnicodeError, ValueError):
  478. return False
  479. paths = {str(root / p) for p in (
  480. "hermes", "run_agent.py", "venv/bin/python", "venv/bin/python3",
  481. "venv/bin/hermes",
  482. ".hermes/bin/hermes", ".hermes/bin/hermes-acp",
  483. )}
  484. # Current store launchers pass this Python bootstrap as one shell argument.
  485. bootstrap = f"sys.path.insert(0, {str(root)!r})"
  486. if paths.intersection(tokens) or any(bootstrap in token for token in tokens):
  487. return True
  488. # The historical updater wrote ACP as a sibling-hermes forwarder. Adopt
  489. # it only when that sibling demonstrably belongs to this installation.
  490. if target.name == "hermes-acp":
  491. sibling = target.with_name("hermes")
  492. return (tokens == ["exec", str(sibling), "acp", "$@"]
  493. and _owns_launcher(sibling, root))
  494. return False
  495. def _publish_conveniences(root: Path, out_dir: Path, names, *, create: bool = True) -> dict[Path, bool]:
  496. """User-bin commands forward to durable local launchers, not a Python pin."""
  497. if create:
  498. out_dir.mkdir(parents=True, exist_ok=True)
  499. elif not out_dir.is_dir():
  500. return {}
  501. published = {}
  502. for name in names:
  503. target = out_dir / name
  504. if (not create or target.exists() or target.is_symlink()) and not _owns_launcher(target, root):
  505. continue
  506. before = target.lstat().st_mtime_ns if target.exists() or target.is_symlink() else None
  507. command = ([str(root / ".hermes/bin/hermes"), "--run-module", "run_agent"]
  508. if name == "hermes-agent" else [str(root / ".hermes/bin" / name)])
  509. if _write_shell(target, command) is None:
  510. raise OSError(f"could not publish launcher {target}")
  511. published[target] = before != target.lstat().st_mtime_ns
  512. return published
  513. def stage_launcher(name: str, repo_root: Path, out_dir: Path) -> Path | None:
  514. """Publish one launcher bound to store Python, or refuse missing tools."""
  515. repo_root = Path(repo_root)
  516. # A launcher outlives the process that writes it, so the inherited
  517. # runtime override must not displace the tree's own interpreter.
  518. store_python = resolve_store_python(repo_root, publication=True)
  519. if store_python is not None:
  520. path = mint_launcher(name, repo_root, out_dir, store_python, None)
  521. if path is None:
  522. return None
  523. # Any publication collects copies retired by an earlier one, whatever
  524. # launcher form it writes now (distlib may be back since).
  525. _collect_retired(Path(out_dir) / f"{name}.exe")
  526. if path.suffix == ".cmd":
  527. # cmd.exe prefers .exe. An older launcher must not shadow the
  528. # newly published command when distlib is unavailable.
  529. if not _retire_exe(Path(out_dir) / f"{name}.exe"):
  530. return None
  531. return path
  532. return None
  533. def _collect_retired(exe: Path) -> None:
  534. """Delete aside copies of ``exe`` whose process has since exited: ours
  535. (``.<pid>.deleteme``) and distlib's own (``.deleteme``)."""
  536. for leftover in exe.parent.glob(f"{exe.name}*.deleteme"):
  537. with suppress(OSError):
  538. leftover.unlink()
  539. def _retire_exe(exe: Path) -> bool:
  540. """Remove ``exe``; a running one is renamed aside instead.
  541. Windows refuses to delete a mapped image but allows renaming it, and the
  542. launcher a Python repin has to retire is usually the one running
  543. ``hermes update`` (or the launch retrying its owed launcher step), so a
  544. plain unlink left every repinned update owing launchers -- and the install
  545. stamp -- forever. The aside copy goes on the next publication once its
  546. process has exited."""
  547. try:
  548. exe.unlink(missing_ok=True)
  549. return True
  550. except OSError:
  551. pass
  552. aside = exe.with_name(f"{exe.name}.{os.getpid()}.deleteme")
  553. try:
  554. os.replace(exe, aside)
  555. except OSError:
  556. return False
  557. with suppress(OSError):
  558. aside.unlink()
  559. return True
  560. def _first_token(line: str) -> Path | None:
  561. """First whitespace-delimited token of *line*, honoring one quote pair.
  562. The published launchers always carry the interpreter as the first token
  563. (quoted only when the path holds spaces), so full shell lexing — which
  564. would also eat Windows backslashes as escapes — is the wrong tool."""
  565. text = line.strip()
  566. if not text:
  567. return None
  568. if text[0] in "\"'":
  569. end = text.find(text[0], 1)
  570. if end == -1:
  571. return None
  572. return Path(text[1:end])
  573. return Path(text.split(None, 1)[0])
  574. def _launcher_python(target: Path) -> Path | None:
  575. """Embedded interpreter of an existing launcher, else None.
  576. Fail-open: an unrecognized layout republishes exactly as before."""
  577. try:
  578. data = Path(target).read_bytes()
  579. except OSError:
  580. return None
  581. line: str | None = None
  582. suffix = Path(target).suffix.lower()
  583. if suffix == ".exe":
  584. # distlib native launcher: loader stub, "#!<python> -I" shebang, zip.
  585. # The shebang follows the loader's last NUL byte. distlib leaves
  586. # ScriptMaker.executable unquoted, and a Windows path may hold a space
  587. # or "#!", so take the whole line up to " -I".
  588. from zipfile import BadZipFile, ZipFile
  589. try:
  590. with ZipFile(target) as archive:
  591. prefix = data[:archive.infolist()[0].header_offset]
  592. except (BadZipFile, IndexError, OSError):
  593. return None
  594. start = prefix.find(b"#!", prefix.rfind(b"\0") + 1)
  595. shebang = prefix[start + 2:].rstrip(b"\r\n") if start != -1 else b""
  596. if not shebang.endswith(b" -I") or b"\n" in shebang:
  597. return None
  598. try:
  599. return Path(shebang[:-3].decode("utf-8").strip('"'))
  600. except UnicodeDecodeError:
  601. return None
  602. else:
  603. try:
  604. text = data.decode("utf-8-sig")
  605. except UnicodeDecodeError:
  606. return None
  607. lines = text.splitlines()
  608. if suffix == ".cmd":
  609. # "@echo off", then '"<python>" -I -c "<code>" %*'. The file's
  610. # own \r\n pair gains a translated extra \r on Windows writes,
  611. # so the command may sit past a blank line — never assume its index.
  612. line = next((entry for entry in lines[1:] if entry.strip()), None)
  613. if line is None:
  614. return None
  615. else:
  616. # POSIX shell wrapper: "#!/bin/sh", then "exec <python> -I -c ...".
  617. line = next((entry for entry in lines if entry.startswith("exec ")), None)
  618. if line is None:
  619. return None
  620. # The writer quotes with shlex.join, which splices an apostrophe in as
  621. # '"'"', so read the first token the way sh does. Only the first: the
  622. # rest of the line opens a multi-line -c argument.
  623. lexer = shlex.shlex(line.removeprefix("exec "), posix=True)
  624. lexer.whitespace_split = True
  625. try:
  626. token = lexer.get_token()
  627. except ValueError:
  628. return None
  629. return Path(token) if token else None
  630. try:
  631. return _first_token(line)
  632. except (ValueError, OSError):
  633. return None
  634. def _launcher_checkout(target: Path) -> Path | None:
  635. """Checkout an existing Windows launcher starts, else None.
  636. Reads the script ``_launcher_script`` wrote: the ``__main__.py`` of the
  637. distlib executable, or the base64 payload of the ``.cmd`` fallback. Its
  638. first ``sys.path.insert`` names the checkout.
  639. """
  640. import ast
  641. import base64
  642. import re
  643. from zipfile import BadZipFile, ZipFile
  644. try:
  645. if Path(target).suffix.lower() == ".exe":
  646. with ZipFile(target) as archive:
  647. script = archive.read("__main__.py").decode("utf-8")
  648. else:
  649. encoded = re.search(r"exec\(base64\.b64decode\('([A-Za-z0-9+/=]+)'\)\)",
  650. Path(target).read_text(encoding="utf-8-sig"))
  651. if encoded is None:
  652. return None
  653. script = base64.b64decode(encoded[1], validate=True).decode("utf-8")
  654. inserted = re.search(r"""^sys\.path\.insert\(0, ('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")\)\r?$""",
  655. script, re.MULTILINE)
  656. return Path(ast.literal_eval(inserted[1])) if inserted else None
  657. except (OSError, BadZipFile, KeyError, ValueError, SyntaxError):
  658. # binascii.Error and UnicodeDecodeError are ValueErrors.
  659. return None
  660. def _launcher_of_another_checkout(directory: Path, root: Path) -> Path | None:
  661. """A working command in *directory* that starts a checkout other than *root*, else None.
  662. Only the file Windows runs counts: PATHEXT resolves ``.exe`` before
  663. ``.cmd``. A launcher whose checkout or interpreter is gone does not count,
  664. and neither does one this module cannot read.
  665. """
  666. for name in WINDOWS_BIN_LAUNCHERS:
  667. try:
  668. runs = next((target for target in (directory / f"{name}.exe", directory / f"{name}.cmd")
  669. if target.is_file()), None)
  670. if runs is None:
  671. continue
  672. checkout, python = _launcher_checkout(runs), _launcher_python(runs)
  673. if (checkout is not None and python is not None and checkout != root
  674. and checkout.is_dir() and python.is_file()):
  675. return runs
  676. except OSError:
  677. continue
  678. return None
  679. def _is_home_checkout(root: Path, store: Path) -> bool:
  680. """Is *root* the checkout the default data root was installed with?
  681. That checkout sits at ``<home>/<checkout>`` and runs ``<home>/tools``. The
  682. layout alone is not proof: a root that only borrows the checkout can match
  683. it through HERMES_RUNTIME_DIR=<home>/tools, so the home must also own it.
  684. """
  685. from hermes_constants import get_default_hermes_root
  686. home = get_default_hermes_root().resolve()
  687. return (root.parent == home and store.resolve() == (home / "tools").resolve()
  688. and owning_home_root(root) is None)
  689. def _kept_shared_launcher(name: str, local: Path, store: Path, own: Path | None) -> Path | None:
  690. """Existing checkout launcher already bound outside this root's store.
  691. Checkout launchers are shared by every HERMES_HOME; a launch under one
  692. data root must never repoint them at another root's interpreter (#123238):
  693. once that root is deleted, every hermes breaks. Keep the file when it
  694. execs a live interpreter outside *store*. Missing launchers, dead
  695. interpreters and same-store repins still publish. A launcher whose
  696. interpreter is gone is never left in front of a kept one: PATHEXT resolves
  697. the ``.exe`` first, so the kept ``.cmd`` would not be the file that runs."""
  698. if own is None:
  699. # No interpreter recorded for this root: nothing says whether the
  700. # launcher is ours, and callers read the returned count as success, so
  701. # a keep here would report a half-finished store as healthy.
  702. return None
  703. candidates = [local / name] if not _is_windows() else [local / f"{name}.exe", local / f"{name}.cmd"]
  704. dead: list[Path] = []
  705. for target in candidates:
  706. try:
  707. present = target.is_file() or target.is_symlink()
  708. except OSError:
  709. continue
  710. if not present:
  711. continue
  712. python = _launcher_python(target)
  713. if python is None or python == own:
  714. continue
  715. if not python.is_file():
  716. dead.append(target)
  717. continue
  718. try:
  719. # Resolve the store's directories, not the interpreter: a store
  720. # Python may link to one shared outside it.
  721. store_dir = store.resolve()
  722. foreign = not any(parent.resolve() == store_dir for parent in python.parents)
  723. except (OSError, RuntimeError, ValueError):
  724. continue
  725. if foreign:
  726. for stale in dead:
  727. # cmd.exe picks the .exe first; leaving a dead one would run
  728. # instead of the command just kept. stage_launcher drops the
  729. # same shadow when it has to mint a .cmd.
  730. try:
  731. stale.unlink(missing_ok=True)
  732. except OSError:
  733. pass
  734. return target
  735. return None
  736. def ensure_install_launchers(repo_root: Path, out_dir: Path) -> list[str]:
  737. """Publish exact-install commands; conveniences follow them across Python repins."""
  738. root = Path(repo_root).resolve()
  739. local = root / ".hermes" / "bin"
  740. local.mkdir(parents=True, exist_ok=True)
  741. store = store_root(root)
  742. own = resolve_store_python(root)
  743. # The checkout this data root was installed with always republishes, which
  744. # also heals an install that an earlier foreign launch already rebound.
  745. owner = _is_home_checkout(root, store)
  746. written = []
  747. for name in WINDOWS_BIN_LAUNCHERS:
  748. # ponytail: one guard here covers every caller (launch, sync, repair,
  749. # install); per-home outputs below stay unguarded. Upgrade to a stamped
  750. # owning store if shared checkouts ever need cross-home repins.
  751. kept = None if owner else _kept_shared_launcher(name, local, store, own)
  752. if kept is not None:
  753. written.append(str(kept))
  754. continue
  755. if (path := stage_launcher(name, root, local)) is not None:
  756. written.append(str(path))
  757. if Path(out_dir).resolve() == local:
  758. return written
  759. if len(written) != len(WINDOWS_BIN_LAUNCHERS):
  760. return []
  761. if not _is_windows():
  762. return [str(path) for path in _publish_conveniences(root, Path(out_dir), WINDOWS_BIN_LAUNCHERS)]
  763. Path(out_dir).mkdir(parents=True, exist_ok=True)
  764. return [str(path) for name in WINDOWS_BIN_LAUNCHERS
  765. if (path := stage_launcher(name, root, Path(out_dir))) is not None]
  766. def expose_cli(project_root: Path | None = None, *, create: bool = True) -> dict:
  767. """Repair PATH conveniences without taking over another installation's files.
  768. macOS CLI-first launches link the bundle's signed shims directly; Electron
  769. need not have run. Source installs converge on the store launcher owner.
  770. POSIX shell rc registration remains installer-owned. On Windows the User
  771. PATH entry is repaired only for the home new consoles use (owns_user_path).
  772. Before dependency sync succeeds, create=False maintains only commands we
  773. already own, without loading application config or enabling new exposure.
  774. """
  775. # Resolved before the platform branch: the Windows path needs it too.
  776. from pm.paths import install_root
  777. root = Path(project_root or install_root()).resolve()
  778. if _is_windows():
  779. # The installer stages the user-facing commands into $HERMES_HOME\bin
  780. # and registers that directory in the User PATH. An update skipped both
  781. # (this used to answer "windows-installer-owned"), so a machine updated
  782. # from a release predating that convention kept the old
  783. # venv\Scripts entry and never converged on it. Mirror the installer.
  784. return _expose_windows_user_bin(root, create=create)
  785. if create:
  786. try:
  787. from hermes_cli.config import load_config
  788. except ImportError:
  789. # Installers expose after sync; never invent a config reader here.
  790. return {"ok": True, "skipped": "config-unavailable"}
  791. cli_cfg = (load_config() or {}).get("cli", {})
  792. if isinstance(cli_cfg, dict) and not cli_cfg.get("expose_on_path", True):
  793. return {"ok": True, "skipped": "config-disabled"}
  794. from hermes_cli.steward import read_install_stamp
  795. if _is_bundled_payload(root):
  796. if create and sys.platform == "darwin":
  797. return _symlink_sealed_launchers(root.parent / "bin")
  798. return {"ok": True, "skipped": "bundle-owns-launchers"}
  799. if read_install_stamp(root).get("updateMechanism") == "external":
  800. return {"ok": True, "skipped": "externally-owned"}
  801. if resolve_store_python(root, publication=True) is None:
  802. return {"ok": True, "skipped": "no-store-python"}
  803. try:
  804. local = root / ".hermes" / "bin"
  805. if len(ensure_install_launchers(root, local)) != len(WINDOWS_BIN_LAUNCHERS):
  806. return {"ok": False, "error": "source launcher publication failed"}
  807. dirs = [Path.home() / ".local" / "bin"]
  808. # Repair existing FHS/custom-home exposure, but never create new global
  809. # entries or reclaim a convenience that was repointed to another root.
  810. from hermes_constants import get_default_hermes_root
  811. for directory in (get_default_hermes_root() / "bin", Path("/usr/local/bin")):
  812. if directory not in dirs and (not create or _owns_launcher(directory / "hermes", root)):
  813. dirs.append(directory)
  814. written = []
  815. for directory in dirs:
  816. published = _publish_conveniences(root, directory, (*WINDOWS_BIN_LAUNCHERS, "hermes-agent"), create=create)
  817. written.extend(path.name for path, changed in published.items() if changed)
  818. return {"ok": True, "written": written}
  819. except OSError as exc:
  820. return {"ok": False, "error": str(exc)}
  821. _TOKEN_DUPLICATE = 0x0002
  822. _TOKEN_QUERY = 0x0008
  823. def _new_console_environment() -> dict[str, str] | None:
  824. """The environment Windows gives a new process of this user, or None.
  825. CreateEnvironmentBlock builds it from the user's stored variables
  826. (HKCU\\Environment, the profile folders, the system variables) and ignores
  827. this process's environment. A sandbox that overrides HERMES_HOME or
  828. LOCALAPPDATA for its own processes does not change the result. Names are
  829. upper-cased because Windows compares them case-insensitively.
  830. """
  831. import ctypes
  832. from ctypes import wintypes
  833. kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
  834. advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)
  835. userenv = ctypes.WinDLL("userenv", use_last_error=True)
  836. kernel32.GetCurrentProcess.restype = wintypes.HANDLE
  837. kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
  838. advapi32.OpenProcessToken.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)]
  839. userenv.CreateEnvironmentBlock.argtypes = [ctypes.POINTER(ctypes.c_void_p), wintypes.HANDLE, wintypes.BOOL]
  840. userenv.DestroyEnvironmentBlock.argtypes = [ctypes.c_void_p]
  841. token = wintypes.HANDLE()
  842. if not advapi32.OpenProcessToken(kernel32.GetCurrentProcess(), _TOKEN_QUERY | _TOKEN_DUPLICATE,
  843. ctypes.byref(token)):
  844. return None
  845. block = ctypes.c_void_p()
  846. try:
  847. if not userenv.CreateEnvironmentBlock(ctypes.byref(block), token, False):
  848. return None
  849. return _read_environment_block(block.value)
  850. finally:
  851. if block.value:
  852. userenv.DestroyEnvironmentBlock(block)
  853. kernel32.CloseHandle(token)
  854. def _read_environment_block(address: int) -> dict[str, str]:
  855. """Parse a Windows environment block: NUL-terminated UTF-16 ``NAME=value`` entries, then an empty one.
  856. The cursor advances by UTF-16 code units, not Python characters: a value
  857. holding a character outside the Basic Multilingual Plane (an emoji) takes
  858. two units and one character.
  859. """
  860. import ctypes
  861. environ: dict[str, str] = {}
  862. cursor = address
  863. while entry := ctypes.wstring_at(cursor):
  864. name, _, value = entry.partition("=")
  865. if name: # "=C:=C:\..." entries carry per-drive directories, not variables
  866. environ[name.upper()] = value
  867. cursor += len(entry.encode("utf-16-le", "surrogatepass")) + ctypes.sizeof(ctypes.c_wchar)
  868. return environ
  869. def new_console_hermes_root() -> Path | None:
  870. """The Hermes root that a newly opened console resolves, or None when Windows cannot say."""
  871. from hermes_constants import hermes_root_for_environment
  872. environ = _new_console_environment()
  873. return None if environ is None else hermes_root_for_environment(environ)
  874. def owns_user_path(root: Path) -> bool:
  875. """May ``root`` put its commands on the User PATH?
  876. Every console the user opens reads the User PATH, so only the root that
  877. new consoles resolve may register there. A custom root qualifies only when
  878. HERMES_HOME is stored as a user variable. A process whose own HERMES_HOME,
  879. LOCALAPPDATA or USERPROFILE override selects a different root (a review
  880. sandbox, a test home, a suffixed data directory) gets False. So does any
  881. root when Windows cannot report the console environment.
  882. """
  883. console_root = new_console_hermes_root()
  884. if console_root is not None and (
  885. os.path.normcase(os.path.realpath(root)) == os.path.normcase(os.path.realpath(console_root))
  886. ):
  887. return True
  888. import logging
  889. logging.getLogger(__name__).info(
  890. "User PATH left unchanged: new consoles use %s, not %s",
  891. console_root or "an unknown Hermes home", root)
  892. return False
  893. def _merge_user_path(existing: str, entry: str) -> str | None:
  894. """``entry`` first, or None when the PATH already names it.
  895. Windows paths are case-insensitive and may carry a trailing separator, so
  896. compare that way rather than by exact string.
  897. """
  898. wanted = entry.rstrip("\\/")
  899. parts = [part for part in (existing or "").split(";") if part]
  900. if any(part.rstrip("\\/").casefold() == wanted.casefold() for part in parts):
  901. return None
  902. return ";".join([entry, *parts])
  903. def _register_windows_user_path(entry: Path) -> str:
  904. """Put ``entry`` on the User PATH. Returns 'present' or 'added'.
  905. Preserves the stored value type: install.ps1 writes expandable entries
  906. (``%LOCALAPPDATA%\\...``), and rewriting the value as a plain string would
  907. freeze those.
  908. """
  909. import winreg # type: ignore
  910. with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment", 0,
  911. winreg.KEY_QUERY_VALUE | winreg.KEY_SET_VALUE) as key:
  912. try:
  913. current, kind = winreg.QueryValueEx(key, "Path")
  914. except FileNotFoundError:
  915. current, kind = "", winreg.REG_EXPAND_SZ
  916. merged = _merge_user_path(str(current), str(entry))
  917. if merged is None:
  918. return "present"
  919. if kind not in (winreg.REG_SZ, winreg.REG_EXPAND_SZ):
  920. kind = winreg.REG_EXPAND_SZ
  921. winreg.SetValueEx(key, "Path", 0, kind, merged)
  922. _broadcast_environment_change()
  923. return "added"
  924. def _broadcast_environment_change() -> None:
  925. """Tell running processes the environment changed (best effort)."""
  926. import ctypes
  927. try:
  928. ctypes.windll.user32.SendMessageTimeoutW(0xFFFF, 0x1A, 0, "Environment", 0x0002, 5000, None) # type: ignore[attr-defined]
  929. except Exception:
  930. pass
  931. def _expose_windows_user_bin(root: Path, *, create: bool) -> dict:
  932. """Windows twin of expose_cli's POSIX half.
  933. Stage the user-facing commands into ``$HERMES_HOME\\bin`` and register that
  934. directory in the User PATH -- the same two things scripts/install.ps1 does --
  935. so an update converges a machine installed under the older venv\\Scripts
  936. convention instead of leaving it there forever. The registration happens
  937. only when new consoles resolve this home (``owns_user_path``).
  938. Commands there that start another checkout which still exists stay in
  939. place unless *root* is the home's own checkout: a review tree or worktree
  940. started against the home leaves the installed ``hermes`` alone.
  941. """
  942. from hermes_constants import get_default_hermes_root
  943. directory = get_default_hermes_root() / "bin"
  944. try:
  945. if not create:
  946. # Bootstrap: repair only commands we already own, enable nothing new.
  947. published = _publish_conveniences(root, directory, WINDOWS_BIN_LAUNCHERS, create=False)
  948. return {"ok": True, "written": [path.name for path, changed in published.items() if changed]}
  949. if not _is_home_checkout(root, store_root(root)) and (
  950. other := _launcher_of_another_checkout(directory, root)) is not None:
  951. return {"ok": True, "skipped": f"{other} starts another checkout"}
  952. directory.mkdir(parents=True, exist_ok=True)
  953. written = ensure_install_launchers(root, directory)
  954. if len(written) != len(WINDOWS_BIN_LAUNCHERS):
  955. return {"ok": False, "error": "source launcher publication failed"}
  956. names = [Path(path).name for path in written]
  957. if not owns_user_path(directory.parent):
  958. # New consoles resolve another home; its launchers stay in its own bin.
  959. return {"ok": True, "skipped": "User PATH belongs to the home new consoles use", "written": names}
  960. return {"ok": True, "path": _register_windows_user_path(directory), "written": names}
  961. except OSError as exc:
  962. return {"ok": False, "error": str(exc)}
  963. def _is_bundled_payload(root: Path) -> bool:
  964. """Is ``root`` a desktop bundle's agent payload? The stamp is the
  965. authority (payload marker / desktop-app distribution), never a
  966. sibling-directory sniff; a .git tree is a dev checkout regardless."""
  967. if (root / ".git").exists():
  968. return False
  969. from hermes_cli.steward import STEWARD_DESKTOP, read_install_stamp
  970. stamp = read_install_stamp(root)
  971. if not stamp:
  972. return False
  973. return bool(stamp.get("payload")) or stamp.get("distribution") == STEWARD_DESKTOP
  974. def _symlink_sealed_launchers(payload_bin) -> dict:
  975. """Link ~/.local/bin/{hermes,hermes-agent,hermes-acp} at a sealed
  976. bundle's own prebuilt shims (macOS only).
  977. Symlinks, not copies: the shims are signed as part of the app bundle,
  978. and a copy would both orphan the signature's context and go stale on
  979. every app update — a symlink into the .app follows the bundle's
  980. content wherever Squirrel.Mac swaps it.
  981. Ownership guard mirrors expose_cli's wrapper logic: an existing
  982. entry is replaced only when it is ours — a symlink into THIS app
  983. bundle's payload — or missing/broken. A user's own `hermes` (pipx,
  984. another checkout's wrapper) is never touched.
  985. """
  986. link_dir = Path.home() / ".local" / "bin"
  987. payload_root = payload_bin.parent
  988. written: list[str] = []
  989. try:
  990. link_dir.mkdir(parents=True, exist_ok=True)
  991. for name in ("hermes", "hermes-agent", "hermes-acp"):
  992. source = payload_bin / name
  993. if not source.is_file():
  994. continue
  995. target = link_dir / name
  996. if target.is_symlink():
  997. current = os.readlink(target)
  998. if current == str(source):
  999. continue # already ours and current
  1000. # Ours if it points into this payload (stale app path from
  1001. # a previous version counts — resolve() of a dangling link
  1002. # still yields the old path text) — or dangling entirely.
  1003. points_into_payload = str(Path(current)).startswith(str(payload_root) + os.sep)
  1004. if not points_into_payload and target.exists():
  1005. continue # a live foreign link — user's arrangement
  1006. elif target.exists():
  1007. continue # a real file we did not write — never clobber
  1008. target.unlink(missing_ok=True)
  1009. target.symlink_to(source)
  1010. written.append(name)
  1011. except OSError as exc:
  1012. return {"ok": False, "error": str(exc)}
  1013. return {"ok": True, "written": written, "mode": "sealed-symlinks"}
  1014. if __name__ == "__main__":
  1015. import argparse
  1016. if sys.argv[1:2] == ["--print-runtime-command"]:
  1017. print_runtime_command(Path(__file__).resolve().parents[1], sys.argv[2:])
  1018. raise SystemExit(0)
  1019. parser = argparse.ArgumentParser(description="Publish source-install launchers.")
  1020. parser.add_argument("out_dir", type=Path)
  1021. args = parser.parse_args()
  1022. repo_root = Path(__file__).resolve().parents[1]
  1023. if resolve_store_python(repo_root, publication=True) is None:
  1024. parser.exit(1, "hermes: store interpreter is missing; finish pm install before publishing launchers\n")
  1025. args.out_dir.mkdir(parents=True, exist_ok=True)
  1026. written = ensure_install_launchers(repo_root, args.out_dir)
  1027. if len(written) != len(ENTRY_POINTS):
  1028. parser.exit(1, "hermes: launcher publication failed\n")
  1029. print("\n".join(written))