web_server_profiles.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. """Profile-scoped helpers: profile discovery fallback, profile dir/MCP-server writes,
  2. the profile/config scope context managers, skills-hub and tools/analytics catalog helpers.
  3. """
  4. import logging
  5. import hashlib
  6. import os
  7. import re
  8. import sys
  9. import threading
  10. from contextlib import contextmanager, nullcontext
  11. from fastapi import HTTPException
  12. from pathlib import Path
  13. from typing import Any, Callable, Dict, List, Optional
  14. from hermes_cli.config import DEFAULT_CONFIG, get_process_hermes_home
  15. from hermes_cli.web_models import MCPServerCreate
  16. from hermes_cli.web_server_gateway import _ACTION_LOG_FILES
  17. from hermes_cli.web_server_mcp import _normalize_mcp_server_create
  18. # Same logger the code used before extraction (record parity).
  19. _log = logging.getLogger("hermes_cli.web_server")
  20. def _safe(callable_: Callable[[], Any], default: Any) -> Any:
  21. try:
  22. return callable_()
  23. except Exception:
  24. return default
  25. def _is_current_profile(profile: Optional[str]) -> bool:
  26. """None/""/"current" all mean the dashboard's own profile."""
  27. requested = (profile or "").strip()
  28. return not requested or requested.lower() == "current"
  29. @contextmanager
  30. def _hermes_home_scope(path) -> Any:
  31. """Scope ``load_config``/``save_config`` (anything resolving ``get_hermes_home()`` at call
  32. time) to ``path`` for the block via the context-local HERMES_HOME override."""
  33. from hermes_constants import set_hermes_home_override, reset_hermes_home_override
  34. token = set_hermes_home_override(str(path))
  35. try:
  36. yield
  37. finally:
  38. reset_hermes_home_override(token)
  39. def serving_profile_name() -> str:
  40. """This process's OWN profile name — but only when that name provably resolves back
  41. to the process home.
  42. The dashboard SPA needs an explicit scope for requests it fires before the profile
  43. switcher has resolved: a destructive route now 400s on an unnamed profile as soon as
  44. the host serves more than one, and "" would otherwise mean "whichever home this
  45. process launched with" anyway. Naming it is only safe if the name cannot resolve
  46. ELSEWHERE, so a custom HERMES_HOME outside ``profiles/`` (``get_active_profile_name()``
  47. answers ``"custom"``) returns "" and keeps the old unnamed behaviour rather than
  48. risking a wrong-profile write.
  49. """
  50. from hermes_cli import profiles as profiles_mod
  51. try:
  52. name = (profiles_mod.get_active_profile_name() or "").strip()
  53. if not name or name == "custom":
  54. return ""
  55. return name if profiles_mod.profile_matches_home(name, get_process_hermes_home()) else ""
  56. except Exception:
  57. return ""
  58. def _is_other_profile(profile: Optional[str]) -> bool:
  59. """True when ``profile`` names a profile other than this process's own."""
  60. if _is_current_profile(profile):
  61. return False
  62. try:
  63. target = _resolve_profile_dir(profile.strip())
  64. except HTTPException:
  65. return True
  66. return target.resolve() != get_process_hermes_home().resolve()
  67. def _approval_mode_of(config: dict[str, Any]) -> str:
  68. """Normalize approvals.mode from an in-memory config document. Both sides of the
  69. broadcast comparison use in-memory documents: re-reading through the config cache after
  70. a save can serve the pre-save document when the replacement file collides on the
  71. (mtime_ns, size) cache key, suppressing the broadcast exactly when the mode changed."""
  72. from tools.approval_context import _normalize_approval_mode
  73. approvals = config.get("approvals")
  74. default_mode = (DEFAULT_CONFIG.get("approvals") or {}).get("mode", "manual")
  75. mode = approvals.get("mode", default_mode) if isinstance(approvals, dict) else default_mode
  76. return _normalize_approval_mode(mode)
  77. def _broadcast_gateway_session_info() -> None:
  78. """Broadcast session.info on the in-process gateway when it's loaded (``sys.modules``
  79. guard, not an import: gateway never imported means no live sessions to notify)."""
  80. server = sys.modules.get("tui_gateway.server")
  81. if server is None:
  82. return
  83. try:
  84. server.broadcast_session_info()
  85. except Exception:
  86. _log.exception("session.info broadcast after config save failed")
  87. _MODEL_ENTRY_METADATA = ("canonical_model", "reasoning_effort")
  88. def _parse_model_entries(resp: Any) -> list[dict[str, str]]:
  89. """Model rows from an OpenAI-compatible ``/v1/models`` response as ``{"id": ..}`` dicts,
  90. keeping the alias metadata a gateway may advertise (``canonical_model``,
  91. ``reasoning_effort``). Flattening to bare ids lost that, so Desktop stored a reasoning
  92. alias as the literal upstream model (#93622). Accepts ``{"data": [{"id": ..}]}`` or a
  93. bare ``{"data": ["id", ..]}``; ``[]`` on any parse/HTTP error so a slightly
  94. non-standard endpoint never hard-blocks."""
  95. try:
  96. if not resp.is_success:
  97. return []
  98. payload = resp.json()
  99. except Exception:
  100. return []
  101. data = payload.get("data") if isinstance(payload, dict) else payload
  102. if not isinstance(data, list):
  103. return []
  104. entries: list[dict[str, str]] = []
  105. for item in data:
  106. model_id = str((item.get("id") if isinstance(item, dict) else item) or "").strip()
  107. if not model_id:
  108. continue
  109. entry = {"id": model_id}
  110. if isinstance(item, dict):
  111. for key in _MODEL_ENTRY_METADATA:
  112. value = str(item.get(key) or "").strip()
  113. if value:
  114. entry[key] = value
  115. entries.append(entry)
  116. return entries
  117. def _parse_model_ids(resp: Any) -> list[str]:
  118. """Bare model ids from a ``/v1/models`` response (see :func:`_parse_model_entries`)."""
  119. return [entry["id"] for entry in _parse_model_entries(resp)]
  120. def _fallback_profile_entry(profiles_mod, name: str, home: Path, *, is_default: bool,
  121. has_env: bool, gateway_running: Callable[[], bool]) -> dict[str, Any]:
  122. model, provider = _safe(lambda: profiles_mod._read_config_model(home), (None, None))
  123. meta = lambda key, default: _safe(
  124. lambda: profiles_mod.read_profile_meta(home).get(key, default), default)
  125. return {
  126. "name": name, "path": str(home), "is_default": is_default, "model": model,
  127. "provider": provider, "has_env": has_env,
  128. "skill_count": _safe(lambda: profiles_mod._cached_skill_count(home), 0),
  129. "gateway_running": _safe(gateway_running, False),
  130. "description": meta("description", ""), "description_auto": meta("description_auto", False),
  131. "bot_title": meta("bot_title", ""),
  132. "distribution_name": None, "distribution_version": None, "distribution_source": None,
  133. "has_alias": False}
  134. def _fallback_profile_dicts(profiles_mod) -> list[dict[str, Any]]:
  135. profiles: list[dict[str, Any]] = []
  136. default_home = profiles_mod._get_default_hermes_home()
  137. if default_home.is_dir():
  138. profiles.append(_fallback_profile_entry(
  139. profiles_mod, "default", default_home, is_default=True,
  140. has_env=(default_home / ".env").exists(),
  141. gateway_running=lambda: profiles_mod._check_gateway_running(default_home)))
  142. profiles_root = profiles_mod._get_profiles_root()
  143. if profiles_root.is_dir():
  144. # os.scandir (context-managed) rather than Path.iterdir: an exception mid-iteration
  145. # must not leak the directory fd — the sidebar polls every few seconds, so a leak
  146. # exhausts RLIMIT_NOFILE within days.
  147. with os.scandir(profiles_root) as scan:
  148. entries = sorted(scan, key=lambda e: e.name)
  149. for entry in entries:
  150. home = Path(entry.path)
  151. if not entry.is_dir() or not profiles_mod._PROFILE_ID_RE.match(entry.name):
  152. continue
  153. profiles.append(_fallback_profile_entry(
  154. profiles_mod, entry.name, home, is_default=False,
  155. has_env=_safe(lambda: (home / ".env").exists(), False),
  156. gateway_running=lambda home=home, name=entry.name: (
  157. profiles_mod._check_gateway_running(home)
  158. or profiles_mod._served_by_running_multiplexer(name))))
  159. return profiles
  160. def _resolve_profile_dir(name: str) -> Path:
  161. """Validate ``name`` and resolve to its directory or raise an HTTPException."""
  162. from hermes_cli import profiles as profiles_mod
  163. try:
  164. profiles_mod.validate_profile_name(name)
  165. except ValueError as e:
  166. raise HTTPException(status_code=400, detail=str(e))
  167. if not profiles_mod.profile_exists(name):
  168. raise HTTPException(status_code=404, detail=f"Profile '{name}' does not exist.")
  169. return profiles_mod.get_profile_dir(name)
  170. def _write_profile_mcp_servers(profile_dir: Path, servers: list[MCPServerCreate]) -> int:
  171. """Write MCP server entries into ``profile_dir``'s config.yaml (HERMES_HOME-scoped).
  172. Mirrors the per-server shape ``POST /api/mcp/servers`` builds, batched so the whole
  173. profile-create write is one config save. Returns the number of servers written.
  174. """
  175. from hermes_cli.config import load_config, save_config
  176. from hermes_cli.mcp_config import _save_bearer_auth_token
  177. written = 0
  178. with _hermes_home_scope(profile_dir):
  179. cfg = load_config()
  180. mcp = cfg.setdefault("mcp_servers", {})
  181. for server in servers:
  182. try:
  183. name, entry, bearer_token = _normalize_mcp_server_create(server)
  184. except ValueError as exc:
  185. display_name = (server.name or "").strip() or "<unnamed>"
  186. _log.warning("Profile-create: skipping MCP server '%s': %s", display_name, exc)
  187. continue
  188. if bearer_token is not None:
  189. entry["headers"] = _save_bearer_auth_token(name, bearer_token)
  190. mcp[name] = entry
  191. written += 1
  192. if written:
  193. save_config(cfg)
  194. elif not mcp:
  195. # Don't leave the stray empty key we just created in the new profile's config.
  196. cfg.pop("mcp_servers", None)
  197. save_config(cfg)
  198. return written
  199. # Skills & Tools endpoints accept an optional ``profile`` query param so the dashboard can
  200. # manage ANY profile's skills/toolsets ("Set as active" only flips the sticky active_profile
  201. # file for FUTURE invocations, which misled users into thinking toggles landed there).
  202. _SKILLS_PROFILE_LOCK = threading.RLock()
  203. @contextmanager
  204. def _profile_scope(profile: Optional[str]):
  205. """Scope config + skill-directory resolution to ``profile`` for one request.
  206. Two seams: (1) ``load_config``/``save_config`` resolve ``get_hermes_home()`` at call
  207. time, so the contextvar override reaches them; (2) ``tools.skills_tool`` /
  208. ``tools.skill_manager_tool`` bind ``SKILLS_DIR`` at import time, so both are retargeted
  209. under a lock and restored after. For the dashboard's own profile config resolution is
  210. untouched, but the skill-module globals are still retargeted to the *current*
  211. ``get_hermes_home()`` so writes land in the live home even when the import-time binding
  212. is stale (test isolation, late HERMES_HOME override). Yields the profile dir for a named
  213. profile, None for the current one.
  214. ``tools.skills_sync`` (reset/diff/list-modified/opt-in/opt-out/ repair-official) needs NO retargeting:
  215. since #65828 its directory lookups resolve at call time through the same contextvar override set in step
  216. 1.
  217. """
  218. from hermes_constants import get_hermes_home
  219. from tools import skills_tool as _skills_tool
  220. from tools import skill_manager_tool as _skill_mgr
  221. with _config_profile_scope(profile) as scoped:
  222. profile_dir = get_hermes_home() if scoped is None else scoped
  223. modules = (_skills_tool, _skill_mgr)
  224. with _SKILLS_PROFILE_LOCK:
  225. saved = [(m.HERMES_HOME, m.SKILLS_DIR) for m in modules]
  226. for m in modules:
  227. m.HERMES_HOME, m.SKILLS_DIR = profile_dir, profile_dir / "skills"
  228. try:
  229. yield scoped
  230. finally:
  231. for m, (home, skills_dir) in zip(modules, saved):
  232. m.HERMES_HOME, m.SKILLS_DIR = home, skills_dir
  233. @contextmanager
  234. def _config_profile_scope(profile: Optional[str]):
  235. """Await-safe profile scope: the task-local HERMES_HOME contextvar PLUS the profile's secret
  236. scope, never the process-global skills-module attributes ``_profile_scope`` swaps (holding
  237. those across an ``await`` lets a concurrent request restore THIS request's dir on its
  238. ``finally``). None/""/"current" = no override.
  239. Home alone left ``get_secret`` on the dashboard process's ``os.environ`` - the DEFAULT
  240. profile's values - so ``GET /api/config?profile=B`` expanded B's ``${VAR}`` refs to the default
  241. profile's plaintext credentials and ``load_gateway_config()`` under B's home bridged B's YAML
  242. settings into the shared process env (``yaml_env_setter`` skips only under a secret scope).
  243. A request for another profile's home also flips this process to fail-closed multi-profile
  244. hosting (``tui_gateway/launch_profile_policy.py``), so any remaining unscoped read raises
  245. instead of borrowing; the dashboard's own profile then runs under its frozen-launch-env scope.
  246. Explicit names resolving to the process home retain current-profile semantics.
  247. Still enter the requested home so a nested scope cannot retain another profile.
  248. None/""/"current" mean the request's EFFECTIVE home: a task-local override (a secondary
  249. profile's native ticket, ``native_profile_scope``) is that profile, so it gets that profile's
  250. secret scope rather than the launch profile's.
  251. """
  252. from agent.secret_scope import build_profile_secret_scope, reset_secret_scope, set_secret_scope
  253. from hermes_cli.env_loader import hydrate_profile_secret_sources
  254. from hermes_constants import get_hermes_home, get_hermes_home_override
  255. from tui_gateway.launch_profile_policy import activate_multi_profile_hosting, launch_secret_scope
  256. process_home = get_process_hermes_home()
  257. if _is_current_profile(profile):
  258. profile_dir = get_hermes_home() if get_hermes_home_override() else None
  259. else:
  260. profile_dir = _resolve_profile_dir(profile.strip())
  261. scoped = None if profile_dir is None or profile_dir.resolve() == process_home.resolve() else profile_dir
  262. if scoped is not None:
  263. activate_multi_profile_hosting()
  264. hydrate_profile_secret_sources(scoped) # first call may block on the source's fetch
  265. secrets = build_profile_secret_scope(scoped)
  266. else:
  267. # The dashboard's own profile: its launch-env scope (live env + .env while single-profile, so
  268. # systemd / op-run injection keeps resolving; frozen at activation afterwards). Bound even
  269. # before any secondary is served so the request's credential source is decided HERE: a
  270. # concurrent first ``?profile=B`` request flips ``get_secret`` to fail closed mid-request,
  271. # and an unscoped launch request would then raise ``UnscopedSecretError`` on its next read.
  272. secrets = launch_secret_scope(process_home)
  273. with (_hermes_home_scope(profile_dir) if profile_dir is not None else nullcontext()):
  274. token = set_secret_scope(secrets, profile_home=str(profile_dir or process_home))
  275. try:
  276. yield scoped
  277. finally:
  278. reset_secret_scope(token)
  279. # Terminal backend picker rows — GUI counterpart of terminal.backend. Keep in sync with
  280. # tools/terminal_tool.py::_create_environment and the terminal.backend enum.
  281. # --------------------------------------------------------------------------- Terminal execution backend
  282. # picker — the GUI counterpart of terminal.backend in config.yaml. Each row carries a fast, defensive health
  283. # probe (Docker daemon reachable, SSH host configured, Modal/Daytona credentials present) so the
  284. # Capabilities panel can render Ready / Needs setup guidance instead of a bare enum (issues #57738 /
  285. # #63783). Probes must never raise — a probe failure renders as a status, not a 500.
  286. # ---------------------------------------------------------------------------
  287. _TERMINAL_BACKENDS: list[dict[str, str]] = [
  288. dict(zip(("name", "label", "description"), row)) for row in (
  289. ("local", "Local", "Run commands directly on this machine. No isolation."),
  290. ("docker", "Docker / Podman",
  291. "Run commands in an isolated Docker or Podman container with a persistent workspace."),
  292. ("modal", "Modal", "Run commands in a Modal cloud sandbox."),
  293. ("daytona", "Daytona", "Run commands in a Daytona cloud sandbox."),
  294. ("ssh", "SSH", "Run commands on a remote host over SSH."))]
  295. def _plugin_terminal_backend_rows() -> list[dict[str, str]]:
  296. """Picker rows for plugin-registered terminal backends (fail-soft)."""
  297. rows: list[dict[str, str]] = []
  298. try:
  299. from hermes_cli.plugins import discover_plugins
  300. discover_plugins() # idempotent — plugin state may not be loaded yet
  301. except Exception:
  302. pass
  303. try:
  304. from agent.terminal_env_registry import list_providers
  305. for provider in list_providers():
  306. try:
  307. rows.append({"name": provider.name.strip().lower(), "label": provider.display_name,
  308. "description": provider.description})
  309. except Exception:
  310. continue
  311. except Exception:
  312. return rows
  313. return rows
  314. # Token / cost analytics helpers.
  315. _AUX_COUNTERS = ("input_tokens", "output_tokens", "estimated_cost", "api_calls")
  316. def _token_volume(row: dict[str, Any]) -> Any:
  317. return (row.get("input_tokens") or 0) + (row.get("output_tokens") or 0)
  318. def _aux_usage_rows(db, cutoff: float) -> list[dict[str, Any]]:
  319. """Per-(model, task) auxiliary usage within the window: the task-dimension rows
  320. (task != '') record_auxiliary_usage writes into session_model_usage. [] when the
  321. table predates the task column (older DB opened read-only by newer code).
  322. See #23270.
  323. """
  324. try:
  325. cur = db._conn.execute("""
  326. SELECT u.model,
  327. u.task,
  328. u.billing_provider,
  329. SUM(u.input_tokens) as input_tokens,
  330. SUM(u.output_tokens) as output_tokens,
  331. SUM(u.cache_read_tokens) as cache_read_tokens,
  332. SUM(u.reasoning_tokens) as reasoning_tokens,
  333. COALESCE(SUM(u.estimated_cost_usd), 0) as estimated_cost,
  334. COUNT(DISTINCT u.session_id) as sessions,
  335. SUM(COALESCE(u.api_call_count, 0)) as api_calls,
  336. MAX(u.last_seen) as last_used_at
  337. FROM session_model_usage u
  338. JOIN sessions s ON s.id = u.session_id
  339. WHERE s.started_at > ? AND u.task != ''
  340. GROUP BY u.model, u.task, u.billing_provider
  341. ORDER BY SUM(u.input_tokens) + SUM(u.output_tokens) DESC
  342. """, (cutoff,))
  343. return [dict(r) for r in cur.fetchall()]
  344. except Exception:
  345. return []
  346. def _merge_aux_into_by_model(
  347. by_model: list[dict[str, Any]], aux_rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
  348. """Fold aux usage rows into the sessions-derived per-model list. Aux usage lives only in
  349. session_model_usage (never in the sessions counters), so this cannot double-count;
  350. models that ONLY appear via aux calls (e.g. a vision model) get their own entry."""
  351. if not aux_rows:
  352. return by_model
  353. merged: dict[str, dict[str, Any]] = {row.get("model") or "unknown": row for row in by_model}
  354. for aux in aux_rows:
  355. model = aux.get("model") or "unknown"
  356. target = merged.setdefault(model, {"model": model, "input_tokens": 0, "output_tokens": 0,
  357. "estimated_cost": 0, "sessions": 0, "api_calls": 0})
  358. for key in _AUX_COUNTERS:
  359. target[key] = (target.get(key) or 0) + (aux.get(key) or 0)
  360. target.setdefault("aux_tasks", []).append(
  361. {"task": aux.get("task") or "", **{key: aux.get(key) or 0 for key in _AUX_COUNTERS}})
  362. return sorted(merged.values(), key=_token_volume, reverse=True)
  363. def _aux_task_summary(aux_rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
  364. """Aggregate aux usage rows across models into a per-task summary."""
  365. by_task: dict[str, dict[str, Any]] = {}
  366. for aux in aux_rows:
  367. task = aux.get("task") or ""
  368. d = by_task.setdefault(task, {"task": task, "input_tokens": 0, "output_tokens": 0,
  369. "estimated_cost": 0, "api_calls": 0, "models": []})
  370. for key in _AUX_COUNTERS:
  371. d[key] += aux.get(key) or 0
  372. model = aux.get("model") or "unknown"
  373. if model not in d["models"]:
  374. d["models"].append(model)
  375. return sorted(by_task.values(), key=_token_volume, reverse=True)
  376. def _profile_cli_args(profile: Optional[str]) -> list[str]:
  377. """``["-p", <name>]`` for a validated named profile, else ``[]``. Hub actions run in
  378. a fresh ``hermes`` subprocess whose ``_apply_profile_override()`` reads ``-p`` from argv —
  379. the only mechanism that reaches import-time-bound globals like ``skills_hub.SKILLS_DIR``.
  380. ``default`` is a real named target, not an alias for the dashboard's own profile:
  381. selector-less argv would make the child resolve the ambient ``HERMES_HOME`` (the launch
  382. profile under a pooled ``-p X serve``), not the default home."""
  383. requested = (profile or "").strip()
  384. if not requested or requested.lower() == "current":
  385. return []
  386. from hermes_cli import profiles as profiles_mod
  387. _resolve_profile_dir(requested)
  388. return ["-p", profiles_mod.normalize_profile_name(requested)]
  389. def _hub_action_name(verb: str, key: str) -> str:
  390. """Unique per-skill hub action name (+ registered log file): ``_spawn_hermes_action``
  391. tracks one process/log per name, so a shared "skills-install" would make concurrent
  392. row-level actions overwrite each other. Slug (readable) + hash (collision-proof)."""
  393. slug = re.sub(r"[^a-z0-9]+", "-", key.lower()).strip("-")[:48] or "skill"
  394. digest = hashlib.sha1(key.encode()).hexdigest()[:8]
  395. name = f"skills-{verb}-{slug}-{digest}"
  396. _ACTION_LOG_FILES.setdefault(name, f"action-{name}.log")
  397. return name
  398. def _installed_hub_identifiers(profile: Optional[str] = None) -> dict:
  399. """identifier -> installed lock entry for hub-installed skills (UI marks installed search
  400. results and catalog cards). Scoped to ``profile``'s skills/.hub/lock.json when given —
  401. HubLockFile takes an explicit path, sidestepping the import-time LOCK_FILE binding. {} when
  402. unreadable.
  403. Keyed by ``HubLockFile.by_identifier``, so a ClawHub install also answers to the
  404. ``clawhub/<slug>`` id a catalog card installs. Search lists a ClawHub skill by its bare
  405. slug; a client looks such a hit up under that card id, going by the hit's source."""
  406. try:
  407. from tools.skills_hub import HubLockFile
  408. if _is_current_profile(profile):
  409. lock = HubLockFile()
  410. else:
  411. profile_dir = _resolve_profile_dir(profile.strip())
  412. lock = HubLockFile(profile_dir / "skills" / ".hub" / "lock.json")
  413. keys = ("name", "trust_level", "scan_verdict")
  414. return {identifier: {k: entry.get(k) for k in keys}
  415. for identifier, entry in lock.by_identifier().items()}
  416. except HTTPException:
  417. raise # an unknown profile is the scope's 404, not an unreadable lock file
  418. except Exception:
  419. return {}