datap-0.4 0.4.0__py3-none-any.whl

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.
btsh/__init__.py ADDED
@@ -0,0 +1,42 @@
1
+ """btsh - an ssh-like shell that rides on a Bluetooth speaker's audio codec."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.metadata import PackageNotFoundError
6
+ from importlib.metadata import version as _distribution_version
7
+
8
+ try: # installed from PyPI or a wheel
9
+ __version__ = _distribution_version("datap")
10
+ except PackageNotFoundError: # running from a source tree, keep in sync with pyproject.toml
11
+ __version__ = "0.3.0"
12
+
13
+ from .channel import Channel, ChannelError # noqa: E402
14
+ from .client import Client # noqa: E402
15
+ from .server import ShellConfig, ShellServer, execute # noqa: E402
16
+ from .session import AuthError, Session # noqa: E402
17
+ from .transport import ( # noqa: E402
18
+ AcousticTransport,
19
+ CodecTransport,
20
+ FifoTransport,
21
+ LoopbackTransport,
22
+ Transport,
23
+ TransportError,
24
+ )
25
+
26
+ __all__ = [
27
+ "__version__",
28
+ "AcousticTransport",
29
+ "AuthError",
30
+ "Channel",
31
+ "ChannelError",
32
+ "Client",
33
+ "CodecTransport",
34
+ "FifoTransport",
35
+ "LoopbackTransport",
36
+ "Session",
37
+ "ShellConfig",
38
+ "ShellServer",
39
+ "Transport",
40
+ "TransportError",
41
+ "execute",
42
+ ]
btsh/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Allow ``python -m btsh``."""
2
+
3
+ from .cli import main
4
+
5
+ raise SystemExit(main())
btsh/audio.py ADDED
@@ -0,0 +1,143 @@
1
+ """Cross-platform audio transport: PortAudio through ``sounddevice``.
2
+
3
+ One backend for Linux, macOS and Windows, unlike the PipeWire transport which
4
+ is Linux only. The Bluetooth device just has to be the system's output device
5
+ (and, for duplex, its input device): the OS does the A2DP/HFP plumbing, we
6
+ speak into it and listen from it.
7
+
8
+ Linux pactl list short sinks -> device index or name
9
+ macOS system output / input -> the AirPods show up as one device
10
+ Windows WASAPI/MME device names -> the AirPods output, not "Stereo Mix"
11
+
12
+ ``sounddevice`` needs the PortAudio shared library: package ``portaudio`` on
13
+ Debian/Fedora, ``portaudio`` on Homebrew, nothing on Windows (bundled).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import queue
19
+ import time
20
+
21
+ from .modem import SAMPLE_RATE
22
+ from .transport import Transport, TransportError
23
+
24
+
25
+ def _sd():
26
+ try:
27
+ import sounddevice # noqa: PLC0415 - optional dependency
28
+ except OSError as exc: # pragma: no cover - depends on the host
29
+ raise TransportError(f"PortAudio missing: {exc}") from exc
30
+ except ImportError as exc: # pragma: no cover
31
+ raise TransportError("install btsh[audio] (pip install sounddevice)") from exc
32
+ return sounddevice
33
+
34
+
35
+ def list_devices() -> list[dict]:
36
+ """Audio devices, with the default input/output flagged."""
37
+ sd = _sd()
38
+ try:
39
+ raw = sd.query_devices()
40
+ default_in, default_out = sd.default.device
41
+ except Exception as exc: # pragma: no cover - host dependent
42
+ raise TransportError(f"could not enumerate audio devices: {exc}") from exc
43
+ devices = []
44
+ for index, device in enumerate(raw):
45
+ devices.append(
46
+ {
47
+ "index": index,
48
+ "name": device["name"],
49
+ "inputs": int(device["max_input_channels"]),
50
+ "outputs": int(device["max_output_channels"]),
51
+ "default_input": index == default_in,
52
+ "default_output": index == default_out,
53
+ "host_api": sd.query_hostapis(device["hostapi"])["name"],
54
+ }
55
+ )
56
+ return devices
57
+
58
+
59
+ class PortAudioTransport(Transport):
60
+ """Duplex PCM over the system's default (or named) audio devices."""
61
+
62
+ name = "portaudio"
63
+
64
+ def __init__(
65
+ self,
66
+ output_device: str | int | None = None,
67
+ input_device: str | int | None = None,
68
+ rate: int = SAMPLE_RATE,
69
+ blocksize: int = 480,
70
+ ) -> None:
71
+ self.sd = _sd()
72
+ self.rate = rate
73
+ self.output_device = output_device
74
+ self.input_device = input_device
75
+ self._queue: queue.Queue[bytes] = queue.Queue()
76
+ self._min_burst = int(rate * 0.25) * 2 # 250 ms of s16
77
+ try:
78
+ self._out = self.sd.RawOutputStream(
79
+ samplerate=rate,
80
+ blocksize=blocksize,
81
+ device=output_device,
82
+ channels=1,
83
+ dtype="int16",
84
+ )
85
+ self._in = self.sd.RawInputStream(
86
+ samplerate=rate,
87
+ blocksize=blocksize,
88
+ device=input_device,
89
+ channels=1,
90
+ dtype="int16",
91
+ callback=self._callback,
92
+ )
93
+ except Exception as exc: # pragma: no cover - host dependent
94
+ raise TransportError(f"could not open audio devices: {exc}") from exc
95
+ self._out.start()
96
+ self._in.start()
97
+
98
+ def _callback(self, indata, frames, time_info, status) -> None: # noqa: ANN001 - PortAudio signature
99
+ self._queue.put(bytes(indata))
100
+
101
+ def send_burst(self, pcm: bytes) -> None:
102
+ try:
103
+ self._out.write(pcm)
104
+ except Exception as exc: # pragma: no cover - device unplugged
105
+ raise TransportError(f"playback failed: {exc}") from exc
106
+
107
+ def recv_burst(self, timeout: float = 5.0) -> bytes | None:
108
+ deadline = time.monotonic() + timeout
109
+ buffer = bytearray()
110
+ while time.monotonic() < deadline:
111
+ try:
112
+ buffer.extend(self._queue.get(timeout=max(0.01, deadline - time.monotonic())))
113
+ except queue.Empty:
114
+ break
115
+ if len(buffer) >= self._min_burst:
116
+ while True:
117
+ try:
118
+ buffer.extend(self._queue.get_nowait())
119
+ except queue.Empty:
120
+ break
121
+ break
122
+ return bytes(buffer) or None
123
+
124
+ def describe(self) -> dict:
125
+ out = super().describe()
126
+ out.update(
127
+ {
128
+ "output_device": self.output_device,
129
+ "input_device": self.input_device,
130
+ "rate": self.rate,
131
+ }
132
+ )
133
+ return out
134
+
135
+ def close(self) -> None:
136
+ for stream in (getattr(self, "_in", None), getattr(self, "_out", None)):
137
+ if stream is None:
138
+ continue
139
+ try:
140
+ stream.stop()
141
+ stream.close()
142
+ except Exception: # pragma: no cover
143
+ pass
btsh/auto.py ADDED
@@ -0,0 +1,443 @@
1
+ """Zero-flag autoconfiguration.
2
+
3
+ ``btsh`` with no argument should be enough: find the best link that actually
4
+ answers, remember it, and wire the machine into Hermes as an MCP server. Every
5
+ probe runs in a child process, so a link that blocks or crashes (a FIFO nobody
6
+ writes to, a BLE adapter that hangs) can never wedge the caller.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import shutil
14
+ import subprocess
15
+ import sys
16
+ import time
17
+ from dataclasses import dataclass, field
18
+ from pathlib import Path
19
+
20
+ CACHE_PATH = "~/.btsh/auto.json"
21
+ LOG_PATH = "~/.btsh/auto.log"
22
+ IDENTITY_PATH = "~/.btsh/identity"
23
+ KEY_PATH = "~/.btsh.key"
24
+ FIFO_DIR = "~/.cache/btsh/fifos"
25
+ DEFAULT_PORT = 7878
26
+ PROBE_COMMAND = "echo btsh-auto-ok"
27
+ PROBE_MARK = "btsh-auto-ok"
28
+ # Advertised names that look like the btsh hub; the Android app can be renamed.
29
+ BLE_HINTS = ("btsh", "redmi", "buds", "pixel", "galaxy", "phone")
30
+ HERMES_SERVER = "btsh"
31
+ HERMES_ARGS = ["auto", "--mcp"]
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class Link:
36
+ """A way to reach the peer, with the flags that describe it."""
37
+
38
+ transport: str
39
+ options: dict = field(default_factory=dict)
40
+ source: str = "probe"
41
+
42
+ @property
43
+ def label(self) -> str:
44
+ if self.transport == "tcp":
45
+ return f"tcp {self.options.get('host')}:{self.options.get('port', DEFAULT_PORT)}"
46
+ if self.transport == "ble":
47
+ return f"ble {self.options.get('ble_name') or self.options.get('ble_address')}"
48
+ if self.transport == "fifo":
49
+ return f"fifo {self.options.get('fifo_dir')}"
50
+ return self.transport
51
+
52
+ def flags(self) -> list[str]:
53
+ flags = ["--transport", self.transport]
54
+ if self.transport == "tcp":
55
+ flags += ["--host", str(self.options["host"])]
56
+ flags += ["--port", str(self.options.get("port", DEFAULT_PORT))]
57
+ elif self.transport == "ble":
58
+ if self.options.get("ble_address"):
59
+ flags += ["--ble-address", self.options["ble_address"]]
60
+ elif self.options.get("ble_name"):
61
+ flags += ["--ble-name", self.options["ble_name"]]
62
+ elif self.transport == "fifo":
63
+ flags += ["--fifo-dir", str(self.options.get("fifo_dir", FIFO_DIR))]
64
+ if self.options.get("codec"):
65
+ flags += ["--codec", str(self.options["codec"])]
66
+ return flags
67
+
68
+ def as_dict(self) -> dict:
69
+ return {"transport": self.transport, "options": dict(self.options), "source": self.source}
70
+
71
+
72
+ @dataclass
73
+ class Solution:
74
+ link: Link
75
+ crypto: str
76
+ key: str | None
77
+ rtt_ms: float
78
+ attempts: list
79
+
80
+
81
+ # --------------------------------------------------------------------------- cache
82
+
83
+
84
+ def cache_file(env: dict | None = None) -> Path:
85
+ env = dict(os.environ if env is None else env)
86
+ return Path(os.path.expanduser(env.get("BTSH_CACHE", CACHE_PATH)))
87
+
88
+
89
+ def load_cache(env: dict | None = None) -> dict:
90
+ path = cache_file(env)
91
+ try:
92
+ data = json.loads(path.read_text(encoding="utf-8"))
93
+ except (OSError, json.JSONDecodeError):
94
+ return {}
95
+ return data if isinstance(data, dict) else {}
96
+
97
+
98
+ def save_cache(link: Link, crypto: str, env: dict | None = None) -> Path:
99
+ env = dict(os.environ if env is None else env)
100
+ path = cache_file(env)
101
+ path.parent.mkdir(parents=True, exist_ok=True)
102
+ payload = {"link": link.as_dict(), "crypto": crypto, "saved_at": int(time.time())}
103
+ path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
104
+ return path
105
+
106
+
107
+ # ---------------------------------------------------------------------------- log
108
+
109
+
110
+ def log_file(env: dict | None = None) -> Path:
111
+ env = dict(os.environ if env is None else env)
112
+ return Path(os.path.expanduser(env.get("BTSH_LOG", LOG_PATH)))
113
+
114
+
115
+ def log_event(event: str, payload: dict, env: dict | None = None) -> Path | None:
116
+ """Append one JSON line to the decision log. Never raises."""
117
+ path = log_file(env)
118
+ record = {"at": time.strftime("%Y-%m-%dT%H:%M:%S"), "event": event, **payload}
119
+ try:
120
+ path.parent.mkdir(parents=True, exist_ok=True)
121
+ if path.exists() and path.stat().st_size > 1_000_000:
122
+ kept = path.read_text(encoding="utf-8").splitlines()[-500:]
123
+ path.write_text("\n".join(kept) + "\n", encoding="utf-8")
124
+ with open(path, "a", encoding="utf-8") as handle:
125
+ handle.write(json.dumps(record, sort_keys=True) + "\n")
126
+ except OSError:
127
+ return None
128
+ return path
129
+
130
+
131
+ def line_for(record: dict, chosen: bool = False) -> str:
132
+ link = f"{record['link']} ({record.get('source', 'probe')})"
133
+ verdict = "ok" if record.get("ok") else (record.get("error") or "failed")
134
+ suffix = " <- chosen" if chosen else ""
135
+ return f"{link:<34} {record.get('crypto', ''):<7} {verdict:<44} {record.get('ms', 0):>7.0f} ms{suffix}"
136
+
137
+
138
+ def trace(attempts: list[dict], solution: Solution | None, env: dict | None = None) -> Path | None:
139
+ """Write every candidate and the verdict to the log, one line per attempt."""
140
+ written = None
141
+ for index, record in enumerate(attempts, start=1):
142
+ chosen = bool(solution and solution.link.label == record["link"] and solution.crypto == record["crypto"])
143
+ written = log_event("probe", {"n": index, **record, "chosen": chosen}, env)
144
+ log_event(
145
+ "resolved",
146
+ {
147
+ "chosen": None
148
+ if solution is None
149
+ else {"link": solution.link.as_dict(), "crypto": solution.crypto, "rtt_ms": solution.rtt_ms},
150
+ "attempts": len(attempts),
151
+ },
152
+ env,
153
+ )
154
+ return written
155
+
156
+
157
+ # ---------------------------------------------------------------------- discovery
158
+
159
+
160
+ def _fifos_ready(directory: str) -> bool:
161
+ return all(
162
+ os.path.exists(os.path.join(directory, name))
163
+ for name in ("client-to-server.fifo", "server-to-client.fifo")
164
+ )
165
+
166
+
167
+ def candidates(
168
+ env: dict | None = None,
169
+ cache: dict | None = None,
170
+ *,
171
+ fifo_dir: str = FIFO_DIR,
172
+ port: int = DEFAULT_PORT,
173
+ hosts: tuple = (),
174
+ ble_names: tuple = (),
175
+ ) -> list[Link]:
176
+ """Links worth trying, cheapest and most likely first, without duplicates."""
177
+ env = dict(os.environ if env is None else env)
178
+ cache = load_cache(env) if cache is None else cache
179
+ links: list[Link] = []
180
+ seen: set = set()
181
+
182
+ def add(link: Link) -> None:
183
+ key = (link.transport, tuple(sorted(link.options.items())))
184
+ if key not in seen:
185
+ seen.add(key)
186
+ links.append(link)
187
+
188
+ # 1. whatever worked last time
189
+ cached = cache.get("link") or {}
190
+ if cached.get("transport") in ("tcp", "ble", "fifo"):
191
+ options = dict(cached.get("options") or {})
192
+ if cached["transport"] == "fifo" and not _fifos_ready(options.get("fifo_dir", fifo_dir)):
193
+ options = {}
194
+ if options:
195
+ add(Link(cached["transport"], options, "cache"))
196
+
197
+ # 2. a shell server already listening on this host
198
+ directory = os.path.expanduser(env.get("BTSH_FIFO_DIR") or fifo_dir)
199
+ if _fifos_ready(directory):
200
+ add(Link("fifo", {"fifo_dir": directory}, "local"))
201
+
202
+ # 3. an explicit hub, then the usual suspects on the local network
203
+ explicit = env.get("BTSH_HOST")
204
+ hub_port = int(env.get("BTSH_PORT") or port)
205
+ if explicit:
206
+ add(Link("tcp", {"host": explicit, "port": hub_port}, "env"))
207
+ for host in hosts or ("127.0.0.1",):
208
+ add(Link("tcp", {"host": host, "port": hub_port}, "local"))
209
+
210
+ # 4. the Android app over BLE, by explicit name first, then advertised ones
211
+ named = [name for name in (env.get("BTSH_BLE"), *ble_names) if name]
212
+ for name in named:
213
+ add(Link("ble", {"ble_name": name}, "env"))
214
+ for name in _advertised(named):
215
+ add(Link("ble", {"ble_name": name}, "scan"))
216
+ return links
217
+
218
+
219
+ def _advertised(avoid: list[str], timeout: float = 8.0) -> list[str]:
220
+ """Names of nearby BLE peripherals that look like a btsh hub."""
221
+ try:
222
+ from . import ble
223
+
224
+ found = ble.scan(timeout)
225
+ except Exception: # noqa: BLE001 - no adapter, no permission, no D-Bus
226
+ return []
227
+ lowered = {name.lower() for name in avoid}
228
+ names = []
229
+ for device in found:
230
+ name = (device.get("name") or "").strip()
231
+ if not name or name.lower() in lowered:
232
+ continue
233
+ if any(hint in name.lower() for hint in BLE_HINTS):
234
+ names.append(name)
235
+ return names
236
+
237
+
238
+ def crypto_order(transport: str, key: str | None, env: dict | None = None) -> list[str]:
239
+ """Handshake modes to try, most appropriate first."""
240
+ env = dict(os.environ if env is None else env)
241
+ has_key = bool(key and os.path.exists(os.path.expanduser(key)))
242
+ if transport == "ble": # the Android app speaks the pre-shared key handshake
243
+ order = ["psk", "sealed", "none"] if has_key else ["sealed", "none"]
244
+ else:
245
+ order = ["sealed", "psk", "none"] if has_key else ["sealed", "none"]
246
+ return order
247
+
248
+
249
+ # ------------------------------------------------------------------------- probing
250
+
251
+
252
+ def probe(
253
+ link: Link,
254
+ crypto: str,
255
+ *,
256
+ key: str | None = None,
257
+ identity: str = IDENTITY_PATH,
258
+ timeout: float = 40.0,
259
+ command: list[str] | None = None,
260
+ ) -> dict:
261
+ """Run one probe in a child process so a stuck link cannot block us."""
262
+ command = command or [sys.executable, "-m", "btsh"]
263
+ flags = [*command, "_probe", *link.flags(), "--crypto", crypto, "--identity", identity]
264
+ if key and os.path.exists(os.path.expanduser(key)):
265
+ flags += ["--key", key]
266
+ started = time.monotonic()
267
+ try:
268
+ done = subprocess.run(flags, capture_output=True, text=True, timeout=timeout)
269
+ except subprocess.TimeoutExpired:
270
+ return {"ok": False, "error": f"timeout after {timeout:.0f}s", "ms": (time.monotonic() - started) * 1000}
271
+ except OSError as exc:
272
+ return {"ok": False, "error": f"cannot start probe: {exc}", "ms": 0.0}
273
+ answer = _last_json(done.stdout)
274
+ if answer is None:
275
+ detail = (done.stderr or done.stdout or "").strip().splitlines()
276
+ return {
277
+ "ok": False,
278
+ "error": (detail[-1] if detail else f"probe exited {done.returncode}"),
279
+ "ms": (time.monotonic() - started) * 1000,
280
+ }
281
+ answer.setdefault("ms", (time.monotonic() - started) * 1000)
282
+ return answer
283
+
284
+
285
+ def _last_json(text: str) -> dict | None:
286
+ for line in reversed((text or "").strip().splitlines()):
287
+ line = line.strip()
288
+ if not line.startswith("{"):
289
+ continue
290
+ try:
291
+ value = json.loads(line)
292
+ except json.JSONDecodeError:
293
+ continue
294
+ if isinstance(value, dict):
295
+ return value
296
+ return None
297
+
298
+
299
+ def resolve(
300
+ links: list[Link],
301
+ *,
302
+ key: str | None = KEY_PATH,
303
+ identity: str = IDENTITY_PATH,
304
+ prober=probe,
305
+ timeout: float = 40.0,
306
+ on_try=None,
307
+ ) -> tuple[Solution | None, list[dict]]:
308
+ """First link and handshake mode that actually answer win."""
309
+ attempts: list[dict] = []
310
+ for link in links:
311
+ for crypto in crypto_order(link.transport, key):
312
+ answer = prober(link, crypto, key=key, identity=identity, timeout=timeout)
313
+ record = {
314
+ "link": link.label,
315
+ "source": link.source,
316
+ "crypto": crypto,
317
+ "ok": bool(answer.get("ok")),
318
+ "ms": round(float(answer.get("ms") or 0), 1),
319
+ "error": answer.get("error"),
320
+ }
321
+ attempts.append(record)
322
+ if on_try:
323
+ on_try(record)
324
+ if record["ok"]:
325
+ return Solution(link, crypto, key, record["ms"], attempts), attempts
326
+ return None, attempts
327
+
328
+
329
+ # ------------------------------------------------------------------- hermes config
330
+
331
+
332
+ def hermes_config(env: dict | None = None) -> Path:
333
+ env = dict(os.environ if env is None else env)
334
+ home = env.get("HERMES_CONFIG") or os.path.join(env.get("HERMES_HOME") or "~/.hermes", "config.yaml")
335
+ return Path(os.path.expanduser(home))
336
+
337
+
338
+ def hermes_entry() -> tuple[str, list[str]]:
339
+ """How Hermes should start us: one program token plus its arguments."""
340
+ candidate = shutil.which("btsh")
341
+ if not candidate:
342
+ sibling = Path(sys.executable).with_name("btsh")
343
+ if sibling.exists():
344
+ candidate = str(sibling)
345
+ if candidate:
346
+ return candidate, list(HERMES_ARGS)
347
+ return sys.executable, ["-m", "btsh", *HERMES_ARGS]
348
+
349
+
350
+ def hermes_command() -> str:
351
+ """The program part only, kept for callers that want a single string."""
352
+ return hermes_entry()[0]
353
+
354
+
355
+ def _yaml_scalar(value: str) -> str:
356
+ if value and all(ch.isalnum() or ch in "._-/\\: " for ch in value) and not value[0] in "-?&*!|>%@`":
357
+ return value if " " not in value and ":" not in value else f"'{value}'"
358
+ return "'" + value.replace("'", "''") + "'"
359
+
360
+
361
+ def server_block(
362
+ command: str, indent: str = " ", server: str = HERMES_SERVER, args: list[str] | None = None, timeout: int = 300
363
+ ) -> list[str]:
364
+ words = HERMES_ARGS if args is None else list(args)
365
+ rendered = ", ".join(_yaml_scalar(part) for part in words)
366
+ return [
367
+ f"{indent}{server}:",
368
+ f"{indent} command: {_yaml_scalar(command)}",
369
+ f"{indent} args: [{rendered}]",
370
+ f"{indent} enabled: true",
371
+ f"{indent} timeout: {timeout}",
372
+ ]
373
+
374
+
375
+ def register(text: str, command: str, *, server: str = HERMES_SERVER, args: list[str] | None = None) -> tuple[str, bool]:
376
+ """Insert or refresh our MCP server in a Hermes config, leaving the rest alone."""
377
+ block = server_block(command, server=server, args=args)
378
+ lines = text.splitlines()
379
+ head = None
380
+ for index, line in enumerate(lines):
381
+ if line.rstrip() == "mcp_servers:":
382
+ head = index
383
+ break
384
+ if head is None:
385
+ body = text.rstrip("\n")
386
+ prefix = [body, ""] if body else []
387
+ updated = "\n".join([*prefix, "mcp_servers:", *block[1:]]) + "\n"
388
+ return updated, True
389
+
390
+ end = len(lines)
391
+ for index in range(head + 1, len(lines)):
392
+ line = lines[index]
393
+ if line.strip() and not line.startswith((" ", "\t")):
394
+ end = index
395
+ break
396
+
397
+ start = None
398
+ for index in range(head + 1, end):
399
+ line = lines[index]
400
+ if line.startswith(" ") and not line.startswith(" ") and line.strip().startswith(f"{server}:"):
401
+ start = index
402
+ break
403
+
404
+ if start is None:
405
+ new_lines = [*lines[: head + 1], *block, *lines[head + 1 :]]
406
+ return "\n".join(new_lines) + "\n", True
407
+
408
+ stop = start + 1
409
+ while stop < end and (not lines[stop].strip() or lines[stop].startswith(" ")):
410
+ stop += 1
411
+ if lines[start:stop] == block:
412
+ return text, False
413
+ return "\n".join([*lines[:start], *block, *lines[stop:]]) + "\n", True
414
+
415
+
416
+ def write_hermes(
417
+ command: str, *, args: list[str] | None = None, env: dict | None = None, server: str = HERMES_SERVER
418
+ ) -> dict:
419
+ """Register the server on disk. Returns what happened, never raises."""
420
+ path = hermes_config(env)
421
+ if not path.exists():
422
+ return {
423
+ "written": False,
424
+ "path": str(path),
425
+ "server": server,
426
+ "reason": "no Hermes config",
427
+ "block": server_block(command, server=server, args=args),
428
+ }
429
+ try:
430
+ original = path.read_text(encoding="utf-8")
431
+ except OSError as exc:
432
+ return {"written": False, "path": str(path), "server": server, "reason": f"cannot read: {exc}"}
433
+ updated, changed = register(original, command, server=server, args=args)
434
+ if not changed:
435
+ return {"written": False, "path": str(path), "server": server, "reason": "already registered", "changed": False}
436
+ backup = path.with_suffix(path.suffix + ".btsh.bak")
437
+ try:
438
+ if not backup.exists():
439
+ backup.write_text(original, encoding="utf-8")
440
+ path.write_text(updated, encoding="utf-8")
441
+ except OSError as exc:
442
+ return {"written": False, "path": str(path), "server": server, "reason": f"cannot write: {exc}"}
443
+ return {"written": True, "path": str(path), "server": server, "backup": str(backup), "changed": True}