The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli): foreign_sessions _block_text/_message_turn fold, heartbeat/dingtalk/gitlock/install_identity compaction
Tekniumd4904b8327ca
diff --git a/hermes_cli/dingtalk_auth.py b/hermes_cli/dingtalk_auth.pyindex 96e89e0adf2..0c9cd1f9e3b 100644--- a/hermes_cli/dingtalk_auth.py+++ b/hermes_cli/dingtalk_auth.py@@ -2,6 +2,7 @@from __future__ import annotations+import contextlibimport osimport sysimport time@@ -36,8 +37,7 @@ def _api_post(path: str, payload: dict) -> dict:def begin_registration() -> dict:"""Start a device-flow registration: init → nonce, begin → device_code + verification URL."""- init_data = _api_post("/app/registration/init", {"source": REGISTRATION_SOURCE})- nonce = str(init_data.get("nonce", "")).strip()+ nonce = str(_api_post("/app/registration/init", {"source": REGISTRATION_SOURCE}).get("nonce", "")).strip()if not nonce:raise RegistrationError("init response missing nonce")begin_data = _api_post("/app/registration/begin", {"nonce": nonce})@@ -74,8 +74,8 @@ def wait_for_registration_success(nonlocal retry_startif retry_start == 0:retry_start = time.monotonic()-return time.monotonic() - retry_start < _RETRY_WINDOW+while time.monotonic() < deadline:time.sleep(interval)try:@@ -89,33 +89,27 @@ def wait_for_registration_success(retry_start = 0if on_waiting:on_waiting()- continue- if status == "SUCCESS":+ elif status == "SUCCESS":cid, csecret = result["client_id"], result["client_secret"]if not cid or not csecret:raise RegistrationError("authorization succeeded but credentials are missing")return cid, csecret- if _within_retry_window():- continue- raise RegistrationError(f"authorization failed: {result.get('fail_reason') or status}")+ elif not _within_retry_window():+ raise RegistrationError(f"authorization failed: {result.get('fail_reason') or status}")raise RegistrationError("authorization timed out, please retry")def _ensure_qrcode_installed() -> bool:"""Try to import qrcode; if missing, auto-install it via pip/uv."""- try:+ with contextlib.suppress(ImportError):import qrcode # noqa: F401return True- except ImportError:- passimport subprocessfrom hermes_cli.tools_config import _pip_install- try:+ with contextlib.suppress(subprocess.SubprocessError, ImportError, OSError):if _pip_install(["-q", "qrcode"], timeout=120).returncode == 0:import qrcode # noqa: F401,F811return True- except (subprocess.SubprocessError, ImportError, OSError):- passreturn False@@ -169,8 +163,8 @@ def dingtalk_qr_auth() -> Optional[Tuple[str, str]]:dot_count += 1if dot_count % 10 == 0:sys.stdout.write(".")-sys.stdout.flush()+try:client_id, client_secret = wait_for_registration_success(device_code=reg["device_code"], interval=reg["interval"], expires_in=reg["expires_in"],diff --git a/hermes_cli/foreign_sessions.py b/hermes_cli/foreign_sessions.pyindex c87c61489f9..696650417ea 100644--- a/hermes_cli/foreign_sessions.py+++ b/hermes_cli/foreign_sessions.py@@ -18,9 +18,7 @@ from typing import Any, Dict, List, Optional, Tuple_WRAPPER_TAG_RE = re.compile(r"^<(?:user_instructions|environment_context|recommended_plugins|"r"skills_instructions|permissions[_-]instructions|turn_context|"- r"command-name|command-message|local-command-stdout|system-reminder)\b",- re.IGNORECASE,-)+ r"command-name|command-message|local-command-stdout|system-reminder)\b", re.IGNORECASE)_TITLE_MAX = 60_SOURCE_LABELS = {"claude": "Claude Code", "codex": "Codex CLI"}@@ -41,24 +39,34 @@ class ForeignSession:@propertydef label(self) -> str:- name = _SOURCE_LABELS.get(self.source, self.source)title = (self.title_guess or "").strip() or self.path.stem- return f"[{name}] {title[:_TITLE_MAX]}"+ return f"[{_SOURCE_LABELS.get(self.source, self.source)}] {title[:_TITLE_MAX]}"def _read_json_lines(path: Path):"""Yield parsed JSON objects, silently skipping unparseable lines."""- try:- with open(path, "r", encoding="utf-8", errors="replace") as f:- for line in f:- try:- obj = json.loads(line) if line.strip() else None- except ValueError:- continue- if isinstance(obj, dict):- yield obj- except OSError:- return+ with contextlib.suppress(OSError), open(path, "r", encoding="utf-8", errors="replace") as f:+ for line in f:+ try:+ obj = json.loads(line)+ except ValueError:+ continue+ if isinstance(obj, dict):+ yield obj+++def _block_text(block: Any) -> str:+ """Plain text of one content block; tool_result, thinking/reasoning and unknown types yield ''."""+ if isinstance(block, str):+ return block+ if not isinstance(block, dict):+ return ""+ btype = block.get("type")+ if btype in ("text", "input_text", "output_text"):+ return text if isinstance(text := block.get("text"), str) else ""+ if btype == "tool_use": # Claude Code assistant block+ return f"[ran tool: {block.get('name') or 'tool'}]"+ return "[image]" if btype == "image" else ""def _flatten_blocks(content: Any) -> str:@@ -67,22 +75,7 @@ def _flatten_blocks(content: Any) -> str:return contentif not isinstance(content, list):return ""- parts: List[str] = []- for block in content:- if isinstance(block, str):- parts.append(block)- elif not isinstance(block, dict):- continue- # tool_result (tool output echoed into a user message), thinking/reasoning and unknown- # block types are skipped.- elif (btype := block.get("type")) in ("text", "input_text", "output_text"):- if isinstance(text := block.get("text"), str) and text:- parts.append(text)- elif btype == "tool_use": # Claude Code assistant block- parts.append(f"[ran tool: {block.get('name') or 'tool'}]")- elif btype == "image":- parts.append("[image]")- return "\n\n".join(p for p in (s.strip() for s in parts) if p)+ return "\n\n".join(p for p in (_block_text(b).strip() for b in content) if p)def _merge_turns(raw_turns: List[Tuple[str, str]]) -> List[Dict[str, str]]:@@ -104,11 +97,12 @@ def _merge_turns(raw_turns: List[Tuple[str, str]]) -> List[Dict[str, str]]:return merged-def _message_turn(role: Any, content: Any) -> Optional[Tuple[str, str]]:- """Normalize one message into a ``(role, text)`` turn, or None when it is not importable."""+def _message_turn(message: Any) -> Optional[Tuple[str, str]]:+ """Normalize one message dict into a ``(role, text)`` turn, or None when it is not importable."""+ role = message.get("role") if isinstance(message, dict) else Noneif role not in ("user", "assistant"):return None- text = _flatten_blocks(content)+ text = _flatten_blocks(message.get("content"))return None if not text or (role == "user" and _WRAPPER_TAG_RE.match(text.lstrip())) else (role, text)@@ -132,19 +126,15 @@ def parse_claude_session(path: Path) -> Dict[str, Any]:for obj in _read_json_lines(path):otype = obj.get("type")if otype == "summary":- s = obj.get("summary")- if isinstance(s, str) and s.strip():+ if isinstance(s := obj.get("summary"), str) and s.strip():summary = s.strip()- continue- if otype not in ("user", "assistant") or obj.get("isSidechain") or obj.get("isMeta"):- continue- if cwd is None and isinstance(obj.get("cwd"), str):- cwd = obj["cwd"]- if session_id is None and isinstance(obj.get("sessionId"), str):- session_id = obj["sessionId"]- message = obj.get("message")- if isinstance(message, dict) and (turn := _message_turn(message.get("role"), message.get("content"))):- turns.append(turn)+ elif otype in ("user", "assistant") and not (obj.get("isSidechain") or obj.get("isMeta")):+ if cwd is None and isinstance(obj.get("cwd"), str):+ cwd = obj["cwd"]+ if session_id is None and isinstance(obj.get("sessionId"), str):+ session_id = obj["sessionId"]+ if turn := _message_turn(obj.get("message")):+ turns.append(turn)return _parsed(turns, cwd, session_id, summary)@@ -153,27 +143,22 @@ def parse_codex_session(path: Path) -> Dict[str, Any]:turns: List[Tuple[str, str]] = []cwd = session_id = Nonefor obj in _read_json_lines(path):- otype = obj.get("type")- payload = obj.get("payload")+ otype, payload = obj.get("type"), obj.get("payload")if not isinstance(payload, dict):continueif otype == "session_meta":if isinstance(payload.get("cwd"), str):cwd = payload["cwd"]- sid = payload.get("session_id") or payload.get("id")- if isinstance(sid, str):+ if isinstance(sid := payload.get("session_id") or payload.get("id"), str):session_id = sid- continue- if otype != "response_item":- continue- ptype = payload.get("type")- if ptype == "message": # developer/system payloads never imported- if turn := _message_turn(payload.get("role"), payload.get("content")):+ elif otype == "response_item":+ ptype = payload.get("type")+ if ptype == "message" and (turn := _message_turn(payload)): # developer/system payloads skippedturns.append(turn)- elif ptype in ("custom_tool_call", "function_call", "local_shell_call"):- # Assistant activity; merged into neighbours later. Tool outputs / reasoning skipped.- name = payload.get("name") or payload.get("tool") or "tool"- turns.append(("assistant", f"[ran tool: {name}]"))+ elif ptype in ("custom_tool_call", "function_call", "local_shell_call"):+ # Assistant activity; merged into neighbours later. Tool outputs / reasoning skipped.+ name = payload.get("name") or payload.get("tool") or "tool"+ turns.append(("assistant", f"[ran tool: {name}]"))return _parsed(turns, cwd, session_id)@@ -204,8 +189,7 @@ def _list_sessions(source: str, root: Optional[Path]) -> List[ForeignSession]:def import_foreign_session(source: str, path, db=None) -> str:"""Import one foreign session into the Hermes SessionDB; returns the new Hermes session id.- Raises ``ValueError`` on unknown source or a session with no usable conversation turns.- """+ Raises ``ValueError`` on unknown source or a session with no usable conversation turns."""source = (source or "").strip().lower().lstrip("@")if source not in _SOURCE_LABELS:raise ValueError(f"Unknown foreign session source: {source!r}")@@ -239,10 +223,8 @@ def import_foreign_session(source: str, path, db=None) -> str:db.close()-def gather_foreign_sessions(- source: Optional[str] = None, *, claude_root: Optional[Path] = None, codex_root: Optional[Path] = None,- limit: int = 25,-) -> List[ForeignSession]:+def gather_foreign_sessions(source: Optional[str] = None, *, claude_root: Optional[Path] = None,+ codex_root: Optional[Path] = None, limit: int = 25) -> List[ForeignSession]:"""List foreign sessions across sources, newest first."""sessions = [s for name, root in (("claude", claude_root), ("codex", codex_root)) if source in (None, name)for s in _list_sessions(name, root)]@@ -273,11 +255,10 @@ def pick_foreign_session(source: Optional[str] = None, *, limit: int = 25) -> Opexcept ValueError:print(f"Not a number: {raw}")return None- if idx is None:- return None- if 1 <= idx <= len(sessions):+ if idx is not None and 1 <= idx <= len(sessions):return sessions[idx - 1]- print(f"Out of range: {idx}")+ if idx is not None:+ print(f"Out of range: {idx}")return None@@ -301,8 +282,7 @@ def run_sessions_import(args, db=None) -> Optional[str]:return Nonechosen_path = Path(path)else:- picked = pick_foreign_session(source)- if picked is None:+ if (picked := pick_foreign_session(source)) is None:return Nonesource, chosen_path = picked.source, picked.pathtry:@@ -310,7 +290,6 @@ def run_sessions_import(args, db=None) -> Optional[str]:except ValueError as e:print(f"Error: {e}")return None- label = _SOURCE_LABELS.get(source, source)- print(f"✓ Imported {label} session as {session_id}")+ print(f"✓ Imported {_SOURCE_LABELS.get(source, source)} session as {session_id}")print(f" Continue it with: hermes --resume {session_id}")return session_iddiff --git a/hermes_cli/gitlock.py b/hermes_cli/gitlock.pyindex 9108ea94cbe..7ad7ff0834b 100644--- a/hermes_cli/gitlock.py+++ b/hermes_cli/gitlock.py@@ -1,8 +1,7 @@"""Stale git lock-file and aborted-fetch pack-debris recovery for update/check paths.A killed ``git fetch`` can leave ``.git/shallow.lock`` behind (every later fetch fails with "Unable to-create '.../shallow.lock': File exists") and ``tmp_pack_*`` files git itself never cleans up.-"""+create '.../shallow.lock': File exists") and ``tmp_pack_*`` files git itself never cleans up."""from __future__ import annotations@@ -28,28 +27,24 @@ _TMP_PACK_PREFIXES = ("tmp_pack_", "tmp_idx_", "tmp_rev_", "tmp_mtimes_")def _git_proc_running() -> bool:- """True when a ``git`` process is currently running.+ """True when a ``git`` process is running — the check that stops us yanking a lock a live fetch holds.- This is the safety check that stops us from yanking a lock a real fetch is holding. A failed- probe logs and returns False; the age floor in the sweep still applies.+ A failed probe logs and returns False; the age floor in the sweep still applies."""try:if os.name == "nt":- out = subprocess.run(- ["tasklist", "/FI", "IMAGENAME eq git.exe", "/FO", "CSV"],- capture_output=True, text=True, timeout=10,- ).stdout.lower()- return "git.exe" in out- return subprocess.run(["pgrep", "-x", "git"], capture_output=True, text=True, timeout=10).returncode == 0+ proc = subprocess.run(["tasklist", "/FI", "IMAGENAME eq git.exe", "/FO", "CSV"],+ capture_output=True, text=True, timeout=10)+ return "git.exe" in proc.stdout.lower()+ proc = subprocess.run(["pgrep", "-x", "git"], capture_output=True, text=True, timeout=10)+ return proc.returncode == 0except Exception:logger.debug("git process probe failed; assuming no git running", exc_info=True)return False-def _sweep_stale(- directory: Path, candidates: Callable[[], Iterable[Path]], *, min_age_seconds: Optional[int], default_age: int,- skip_msg: str, log_removed: Callable[[Path, int], None],-) -> List[str]:+def _sweep_stale(directory: Path, candidates: Callable[[], Iterable[Path]], *, min_age_seconds: Optional[int],+ default_age: int, skip_msg: str, log_removed: Callable[[Path, int], None]) -> List[str]:"""Shared guard + age-floor sweep. Never raises; skips anything it cannot stat/unlink."""if not directory.is_dir():return []@@ -60,12 +55,10 @@ def _sweep_stale(removed: List[str] = []for entry in candidates():try:- if entry.is_file():- st = entry.stat()- if st.st_mtime < cutoff:- entry.unlink()- removed.append(str(entry))- log_removed(entry, st.st_size)+ if entry.is_file() and (st := entry.stat()).st_mtime < cutoff:+ entry.unlink()+ removed.append(str(entry))+ log_removed(entry, st.st_size)except OSError:logger.debug("Could not clear %s (skipping)", entry, exc_info=True)return removed@@ -74,9 +67,8 @@ def _sweep_stale(def clear_stale_git_locks(repo_root: Path, *, min_age_seconds: Optional[int] = None) -> List[str]:"""Remove abandoned ``.git`` lock files under ``repo_root``; returns the removed paths.- A lock is removed only when it is older than the age floor AND no git process is running. Never- raises: a lock we cannot stat or unlink is skipped (a concurrently-held lock may have been- created between the age check and the unlink; skipping is always safe).+ Removes only when older than the age floor AND no git process is running. Never raises: a lock we cannot+ stat/unlink is skipped (it may have been re-created between the age check and the unlink; skipping is safe)."""git_dir = Path(repo_root) / ".git"return _sweep_stale(@@ -88,18 +80,15 @@ def clear_stale_git_locks(repo_root: Path, *, min_age_seconds: Optional[int] = Ndef clear_stale_tmp_packs(repo_root: Path, *, min_age_seconds: Optional[int] = None) -> List[str]:- """Remove aborted-fetch temp pack files under ``.git/objects/pack``.-- Same safety contract as :func:`clear_stale_git_locks`. Returns the removed paths.- """+ """Remove aborted-fetch temp pack files under ``.git/objects/pack``; same contract as clear_stale_git_locks."""pack_dir = Path(repo_root) / ".git" / "objects" / "pack"def _candidates():try:return [e for e in pack_dir.iterdir() if e.name.startswith(_TMP_PACK_PREFIXES)]except OSError:-return []+return _sweep_stale(pack_dir, _candidates,min_age_seconds=min_age_seconds, default_age=STALE_TMP_PACK_MIN_AGE_SECONDS,diff --git a/hermes_cli/heartbeat.py b/hermes_cli/heartbeat.pyindex 4c0f57e176c..a2aa3eb4572 100644--- a/hermes_cli/heartbeat.py+++ b/hermes_cli/heartbeat.py@@ -1,10 +1,9 @@"""Session heartbeats — recurring re-entry prompts for the current session.-Deliberately session-scoped and in-process (CLI or gateway must be running); durable cross-process-scheduling remains ``hermes cron``. Invariants (mirrors goals.py): injection is a plain user message —-no system-prompt mutation or toolset swap, so prompt caching stays intact — and a real user message-always wins: heartbeats only fire into an idle session with an empty input queue.-"""+Session-scoped and in-process (CLI or gateway must be running); durable cross-process scheduling stays+``hermes cron``. Invariants (mirrors goals.py): injection is a plain user message — no system-prompt+mutation or toolset swap, so prompt caching stays intact — and a real user message always wins:+heartbeats only fire into an idle session with an empty input queue."""from __future__ import annotations@@ -21,16 +20,13 @@ MIN_INTERVAL_SECONDS = 60 # floor: re-entering more often than once a minute isPOLL_SECONDS = 5.0 # how often drivers poll for due heartbeats; not user-facingHEARTBEAT_PROMPT_TEMPLATE = (- "[Heartbeat — recurring instruction, fires every {interval}]\n"- "{prompt}\n\n"+ "[Heartbeat — recurring instruction, fires every {interval}]\n{prompt}\n\n""If there is nothing meaningful to do or report for this instruction "- "right now, reply briefly that nothing has changed and stop — do not "- "invent work."+ "right now, reply briefly that nothing has changed and stop — do not invent work.")_INTERVAL_RE = re.compile(- r"^\s*(?:every\s+)?(\d+(?:\.\d+)?)\s*(s|sec|secs|seconds?|m|min|mins|minutes?|h|hr|hrs|hours?|d|days?)\s*$", re.IGNORECASE-)+ r"^\s*(?:every\s+)?(\d+(?:\.\d+)?)\s*(s|sec|secs|seconds?|m|min|mins|minutes?|h|hr|hrs|hours?|d|days?)\s*$", re.IGNORECASE)_UNIT_SECONDS = {**dict.fromkeys(("s", "sec", "secs", "second", "seconds"), 1),@@ -49,8 +45,7 @@ _STATE_FIELDS = {def parse_interval(text: str) -> Optional[int]:"""Parse ``10m`` / ``every 2h`` / ``every 90 minutes`` into seconds.- None when the text is not an interval; values below ``MIN_INTERVAL_SECONDS`` return -1 so- callers can distinguish "not an interval" from "too small".+ None when not an interval; below ``MIN_INTERVAL_SECONDS`` returns -1 so callers can tell "too small" apart."""m = _INTERVAL_RE.match(text) if text else Noneif not m:@@ -88,7 +83,7 @@ class HeartbeatState:def is_due(self, now: Optional[float] = None) -> bool:if self.status != "active" or not self.prompt or self.interval_seconds <= 0:return False- return ((time.time() if now is None else now) - (self.last_fired_at or self.created_at)) >= self.interval_seconds+ return (time.time() if now is None else now) - (self.last_fired_at or self.created_at) >= self.interval_secondsdef render_prompt(self) -> str:return HEARTBEAT_PROMPT_TEMPLATE.format(interval=format_interval(self.interval_seconds), prompt=self.prompt)@@ -113,14 +108,12 @@ def load_heartbeat(session_id: str) -> Optional[HeartbeatState]:except Exception as exc:logger.debug("HeartbeatManager: get_meta failed: %s", exc)return None- if not raw:- return Nonetry:- state = HeartbeatState.from_json(raw)+ state = HeartbeatState.from_json(raw) if raw else Noneexcept Exception as exc:logger.warning("HeartbeatManager: could not parse stored heartbeat for %s: %s", session_id, exc)return None- return None if state.status == "cleared" else state+ return None if state is None or state.status == "cleared" else statedef save_heartbeat(session_id: str, state: HeartbeatState) -> None:@@ -140,9 +133,8 @@ def save_heartbeat(session_id: str, state: HeartbeatState) -> None:class HeartbeatManager:"""Per-session heartbeat state + due-tick decisions; the surface CLI + gateway talk to.- Drivers (CLI thread / gateway task) call :meth:`due_prompt` on a poll cadence while the session- is idle; a non-None return is the user-role message to inject. Firing is recorded immediately so- a slow turn can't double-fire.+ Drivers (CLI thread / gateway task) call :meth:`due_prompt` on a poll cadence while the session is+ idle; a non-None return is the user-role message to inject."""def __init__(self, session_id: str):@@ -178,10 +170,10 @@ class HeartbeatManager:interval_seconds = int(interval_seconds)if interval_seconds < MIN_INTERVAL_SECONDS:raise ValueError(f"interval must be at least {MIN_INTERVAL_SECONDS}s")- state = HeartbeatState(prompt=prompt, interval_seconds=interval_seconds, status="active", created_at=time.time())- self._state = state- save_heartbeat(self.session_id, state)- return state+ self._state = HeartbeatState(prompt=prompt, interval_seconds=interval_seconds, status="active",+ created_at=time.time())+ save_heartbeat(self.session_id, self._state)+ return self._statedef _set_status(self, status: str, *, reanchor: bool = False) -> Optional[HeartbeatState]:if not self._state:@@ -200,17 +192,16 @@ class HeartbeatManager:return self._set_status("active", reanchor=True)def clear(self) -> bool:- if self._set_status("cleared") is None:- return False+ cleared = self._set_status("cleared") is not Noneself._state = None- return True+ return cleareddef due_prompt(self, now: Optional[float] = None) -> Optional[str]:"""Return the injection prompt if the heartbeat is due, else None.- Records the fire immediately (before the turn runs) so overlapping polls or a long turn can- never double-fire the same tick. Missed ticks coalesce into one — the anchor resets to NOW,- not to the theoretical schedule.+ The fire is recorded immediately (before the turn runs) so overlapping polls or a long turn can never+ double-fire the same tick. Missed ticks coalesce: the anchor resets to NOW, not the theoretical+ schedule."""s = self._stateif s is None or not s.is_due(now):@@ -222,10 +213,9 @@ class HeartbeatManager:def migrate_heartbeat_to_session(old_session_id: str, new_session_id: str) -> bool:- """Carry a heartbeat across a compression session rotation.+ """Carry a heartbeat across a compression session rotation (copy to child, archive parent, never raise).- Same shape as ``goals.migrate_goal_to_session`` — copy to the child, archive the parent row,- never raise.+ Same shape as ``goals.migrate_goal_to_session``."""if not old_session_id or not new_session_id or old_session_id == new_session_id:return Falsediff --git a/hermes_cli/install_identity.py b/hermes_cli/install_identity.pyindex 8b8a07d0e81..32669039ab3 100644--- a/hermes_cli/install_identity.py+++ b/hermes_cli/install_identity.py@@ -39,11 +39,9 @@ def _install_id_file_lock(root: Path):finally:try:if windows:- import msvcrtos.lseek(fd, 0, os.SEEK_SET)msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)else:- import fcntlfcntl.flock(fd, fcntl.LOCK_UN)finally:os.close(fd)@@ -79,8 +77,7 @@ def _read_existing(path: Path) -> tuple[Optional[str], bool]:def read_or_create_install_id(root: Path | None = None) -> Optional[str]:"""Read or atomically mint the opaque id for the physical install.- ``None`` means the id could neither be read nor persisted. Returning an ephemeral id would- violate the authority and connection-registry contract.+ ``None`` = neither readable nor persistable; an ephemeral id would violate the authority/registry contract."""root = get_default_hermes_root() if root is None else rootpath = root / _INSTALL_ID_FILENAME@@ -89,21 +86,16 @@ def read_or_create_install_id(root: Path | None = None) -> Optional[str]:return existingtry:root.mkdir(parents=True, exist_ok=True)- except OSError:- return None- try:- # Windows byte-range locks can report a same-process lock conflict instead of waiting for- # another thread. Serialize threads here, then retain the file lock as the cross-process- # publication fence.+ # Windows byte-range locks can report a same-process conflict instead of waiting for another+ # thread: serialize threads here, then keep the file lock as the cross-process publication fence.with _INSTALL_ID_PUBLICATION_LOCK, _install_id_file_lock(root):existing, mint = _read_existing(path)if not mint:return existing- minted = uuid.uuid4().hexfd, tmp_name = tempfile.mkstemp(dir=str(root), prefix=".install_id-")try:with os.fdopen(fd, "w", encoding="utf-8") as handle:- handle.write(minted + "\n")+ handle.write(uuid.uuid4().hex + "\n")handle.flush()os.fsync(handle.fileno())os.replace(tmp_name, path)@@ -126,8 +118,8 @@ def get_install_id(*, cache: dict[str, Optional[str]] | None = None) -> Optionaldef _cached() -> Optional[str]:cached = target_cache.get("value")-return cached if cached and target_cache.get("root") in (None, root_key) else None+if value := _cached():return valuewith _INSTALL_ID_LOCK: