datap-0.6 0.6.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,51 @@
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
+ # The project has been published under several names; take whichever one
10
+ # is actually installed instead of guessing a single distribution name.
11
+ for _name in ("datap", "datap-0.6", "datap-0.5", "datap-0.4", "datap-0.3"):
12
+ try:
13
+ __version__ = _distribution_version(_name)
14
+ break
15
+ except PackageNotFoundError:
16
+ continue
17
+ else: # pragma: no cover - defensive, the loop always ends somewhere
18
+ raise PackageNotFoundError
19
+ except PackageNotFoundError: # running from a source tree, keep in sync with pyproject.toml
20
+ __version__ = "0.6.0"
21
+
22
+ from .channel import Channel, ChannelError # noqa: E402
23
+ from .client import Client # noqa: E402
24
+ from .server import ShellConfig, ShellServer, execute # noqa: E402
25
+ from .session import AuthError, Session # noqa: E402
26
+ from .transport import ( # noqa: E402
27
+ AcousticTransport,
28
+ CodecTransport,
29
+ FifoTransport,
30
+ LoopbackTransport,
31
+ Transport,
32
+ TransportError,
33
+ )
34
+
35
+ __all__ = [
36
+ "__version__",
37
+ "AcousticTransport",
38
+ "AuthError",
39
+ "Channel",
40
+ "ChannelError",
41
+ "Client",
42
+ "CodecTransport",
43
+ "FifoTransport",
44
+ "LoopbackTransport",
45
+ "Session",
46
+ "ShellConfig",
47
+ "ShellServer",
48
+ "Transport",
49
+ "TransportError",
50
+ "execute",
51
+ ]
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,478 @@
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
+ PROBE_COMMAND = "echo btsh-auto-ok"
26
+ PROBE_MARK = "btsh-auto-ok"
27
+ # Advertised names that may hide a hub whose advertisement drops the service
28
+ # UUID; every one of them is confirmed over GATT before being tried.
29
+ BLE_HINTS = ("btsh", "airpods", "iphone", "phone", "pixel", "galaxy", "redmi", "xiaomi", "samsung")
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 == "ble":
45
+ name = self.options.get("ble_name")
46
+ address = self.options.get("ble_address")
47
+ return f"ble {name or address}" if name else f"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 == "ble":
55
+ if self.options.get("ble_address"):
56
+ flags += ["--ble-address", self.options["ble_address"]]
57
+ elif self.options.get("ble_name"):
58
+ flags += ["--ble-name", self.options["ble_name"]]
59
+ elif self.transport == "fifo":
60
+ flags += ["--fifo-dir", str(self.options.get("fifo_dir", FIFO_DIR))]
61
+ if self.options.get("codec"):
62
+ flags += ["--codec", str(self.options["codec"])]
63
+ return flags
64
+
65
+ def as_dict(self) -> dict:
66
+ return {"transport": self.transport, "options": dict(self.options), "source": self.source}
67
+
68
+
69
+ @dataclass
70
+ class Solution:
71
+ link: Link
72
+ crypto: str
73
+ key: str | None
74
+ rtt_ms: float
75
+ attempts: list
76
+
77
+
78
+ # --------------------------------------------------------------------------- cache
79
+
80
+
81
+ def cache_file(env: dict | None = None) -> Path:
82
+ env = dict(os.environ if env is None else env)
83
+ return Path(os.path.expanduser(env.get("BTSH_CACHE", CACHE_PATH)))
84
+
85
+
86
+ def load_cache(env: dict | None = None) -> dict:
87
+ path = cache_file(env)
88
+ try:
89
+ data = json.loads(path.read_text(encoding="utf-8"))
90
+ except (OSError, json.JSONDecodeError):
91
+ return {}
92
+ return data if isinstance(data, dict) else {}
93
+
94
+
95
+ def save_cache(link: Link, crypto: str, env: dict | None = None) -> Path:
96
+ env = dict(os.environ if env is None else env)
97
+ path = cache_file(env)
98
+ path.parent.mkdir(parents=True, exist_ok=True)
99
+ payload = {"link": link.as_dict(), "crypto": crypto, "saved_at": int(time.time())}
100
+ path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
101
+ return path
102
+
103
+
104
+ # ---------------------------------------------------------------------------- log
105
+
106
+
107
+ def log_file(env: dict | None = None) -> Path:
108
+ env = dict(os.environ if env is None else env)
109
+ return Path(os.path.expanduser(env.get("BTSH_LOG", LOG_PATH)))
110
+
111
+
112
+ def log_event(event: str, payload: dict, env: dict | None = None) -> Path | None:
113
+ """Append one JSON line to the decision log. Never raises."""
114
+ path = log_file(env)
115
+ record = {"at": time.strftime("%Y-%m-%dT%H:%M:%S"), "event": event, **payload}
116
+ try:
117
+ path.parent.mkdir(parents=True, exist_ok=True)
118
+ if path.exists() and path.stat().st_size > 1_000_000:
119
+ kept = path.read_text(encoding="utf-8").splitlines()[-500:]
120
+ path.write_text("\n".join(kept) + "\n", encoding="utf-8")
121
+ with open(path, "a", encoding="utf-8") as handle:
122
+ handle.write(json.dumps(record, sort_keys=True) + "\n")
123
+ except OSError:
124
+ return None
125
+ return path
126
+
127
+
128
+ def candidates_menu(links: list[Link], title: str = "candidates, in the order they will be tried:") -> list[str]:
129
+ """Numbered candidate list, the same shape the wizard shows."""
130
+ lines = [title]
131
+ for index, link in enumerate(links, start=1):
132
+ lines.append(f" {index:>2} {link.label:<30} ({link.source})")
133
+ return lines
134
+
135
+
136
+ def line_for(record: dict, chosen: bool = False) -> str:
137
+ link = f"{record['link']} ({record.get('source', 'probe')})"
138
+ verdict = "ok" if record.get("ok") else (record.get("error") or "failed")
139
+ suffix = " <- chosen" if chosen else ""
140
+ return f"{link:<34} {record.get('crypto', ''):<7} {verdict:<44} {record.get('ms', 0):>7.0f} ms{suffix}"
141
+
142
+
143
+ def trace(attempts: list[dict], solution: Solution | None, env: dict | None = None) -> Path | None:
144
+ """Write every candidate and the verdict to the log, one line per attempt."""
145
+ written = None
146
+ for index, record in enumerate(attempts, start=1):
147
+ chosen = bool(solution and solution.link.label == record["link"] and solution.crypto == record["crypto"])
148
+ written = log_event("probe", {"n": index, **record, "chosen": chosen}, env)
149
+ log_event(
150
+ "resolved",
151
+ {
152
+ "chosen": None
153
+ if solution is None
154
+ else {"link": solution.link.as_dict(), "crypto": solution.crypto, "rtt_ms": solution.rtt_ms},
155
+ "attempts": len(attempts),
156
+ },
157
+ env,
158
+ )
159
+ return written
160
+
161
+
162
+ # ---------------------------------------------------------------------- discovery
163
+
164
+
165
+ def candidates(
166
+ env: dict | None = None,
167
+ cache: dict | None = None,
168
+ *,
169
+ ble_names: tuple = (),
170
+ scan: bool = True,
171
+ scan_timeout: float = 8.0,
172
+ report: dict | None = None,
173
+ ) -> list[Link]:
174
+ """BLE links worth trying: a fresh scan first, the remembered one as a fallback.
175
+
176
+ Bluetooth is the only link ``btsh`` looks for: the shell rides on a codec,
177
+ not on IP, so a TCP hub is never a candidate. macOS hands out a new
178
+ CoreBluetooth UUID to the same phone after a while, so a cached address is
179
+ only worth a try when the scan could not run or did not find the hub.
180
+ """
181
+ env = dict(os.environ if env is None else env)
182
+ cache = load_cache(env) if cache is None else cache
183
+ links: list[Link] = []
184
+ seen: set = set()
185
+
186
+ def add(link: Link) -> None:
187
+ if link.transport == "ble": # one entry per peripheral, cache or scan
188
+ key = ("ble", (link.options.get("ble_address") or link.options.get("ble_name") or "").lower())
189
+ else:
190
+ key = (link.transport, tuple(sorted(link.options.items())))
191
+ if key not in seen:
192
+ seen.add(key)
193
+ links.append(link)
194
+
195
+ cached = cache.get("link") or {}
196
+ cached_link = None
197
+ if cached.get("transport") == "ble":
198
+ options = {name: value for name, value in (cached.get("options") or {}).items() if value}
199
+ if options.get("ble_address") or options.get("ble_name"):
200
+ cached_link = Link("ble", options, "cache")
201
+
202
+ # 1. names asked for explicitly, by flag or environment
203
+ named = [name for name in (env.get("BTSH_BLE"), *ble_names) if name]
204
+ for name in named:
205
+ add(Link("ble", {"ble_name": name}, "env"))
206
+
207
+ # 2. a fresh scan, every run: this is what proves the hub is really there
208
+ live: set = set()
209
+ if scan:
210
+ try:
211
+ hubs = _advertised(named, scan_timeout)
212
+ except Exception as exc: # noqa: BLE001 - permissions, no adapter, no D-Bus
213
+ if report is not None:
214
+ report["scan"] = {"ok": False, "error": str(exc), "found": 0}
215
+ else:
216
+ if report is not None:
217
+ report["scan"] = {"ok": True, "error": None, "found": len(hubs)}
218
+ for device in hubs:
219
+ live.add(str(device["address"]).lower())
220
+ options = {"ble_address": device["address"]}
221
+ if device.get("name"):
222
+ options["ble_name"] = device["name"]
223
+ add(Link("ble", options, "scan"))
224
+ elif report is not None:
225
+ report["scan"] = {"ok": True, "error": None, "found": 0, "skipped": True}
226
+
227
+ # 3. the remembered hub, only if the scan did not already list it
228
+ if cached_link is not None:
229
+ address = str(cached_link.options.get("ble_address") or "").lower()
230
+ if not live or not address or address in live:
231
+ add(cached_link)
232
+ return links
233
+
234
+
235
+ def _advertised(avoid: list[str], timeout: float = 8.0) -> list[dict]:
236
+ """Nearby BLE peripherals that look like a btsh hub.
237
+
238
+ A device counts when it advertises the btsh GATT service; without that hint
239
+ (some Android builds hide the UUID in the advertisement) a name that looks
240
+ like a phone or the project itself is enough. Raises when the scan itself
241
+ cannot run: no adapter, denied permission, no D-Bus.
242
+ """
243
+ from . import ble
244
+
245
+ found = ble.scan(timeout)
246
+ lowered = {name.lower() for name in avoid}
247
+ hubs = []
248
+ unconfirmed = []
249
+ for device in found:
250
+ name = (device.get("name") or "").strip()
251
+ if not name or name.lower() in lowered:
252
+ continue
253
+ services = {str(uuid).lower() for uuid in device.get("services") or ()}
254
+ if ble.SERVICE_UUID.lower() in services:
255
+ hubs.append({**device, "match": "service"})
256
+ elif any(hint in name.lower() for hint in BLE_HINTS):
257
+ unconfirmed.append({**device, "match": "name"})
258
+ # A name is a guess: a speaker called "buds" answers a GATT connection but
259
+ # serves no btsh service. Connect once and look before calling it a hub.
260
+ for device in unconfirmed:
261
+ if ble.confirm(device["address"]):
262
+ hubs.append(device)
263
+ # A hub that advertises the service beats one that merely has a matching name.
264
+ hubs.sort(key=lambda device: (device["match"] != "service", device.get("rssi") is None, -(device.get("rssi") or -999)))
265
+ return hubs
266
+
267
+
268
+ def crypto_order(transport: str, key: str | None, env: dict | None = None) -> list[str]:
269
+ """Handshake modes to try, most appropriate first."""
270
+ env = dict(os.environ if env is None else env)
271
+ has_key = bool(key and os.path.exists(os.path.expanduser(key)))
272
+ if transport == "ble": # the Android app speaks the pre-shared key handshake
273
+ order = ["psk", "sealed", "none"] if has_key else ["sealed", "none"]
274
+ else:
275
+ order = ["sealed", "psk", "none"] if has_key else ["sealed", "none"]
276
+ return order
277
+
278
+
279
+ # ------------------------------------------------------------------------- probing
280
+
281
+
282
+ def probe(
283
+ link: Link,
284
+ crypto: str,
285
+ *,
286
+ key: str | None = None,
287
+ identity: str = IDENTITY_PATH,
288
+ timeout: float = 40.0,
289
+ command: list[str] | None = None,
290
+ ) -> dict:
291
+ """Run one probe in a child process so a stuck link cannot block us."""
292
+ command = command or [sys.executable, "-m", "btsh"]
293
+ flags = [*command, "_probe", *link.flags(), "--crypto", crypto, "--identity", identity]
294
+ if key and os.path.exists(os.path.expanduser(key)):
295
+ flags += ["--key", key]
296
+ started = time.monotonic()
297
+ try:
298
+ done = subprocess.run(flags, capture_output=True, text=True, timeout=timeout)
299
+ except subprocess.TimeoutExpired:
300
+ return {"ok": False, "error": f"timeout after {timeout:.0f}s", "ms": (time.monotonic() - started) * 1000}
301
+ except OSError as exc:
302
+ return {"ok": False, "error": f"cannot start probe: {exc}", "ms": 0.0}
303
+ answer = _last_json(done.stdout)
304
+ if answer is None:
305
+ detail = (done.stderr or done.stdout or "").strip().splitlines()
306
+ return {
307
+ "ok": False,
308
+ "error": (detail[-1] if detail else f"probe exited {done.returncode}"),
309
+ "ms": (time.monotonic() - started) * 1000,
310
+ }
311
+ answer.setdefault("ms", (time.monotonic() - started) * 1000)
312
+ return answer
313
+
314
+
315
+ def _last_json(text: str) -> dict | None:
316
+ for line in reversed((text or "").strip().splitlines()):
317
+ line = line.strip()
318
+ if not line.startswith("{"):
319
+ continue
320
+ try:
321
+ value = json.loads(line)
322
+ except json.JSONDecodeError:
323
+ continue
324
+ if isinstance(value, dict):
325
+ return value
326
+ return None
327
+
328
+
329
+ def resolve(
330
+ links: list[Link],
331
+ *,
332
+ key: str | None = KEY_PATH,
333
+ identity: str = IDENTITY_PATH,
334
+ prober=probe,
335
+ timeout: float = 40.0,
336
+ on_try=None,
337
+ ) -> tuple[Solution | None, list[dict]]:
338
+ """First link and handshake mode that actually answer win."""
339
+ attempts: list[dict] = []
340
+ for link in links:
341
+ for crypto in crypto_order(link.transport, key):
342
+ # A peer that answers, but with the wrong thing, is usually a hub
343
+ # still finishing its previous session: one more try is cheap.
344
+ for _ in range(2):
345
+ answer = prober(link, crypto, key=key, identity=identity, timeout=timeout)
346
+ record = {
347
+ "link": link.label,
348
+ "source": link.source,
349
+ "crypto": crypto,
350
+ "ok": bool(answer.get("ok")),
351
+ "ms": round(float(answer.get("ms") or 0), 1),
352
+ "error": answer.get("error"),
353
+ }
354
+ attempts.append(record)
355
+ if on_try:
356
+ on_try(record)
357
+ if record["ok"]:
358
+ return Solution(link, crypto, key, record["ms"], attempts), attempts
359
+ if not str(record["error"] or "").startswith("answered"):
360
+ break # a hard failure will not improve on a retry
361
+ return None, attempts
362
+
363
+
364
+ # ------------------------------------------------------------------- hermes config
365
+
366
+
367
+ def hermes_config(env: dict | None = None) -> Path:
368
+ env = dict(os.environ if env is None else env)
369
+ home = env.get("HERMES_CONFIG") or os.path.join(env.get("HERMES_HOME") or "~/.hermes", "config.yaml")
370
+ return Path(os.path.expanduser(home))
371
+
372
+
373
+ def hermes_entry() -> tuple[str, list[str]]:
374
+ """How Hermes should start us: one program token plus its arguments."""
375
+ candidate = shutil.which("btsh")
376
+ if not candidate:
377
+ sibling = Path(sys.executable).with_name("btsh")
378
+ if sibling.exists():
379
+ candidate = str(sibling)
380
+ if candidate:
381
+ return candidate, list(HERMES_ARGS)
382
+ return sys.executable, ["-m", "btsh", *HERMES_ARGS]
383
+
384
+
385
+ def hermes_command() -> str:
386
+ """The program part only, kept for callers that want a single string."""
387
+ return hermes_entry()[0]
388
+
389
+
390
+ def _yaml_scalar(value: str) -> str:
391
+ if value and all(ch.isalnum() or ch in "._-/\\: " for ch in value) and not value[0] in "-?&*!|>%@`":
392
+ return value if " " not in value and ":" not in value else f"'{value}'"
393
+ return "'" + value.replace("'", "''") + "'"
394
+
395
+
396
+ def server_block(
397
+ command: str, indent: str = " ", server: str = HERMES_SERVER, args: list[str] | None = None, timeout: int = 300
398
+ ) -> list[str]:
399
+ words = HERMES_ARGS if args is None else list(args)
400
+ rendered = ", ".join(_yaml_scalar(part) for part in words)
401
+ return [
402
+ f"{indent}{server}:",
403
+ f"{indent} command: {_yaml_scalar(command)}",
404
+ f"{indent} args: [{rendered}]",
405
+ f"{indent} enabled: true",
406
+ f"{indent} timeout: {timeout}",
407
+ ]
408
+
409
+
410
+ def register(text: str, command: str, *, server: str = HERMES_SERVER, args: list[str] | None = None) -> tuple[str, bool]:
411
+ """Insert or refresh our MCP server in a Hermes config, leaving the rest alone."""
412
+ block = server_block(command, server=server, args=args)
413
+ lines = text.splitlines()
414
+ head = None
415
+ for index, line in enumerate(lines):
416
+ if line.rstrip() == "mcp_servers:":
417
+ head = index
418
+ break
419
+ if head is None:
420
+ body = text.rstrip("\n")
421
+ prefix = [body, ""] if body else []
422
+ updated = "\n".join([*prefix, "mcp_servers:", *block[1:]]) + "\n"
423
+ return updated, True
424
+
425
+ end = len(lines)
426
+ for index in range(head + 1, len(lines)):
427
+ line = lines[index]
428
+ if line.strip() and not line.startswith((" ", "\t")):
429
+ end = index
430
+ break
431
+
432
+ start = None
433
+ for index in range(head + 1, end):
434
+ line = lines[index]
435
+ if line.startswith(" ") and not line.startswith(" ") and line.strip().startswith(f"{server}:"):
436
+ start = index
437
+ break
438
+
439
+ if start is None:
440
+ new_lines = [*lines[: head + 1], *block, *lines[head + 1 :]]
441
+ return "\n".join(new_lines) + "\n", True
442
+
443
+ stop = start + 1
444
+ while stop < end and (not lines[stop].strip() or lines[stop].startswith(" ")):
445
+ stop += 1
446
+ if lines[start:stop] == block:
447
+ return text, False
448
+ return "\n".join([*lines[:start], *block, *lines[stop:]]) + "\n", True
449
+
450
+
451
+ def write_hermes(
452
+ command: str, *, args: list[str] | None = None, env: dict | None = None, server: str = HERMES_SERVER
453
+ ) -> dict:
454
+ """Register the server on disk. Returns what happened, never raises."""
455
+ path = hermes_config(env)
456
+ if not path.exists():
457
+ return {
458
+ "written": False,
459
+ "path": str(path),
460
+ "server": server,
461
+ "reason": "no Hermes config",
462
+ "block": server_block(command, server=server, args=args),
463
+ }
464
+ try:
465
+ original = path.read_text(encoding="utf-8")
466
+ except OSError as exc:
467
+ return {"written": False, "path": str(path), "server": server, "reason": f"cannot read: {exc}"}
468
+ updated, changed = register(original, command, server=server, args=args)
469
+ if not changed:
470
+ return {"written": False, "path": str(path), "server": server, "reason": "already registered", "changed": False}
471
+ backup = path.with_suffix(path.suffix + ".btsh.bak")
472
+ try:
473
+ if not backup.exists():
474
+ backup.write_text(original, encoding="utf-8")
475
+ path.write_text(updated, encoding="utf-8")
476
+ except OSError as exc:
477
+ return {"written": False, "path": str(path), "server": server, "reason": f"cannot write: {exc}"}
478
+ return {"written": True, "path": str(path), "server": server, "backup": str(backup), "changed": True}