dsh-plugin-linux-computer-use 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0 - 2026-11-27
4
+
5
+ - **The server now refreshes itself.** The bundle copied `server/*.py` into
6
+ `~/.local/share/dsh-linux-computer-use` when the *doctor* plugin loaded, but
7
+ the MCP server is started by a separate patch entry: toggling only that entry
8
+ (the normal thing to do in Settings → Plugins) or upgrading the npm package
9
+ left a stale copy running, with no visible sign. The sync now also drops a
10
+ `.source` breadcrumb, and the server compares itself against that package
11
+ before doing anything, copies the newer files and re-executes — so a restart
12
+ is enough, and a stale code path can no longer survive one.
13
+ - `linux_mcp_doctor` grew two preflight checks: `keybindings` (which of
14
+ Alt+Tab / Super+Tab are actually bound, because the keyboard fallback of
15
+ `window_activate` depends on it) and `server-copy` (whether the running copy
16
+ is in step with the installed package). Both also run from
17
+ `linux_desktop_mcp.py --selftest`.
18
+ - `ui_tree` can now be pruned: pass `roles` (e.g. `["push button", "entry"]`)
19
+ to keep only the kinds of node you care about — ancestors collapse into a
20
+ bare `ref`/`role`/`name` path — and `compact` to drop rectangles, states and
21
+ text previews. Measured on this machine: 140 nodes / 10.2 KB → 20 nodes /
22
+ 0.85 KB for the same screen, and filtered trees on a real application save
23
+ far more. The reply now reports `nodes_returned` next to `nodes_used`.
24
+ - Defunct applications are no longer walked (they still answer AT-SPI and
25
+ quietly ate the node budget).
26
+ - MCP server version 1.3.0.
27
+
3
28
  ## 0.3.0 - 2026-11-27
4
29
 
5
30
  - New `window_activate`: raise a window by title substring (or app name). Three
package/README.md CHANGED
@@ -59,6 +59,11 @@ sudo ./linux-computer-use-prep.sh --verify # 不需要 sudo
59
59
 
60
60
  开着插件但没开 Computer Use 时也可以先跑 `linux_mcp_doctor`(不需要 MCP 在线),它会逐项告诉你缺什么、怎么补。
61
61
 
62
+ ## 省钱与提速的两招
63
+
64
+ - **`ui_tree` 先过滤再读**:`roles: ["push button", "entry"]` 只保留你要的节点类型,祖先会折叠成 `ref`/`role`/`name` 的路径;再加 `compact: true` 去掉 rect/states/text。实测同一屏 140 节点/10.2 KB → 20 节点/0.85 KB。
65
+ - **`screenshot` 用 `region` + `scale: 1.0`**:先在 4480×1440 原图上裁剪再缩放,小字才清楚,token 也只有整屏的三分之一。
66
+
62
67
  ## 已知限制(重要,别踩坑)
63
68
 
64
69
  - **Chromium / Electron / Qt 应用(Chrome、VS Code、微信、WPS、Bitwarden)暴露的 UI 树是空的**——这是平台事实,不是 bug。它们只能靠"截屏 + 坐标点击",窗口一动就得重新截图。原生 GTK 应用用 `ui_find` + `ui_action` 很稳。
@@ -125,7 +130,7 @@ honouring its motion: keyboard and scroll still work, clicks do nothing.
125
130
  python3 -u ~/.local/share/dsh-linux-computer-use/linux_desktop_mcp.py --selftest
126
131
  ```
127
132
 
128
- 或在对话里让模型调用 `linux_mcp_doctor`。逐项报告:会话类型、Python/GI/Atspi/Gst、`/dev/uinput`、启动器、wl-clipboard、portal 版本、pipewiresrc、截屏授权、显示器、AT-SPI 应用数。
133
+ 或在对话里让模型调用 `linux_mcp_doctor`。逐项报告:会话类型、Python/GI/Atspi/Gst、`/dev/uinput`、启动器、wl-clipboard、portal 版本、pipewiresrc、截屏授权、显示器、AT-SPI 应用数、**GNOME 窗口切换键位绑定**(Alt+Tab / Super+Tab 哪个有效),以及**正在运行的 server 副本是否与安装的包一致**。
129
134
 
130
135
  ## 兼容性
131
136
 
@@ -141,7 +146,7 @@ MIT
141
146
 
142
147
  ### English
143
148
 
144
- Linux desktop automation for DeepSeek Harness on Wayland. Screenshots go through the `xdg-desktop-portal` Screenshot interface (the only Wayland-legal path, ~0.5s per capture after one granted approval); pointer and keyboard input go straight to `/dev/uinput` so applications cannot tell them from a real user; the UI tree comes from AT-SPI2. 28 tools are published as `mcp__linux__*`, plus a `linux_mcp_doctor` host tool that diagnoses the environment even while the bridge is off. Ships disabled: enable it in Settings → Plugins.
149
+ Linux desktop automation for DeepSeek Harness on Wayland. Screenshots go through the `xdg-desktop-portal` Screenshot interface (the only Wayland-legal path, ~0.5s per capture after one granted approval); pointer and keyboard input go straight to `/dev/uinput` so applications cannot tell them from a real user; the UI tree comes from AT-SPI2. 30 tools are published as `mcp__linux__*`, plus a `linux_mcp_doctor` host tool that diagnoses the environment even while the bridge is off. Ships disabled: enable it in Settings → Plugins.
145
150
 
146
151
  Install: `dsh plugin --profile web add dsh-plugin-linux-computer-use`, run `sudo ./linux-computer-use-prep.sh`, restart `dsh`, then flip the switch.
147
152
 
package/docs/DETAIL.md CHANGED
@@ -46,7 +46,7 @@ reload the page. `linux_mcp_doctor` works either way.
46
46
  | Group | Tools |
47
47
  | --- | --- |
48
48
  | Vision | `screenshot` — PNG + size + path; `region` crops before scaling (sharp text), `scale` sets pixels per logical pixel; the first call asks for permission once |
49
- | Tree | `ui_apps`, `ui_tree`, `ui_find`, `ui_describe`, `ui_text` |
49
+ | Tree | `ui_apps`, `ui_tree` (prune with `roles` + `compact`), `ui_find`, `ui_describe`, `ui_text` |
50
50
  | Act on elements | `ui_action` (invoke/press/toggle), `ui_focus`, `ui_set_text` |
51
51
  | Pointer | `click`, `move`, `drag`, `scroll`, `pointer_button` (hold/release) |
52
52
  | Keyboard | `key` (`ctrl+shift+t`), `type_text` (Unicode via clipboard paste) |
package/index.js CHANGED
@@ -19,6 +19,7 @@ import {
19
19
  mkdirSync,
20
20
  readdirSync,
21
21
  readFileSync,
22
+ writeFileSync,
22
23
  } from 'node:fs'
23
24
  import { homedir } from 'node:os'
24
25
  import { dirname, join } from 'node:path'
@@ -58,6 +59,11 @@ function syncServerFiles() {
58
59
  copyFileSync(from, to)
59
60
  copied.push(name)
60
61
  }
62
+ // Leave a breadcrumb so the installed copy can refresh itself even when
63
+ // only the MCP entry is toggled (that entry never re-runs this function).
64
+ try {
65
+ writeFileSync(join(INSTALL_DIR, '.source'), `${source}\n`, { mode: 0o600 })
66
+ } catch {}
61
67
  return { ok: true, dir: INSTALL_DIR, copied }
62
68
  } catch (error) {
63
69
  return { ok: false, dir: INSTALL_DIR, detail: error?.message ?? String(error), copied }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-linux-computer-use",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Computer Use for a Wayland Linux desktop in DeepSeek Harness: screenshots, UI tree, pointer and keyboard input, clipboard, processes and settings, bridged as mcp__linux__* tools. · 让 DSH 接管 Ubuntu/GNOME 桌面:截屏、UI 树、鼠标键盘、剪贴板、进程与系统设置。",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/server/cu_a11y.py CHANGED
@@ -65,6 +65,11 @@ class A11yError(RuntimeError):
65
65
  """The accessibility tree could not be read or the element is gone."""
66
66
 
67
67
 
68
+ def _count_nodes(node: dict) -> int:
69
+ """How many nodes this subtree actually carries (after filtering)."""
70
+ return 1 + sum(_count_nodes(child) for child in node.get("children", []))
71
+
72
+
68
73
  def _state_names(acc) -> list[str]:
69
74
  try:
70
75
  state_set = acc.get_state_set()
@@ -262,7 +267,8 @@ class A11y:
262
267
  return None
263
268
 
264
269
  # -- snapshot ---------------------------------------------------------- #
265
- def node(self, acc, depth: int, budget: dict, deadline: float) -> dict | None:
270
+ def node(self, acc, depth: int, budget: dict, deadline: float,
271
+ wanted_roles: set | None = None, compact: bool = False) -> dict | None:
266
272
  if budget["nodes"] <= 0 or time.monotonic() > deadline:
267
273
  budget["truncated"] = True
268
274
  return None
@@ -272,40 +278,57 @@ class A11y:
272
278
  name = acc.get_name() or ""
273
279
  except Exception: # noqa: BLE001
274
280
  return None
275
- item: dict = {"ref": self._ref(acc), "role": role}
276
- if name:
277
- item["name"] = name[:120]
278
281
  states = _state_names(acc)
279
- if states:
280
- item["states"] = states
281
- rect = _extents(acc)
282
- if rect:
283
- item["rect"] = rect
284
- actions = _actions(acc)
285
- if actions:
286
- item["actions"] = actions
287
- text = _text_preview(acc)
288
- if text:
289
- item["text"] = text
282
+ if "defunct" in states:
283
+ # A dead application still answers AT-SPI; walking it wastes the budget.
284
+ return None
285
+ children: list[dict] = []
290
286
  if depth > 0:
291
- children = []
292
287
  try:
293
288
  count = acc.get_child_count()
294
289
  except Exception: # noqa: BLE001
295
290
  count = 0
296
291
  for index in range(count):
297
- child = self.node(acc.get_child_at_index(index), depth - 1, budget, deadline)
292
+ child = self.node(acc.get_child_at_index(index), depth - 1, budget, deadline,
293
+ wanted_roles, compact)
298
294
  if child is None:
299
295
  if budget["truncated"]:
300
296
  break
301
297
  continue
302
298
  children.append(child)
303
- if children:
304
- item["children"] = children
299
+ matched = True
300
+ if wanted_roles is not None:
301
+ lowered = role.lower()
302
+ matched = any(needle in lowered for needle in wanted_roles)
303
+ if not matched and not children:
304
+ # Nothing here and nothing below is interesting: drop the node.
305
+ return None
306
+ item: dict = {"ref": self._ref(acc), "role": role}
307
+ if name:
308
+ item["name"] = name[:120]
309
+ if matched and not compact:
310
+ if states:
311
+ item["states"] = states
312
+ rect = _extents(acc)
313
+ if rect:
314
+ item["rect"] = rect
315
+ actions = _actions(acc)
316
+ if actions:
317
+ item["actions"] = actions
318
+ text = _text_preview(acc)
319
+ if text:
320
+ item["text"] = text
321
+ elif matched and compact:
322
+ actions = _actions(acc)
323
+ if actions:
324
+ item["actions"] = actions
325
+ if children:
326
+ item["children"] = children
305
327
  return item
306
328
 
307
329
  def snapshot(self, app: str | None = None, max_depth: int = 3,
308
- max_nodes: int = 220, timeout_s: float = 20.0) -> dict:
330
+ max_nodes: int = 220, timeout_s: float = 20.0,
331
+ roles: list[str] | None = None, compact: bool = False) -> dict:
309
332
  self.start()
310
333
  deadline = time.monotonic() + timeout_s
311
334
  budget = {"nodes": max_nodes, "truncated": False}
@@ -321,17 +344,21 @@ class A11y:
321
344
  target = self._apps.get(item["name"])
322
345
  if target is not None:
323
346
  roots.append((target, item["name"]))
347
+ wanted_roles = {item.lower() for item in roles} if roles else None
324
348
  tree = []
325
349
  for root, label in roots:
326
- node = self.node(root, max_depth, budget, deadline)
350
+ node = self.node(root, max_depth, budget, deadline, wanted_roles, compact)
327
351
  if node is not None:
328
352
  node.setdefault("name", label)
329
353
  node["app"] = label
330
354
  tree.append(node)
355
+ emitted = sum(_count_nodes(item) for item in tree)
356
+
331
357
  return {
332
358
  "applications": tree,
333
359
  "truncated": bool(budget["truncated"]),
334
360
  "nodes_used": max_nodes - max(0, budget["nodes"]),
361
+ "nodes_returned": emitted,
335
362
  }
336
363
 
337
364
  # -- search ------------------------------------------------------------ #
@@ -32,6 +32,7 @@ from __future__ import annotations
32
32
  import base64
33
33
  import json
34
34
  import os
35
+ import shutil
35
36
  import subprocess
36
37
  import sys
37
38
  import time
@@ -46,7 +47,7 @@ import cu_sys # noqa: E402
46
47
  import cu_unlock # noqa: E402
47
48
 
48
49
  SERVER_NAME = "linux-desktop-mcp"
49
- SERVER_VERSION = "1.2.0"
50
+ SERVER_VERSION = "1.3.0"
50
51
  PROTOCOL_VERSION = "2025-06-18"
51
52
  SUPPORTED_PROTOCOLS = {"2024-11-05", "2025-03-26", "2025-06-18"}
52
53
  LOG_PATH = os.path.join(cu_display.CACHE_DIR, "server.log")
@@ -349,7 +350,15 @@ def tool_ui_tree(args: dict) -> dict:
349
350
  app = args.get("app")
350
351
  depth = max(1, min(int(args.get("max_depth", 3)), 8))
351
352
  nodes = max(10, min(int(args.get("max_nodes", 220)), 1200))
352
- snapshot = A11Y.snapshot(app=app, max_depth=depth, max_nodes=nodes)
353
+ roles = args.get("roles")
354
+ if isinstance(roles, str):
355
+ roles = [roles]
356
+ if roles is not None and not isinstance(roles, list):
357
+ raise ToolError("roles must be a list of role name fragments, e.g. [\"push button\", \"entry\"]")
358
+ compact = bool(args.get("compact", False))
359
+ snapshot = A11Y.snapshot(app=app, max_depth=depth, max_nodes=nodes,
360
+ roles=[str(item) for item in roles] if roles else None,
361
+ compact=compact)
353
362
  if snapshot["nodes_used"] <= 3 and snapshot["applications"]:
354
363
  snapshot["hint"] = (
355
364
  "the application exposes (almost) no accessibility nodes: Chromium, "
@@ -1084,8 +1093,10 @@ TOOLS: list[dict] = [
1084
1093
  "name": "ui_tree",
1085
1094
  "description": (
1086
1095
  "Read the accessibility tree of one application (or a few) as nested role/name/rect/"
1087
- "action nodes. Bounded by max_depth and max_nodes. Chromium/Electron/Qt apps usually "
1088
- "expose almost nothing; use screenshot for those."
1096
+ "action nodes. Bounded by max_depth and max_nodes. Pass roles to keep only interesting "
1097
+ "kinds of node (ancestors collapse to a bare ref/role/name path), and compact to drop "
1098
+ "rect/states/text: a filtered compact tree is often 10x cheaper than the full one. "
1099
+ "Chromium/Electron/Qt apps usually expose almost nothing; use screenshot for those."
1089
1100
  ),
1090
1101
  "inputSchema": {
1091
1102
  "type": "object",
@@ -1093,6 +1104,19 @@ TOOLS: list[dict] = [
1093
1104
  "app": {"type": "string", "description": "Application name as shown by ui_apps (substring match)."},
1094
1105
  "max_depth": {"type": "integer", "default": 3, "minimum": 1, "maximum": 8},
1095
1106
  "max_nodes": {"type": "integer", "default": 220, "minimum": 10, "maximum": 1200},
1107
+ "roles": {
1108
+ "type": "array",
1109
+ "items": {"type": "string"},
1110
+ "description": (
1111
+ "Keep only nodes whose role contains one of these fragments, e.g. "
1112
+ "[\"push button\", \"entry\", \"menu item\"]. Case-insensitive."
1113
+ ),
1114
+ },
1115
+ "compact": {
1116
+ "type": "boolean",
1117
+ "default": False,
1118
+ "description": "Drop rect, states and text previews; keep ref, role, name and actions.",
1119
+ },
1096
1120
  },
1097
1121
  },
1098
1122
  "handler": tool_ui_tree,
@@ -1624,6 +1648,129 @@ def _portal_screencast_version() -> int | None:
1624
1648
  return None
1625
1649
 
1626
1650
 
1651
+ def _gsettings_list(schema: str, key: str) -> list[str] | None:
1652
+ """Read a list-valued gsettings key ("['<Super>Tab', '<Alt>Tab']")."""
1653
+ try:
1654
+ result = subprocess.run(
1655
+ ["gsettings", "get", schema, key],
1656
+ capture_output=True, text=True, timeout=4.0, check=False,
1657
+ )
1658
+ except (OSError, subprocess.SubprocessError):
1659
+ return None
1660
+ if result.returncode != 0:
1661
+ return None
1662
+ raw = result.stdout.strip()
1663
+ if not raw.startswith("[") or not raw.endswith("]"):
1664
+ return None
1665
+ inner = raw[1:-1].strip()
1666
+ if not inner:
1667
+ return []
1668
+ return [part.strip().strip("'\"") for part in inner.split(",")]
1669
+
1670
+
1671
+ def _keybinding_checks(checks: list) -> None:
1672
+ """Explain which window-switch shortcut window_activate can actually use."""
1673
+ schema = "org.gnome.desktop.wm.keybindings"
1674
+ windows = _gsettings_list(schema, "switch-windows")
1675
+ apps = _gsettings_list(schema, "switch-applications")
1676
+ if windows is None and apps is None:
1677
+ _check(
1678
+ checks,
1679
+ "keybindings",
1680
+ "warn",
1681
+ "window-switch keybindings are unreadable",
1682
+ "gsettings did not answer; window_activate can still raise XWayland windows",
1683
+ "install libglib2.0-bin (gsettings) to make the keyboard fallback verifiable",
1684
+ )
1685
+ return
1686
+ windows = windows or []
1687
+ apps = apps or []
1688
+ has_alt = any("Alt" in item and "Tab" in item for item in windows)
1689
+ has_super = any("Super" in item and "Tab" in item for item in apps)
1690
+ if has_alt and has_super:
1691
+ _check(
1692
+ checks,
1693
+ "keybindings",
1694
+ "ok",
1695
+ "both window-switch shortcuts are bound",
1696
+ "Alt+Tab switches windows of one application, Super+Tab switches applications",
1697
+ )
1698
+ elif has_super:
1699
+ _check(
1700
+ checks,
1701
+ "keybindings",
1702
+ "ok",
1703
+ "Super+Tab is bound to switch applications",
1704
+ "Alt+Tab is not bound, so window_activate goes straight to Super+Tab",
1705
+ )
1706
+ elif has_alt:
1707
+ _check(
1708
+ checks,
1709
+ "keybindings",
1710
+ "warn",
1711
+ "only Alt+Tab is bound",
1712
+ "Alt+Tab switches windows inside the current application, so raising another application's window may fail",
1713
+ "add a Super+Tab binding to switch-applications, or drag the window forward by hand",
1714
+ )
1715
+ else:
1716
+ _check(
1717
+ checks,
1718
+ "keybindings",
1719
+ "warn",
1720
+ "no window-switch shortcut is bound",
1721
+ "window_activate can only rely on xdotool and the accessibility default action",
1722
+ "bind switch-windows to <Alt>Tab in Settings -> Keyboard -> View and Customise Shortcuts",
1723
+ )
1724
+
1725
+
1726
+ def _sync_check(checks: list) -> None:
1727
+ """Report whether this running copy is in step with the installed package."""
1728
+ if not os.path.exists(SOURCE_POINTER):
1729
+ _check(
1730
+ checks,
1731
+ "server-copy",
1732
+ "warn",
1733
+ "cannot tell which package this server copy came from",
1734
+ f"{SOURCE_POINTER} is missing; the copy never refreshes itself",
1735
+ "reinstall the bundle, or reload it from Settings -> Plugins",
1736
+ )
1737
+ return
1738
+ try:
1739
+ with open(SOURCE_POINTER, encoding="utf-8") as handle:
1740
+ source = handle.read().strip()
1741
+ except OSError as error: # noqa: BLE001
1742
+ _check(checks, "server-copy", "warn", "cannot read the package pointer", str(error))
1743
+ return
1744
+ fresh = os.path.join(source, "linux_desktop_mcp.py")
1745
+ if not os.path.exists(fresh):
1746
+ _check(
1747
+ checks,
1748
+ "server-copy",
1749
+ "warn",
1750
+ "the package this copy came from is gone",
1751
+ source,
1752
+ "reinstall the bundle; the copy now updates itself from the package on start",
1753
+ )
1754
+ return
1755
+ ours = os.path.abspath(__file__)
1756
+ try:
1757
+ same = open(fresh, "rb").read() == open(ours, "rb").read()
1758
+ except OSError as error: # noqa: BLE001
1759
+ _check(checks, "server-copy", "warn", "cannot compare server copies", str(error))
1760
+ return
1761
+ if same:
1762
+ _check(checks, "server-copy", "ok", "this copy matches the installed package", source)
1763
+ else:
1764
+ _check(
1765
+ checks,
1766
+ "server-copy",
1767
+ "warn",
1768
+ "this copy differs from the installed package",
1769
+ f"package: {fresh}",
1770
+ "restart the MCP entry (or reload the bundle): the server refreshes itself on start",
1771
+ )
1772
+
1773
+
1627
1774
  def selftest() -> dict:
1628
1775
  """Collect everything the doctor tool needs, without asking for permissions."""
1629
1776
  checks: list[dict] = []
@@ -1831,6 +1978,9 @@ def selftest() -> dict:
1831
1978
  except Exception as error: # noqa: BLE001
1832
1979
  _check(checks, "a11y", "warn", "AT-SPI is unavailable", str(error), "check that org.a11y.Bus is running")
1833
1980
 
1981
+ _keybinding_checks(checks)
1982
+ _sync_check(checks)
1983
+
1834
1984
  ok = not any(check["status"] == "fail" for check in checks)
1835
1985
  return {
1836
1986
  "ok": ok,
@@ -1871,7 +2021,64 @@ def _cli_unlock(args: list[str]) -> int | None:
1871
2021
  return None
1872
2022
 
1873
2023
 
2024
+ INSTALL_DIR = os.path.dirname(os.path.abspath(__file__))
2025
+ SOURCE_POINTER = os.path.join(INSTALL_DIR, ".source")
2026
+ SELF_UPDATE_FLAG = "DSH_LINUX_CU_SELF_UPDATED"
2027
+
2028
+
2029
+ def _self_update() -> None:
2030
+ """Refresh this copy of the server from the installed package, then re-exec.
2031
+
2032
+ The bundle syncs server/*.py into a stable directory when the *doctor*
2033
+ plugin loads, but the MCP server is started by a different patch entry, so
2034
+ toggling only that entry (or upgrading the npm package) leaves a stale copy
2035
+ behind. A pointer file records where the package lives; comparing against
2036
+ it here makes the server heal itself before it serves a single request.
2037
+ """
2038
+ if os.environ.get(SELF_UPDATE_FLAG) == "1":
2039
+ return
2040
+ try:
2041
+ with open(SOURCE_POINTER, encoding="utf-8") as handle:
2042
+ source = handle.read().strip()
2043
+ except OSError:
2044
+ return
2045
+ if not source or not os.path.isdir(source):
2046
+ return
2047
+ if os.path.realpath(source) == os.path.realpath(INSTALL_DIR):
2048
+ return
2049
+ if not os.path.exists(os.path.join(source, "linux_desktop_mcp.py")):
2050
+ return
2051
+ changed: list[str] = []
2052
+ for name in sorted(os.listdir(source)):
2053
+ if not name.endswith(".py"):
2054
+ continue
2055
+ fresh = os.path.join(source, name)
2056
+ stale = os.path.join(INSTALL_DIR, name)
2057
+ try:
2058
+ with open(fresh, "rb") as mine, open(stale, "rb") as theirs:
2059
+ if mine.read() == theirs.read():
2060
+ continue
2061
+ except OSError:
2062
+ pass
2063
+ try:
2064
+ shutil.copyfile(fresh, stale)
2065
+ changed.append(name)
2066
+ except OSError as error: # noqa: BLE001
2067
+ log(f"self-refresh could not copy {name}: {error}")
2068
+ if not changed:
2069
+ return
2070
+ log(f"refreshed {len(changed)} server file(s) from {source}: {', '.join(changed)}")
2071
+ env = dict(os.environ)
2072
+ env[SELF_UPDATE_FLAG] = "1"
2073
+ try:
2074
+ os.execve(sys.executable, [sys.executable, os.path.abspath(__file__), *sys.argv[1:]], env)
2075
+ except OSError as error: # noqa: BLE001
2076
+ log(f"self-refresh re-exec failed: {error}")
2077
+
2078
+
1874
2079
  def main() -> int:
2080
+ # Serve (and diagnose) with the freshest copy of the code we can find.
2081
+ _self_update()
1875
2082
  unlock_exit = _cli_unlock(sys.argv[1:])
1876
2083
  if unlock_exit is not None:
1877
2084
  return unlock_exit