datap 0.1.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 +36 -0
- btsh/__main__.py +5 -0
- btsh/audio.py +143 -0
- btsh/ble.py +147 -0
- btsh/bt.py +90 -0
- btsh/channel.py +112 -0
- btsh/channels.py +119 -0
- btsh/cli.py +528 -0
- btsh/client.py +75 -0
- btsh/codec.py +120 -0
- btsh/crypto.py +233 -0
- btsh/framing.py +96 -0
- btsh/hub.py +266 -0
- btsh/mcp.py +213 -0
- btsh/modem.py +196 -0
- btsh/node.py +190 -0
- btsh/py.typed +0 -0
- btsh/server.py +194 -0
- btsh/session.py +187 -0
- btsh/transport.py +325 -0
- datap-0.1.0.dist-info/METADATA +207 -0
- datap-0.1.0.dist-info/RECORD +25 -0
- datap-0.1.0.dist-info/WHEEL +5 -0
- datap-0.1.0.dist-info/entry_points.txt +2 -0
- datap-0.1.0.dist-info/top_level.txt +1 -0
btsh/cli.py
ADDED
|
@@ -0,0 +1,528 @@
|
|
|
1
|
+
"""btsh command line."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import shutil
|
|
9
|
+
import socket
|
|
10
|
+
import sys
|
|
11
|
+
import threading
|
|
12
|
+
|
|
13
|
+
from . import __version__, audio, ble, bt, codec
|
|
14
|
+
from .channel import Channel, ChannelError
|
|
15
|
+
from .client import Client
|
|
16
|
+
from .server import ShellConfig, ShellServer
|
|
17
|
+
from .session import AuthError, Session
|
|
18
|
+
from .transport import (
|
|
19
|
+
AcousticTransport,
|
|
20
|
+
FifoTransport,
|
|
21
|
+
LoopbackTransport,
|
|
22
|
+
TransportError,
|
|
23
|
+
make_fifo_pair,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
DEFAULT_FIFO_DIR = os.path.join(os.path.expanduser("~"), ".cache", "btsh", "fifos")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _read_key(path: str | None) -> bytes | None:
|
|
30
|
+
if not path:
|
|
31
|
+
return None
|
|
32
|
+
with open(os.path.expanduser(path), "rb") as handle:
|
|
33
|
+
key = handle.read().strip()
|
|
34
|
+
if not key:
|
|
35
|
+
raise SystemExit(f"btsh: empty key file {path}")
|
|
36
|
+
return key
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _add_link_args(parser: argparse.ArgumentParser) -> None:
|
|
40
|
+
group = parser.add_argument_group("link")
|
|
41
|
+
group.add_argument(
|
|
42
|
+
"--transport",
|
|
43
|
+
choices=("fifo", "pw", "portaudio", "ble", "loopback"),
|
|
44
|
+
default="fifo",
|
|
45
|
+
help="fifo: two pipes on one host; pw: PipeWire; portaudio: Linux/macOS/Windows; ble: GATT",
|
|
46
|
+
)
|
|
47
|
+
group.add_argument("--fifo-dir", default=DEFAULT_FIFO_DIR, help="directory holding the two FIFOs")
|
|
48
|
+
group.add_argument("--target", help="PipeWire node to play into (pw transport)")
|
|
49
|
+
group.add_argument("--target-in", help="PipeWire node to record from (defaults to --target)")
|
|
50
|
+
group.add_argument("--output-device", help="PortAudio output device (index or name)")
|
|
51
|
+
group.add_argument("--input-device", help="PortAudio input device (index or name)")
|
|
52
|
+
group.add_argument("--ble-address", help="BLE peripheral MAC / UUID")
|
|
53
|
+
group.add_argument("--ble-name", help="BLE peripheral name to scan for")
|
|
54
|
+
group.add_argument("--codec", choices=("none", "sbc"), default="sbc", help="codec the acoustic link must survive")
|
|
55
|
+
group.add_argument("--key", help="file holding the pre-shared key (HMAC-SHA256 handshake)")
|
|
56
|
+
group.add_argument(
|
|
57
|
+
"--crypto",
|
|
58
|
+
choices=("sealed", "psk", "none"),
|
|
59
|
+
default="sealed",
|
|
60
|
+
help="sealed: X25519 + ChaCha20-Poly1305 per hop; psk: HMAC tag only; none: plaintext",
|
|
61
|
+
)
|
|
62
|
+
group.add_argument("--identity", default="~/.btsh/identity", help="X25519 identity file for sealed links")
|
|
63
|
+
group.add_argument("--retries", type=int, default=6)
|
|
64
|
+
group.add_argument("--ack-timeout", type=float, default=6.0)
|
|
65
|
+
group.add_argument("--verbose", action="store_true")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _build_transport(args, role: str):
|
|
69
|
+
"""Return (transport, channel mode)."""
|
|
70
|
+
if args.transport == "fifo":
|
|
71
|
+
directory = os.path.expanduser(args.fifo_dir)
|
|
72
|
+
c2s = os.path.join(directory, "client-to-server.fifo")
|
|
73
|
+
s2c = os.path.join(directory, "server-to-client.fifo")
|
|
74
|
+
if role == "server":
|
|
75
|
+
make_fifo_pair(directory)
|
|
76
|
+
return FifoTransport(in_path=c2s, out_path=s2c), "acoustic"
|
|
77
|
+
if not (os.path.exists(c2s) and os.path.exists(s2c)):
|
|
78
|
+
raise SystemExit(f"btsh: no FIFOs in {directory} (start 'btsh serve' first)")
|
|
79
|
+
return FifoTransport(in_path=s2c, out_path=c2s), "acoustic"
|
|
80
|
+
if args.transport == "loopback":
|
|
81
|
+
left, right = LoopbackTransport.pair()
|
|
82
|
+
return (right if role == "server" else left), "acoustic"
|
|
83
|
+
if args.transport == "pw":
|
|
84
|
+
node = args.target
|
|
85
|
+
if not node:
|
|
86
|
+
nodes = codec.bluez_nodes()
|
|
87
|
+
picked = codec.pick_node(nodes, "out")
|
|
88
|
+
if picked:
|
|
89
|
+
node = picked["node"]
|
|
90
|
+
if not node:
|
|
91
|
+
raise SystemExit("btsh: no Bluetooth audio node found; pass --target")
|
|
92
|
+
return AcousticTransport(node, args.target_in or node), "acoustic"
|
|
93
|
+
if args.transport == "portaudio":
|
|
94
|
+
return (
|
|
95
|
+
audio.PortAudioTransport(output_device=args.output_device, input_device=args.input_device),
|
|
96
|
+
"acoustic",
|
|
97
|
+
)
|
|
98
|
+
if args.transport == "ble":
|
|
99
|
+
if role == "server":
|
|
100
|
+
raise SystemExit(
|
|
101
|
+
"btsh: a BLE server cannot run in Python here; run the Android app (android/) as the server "
|
|
102
|
+
"and connect with 'btsh --transport ble --ble-name <name> exec ...'"
|
|
103
|
+
)
|
|
104
|
+
address = args.ble_address or (ble.find(args.ble_name) if args.ble_name else None)
|
|
105
|
+
if not address:
|
|
106
|
+
raise SystemExit("btsh: pass --ble-address or --ble-name")
|
|
107
|
+
return ble.BleTransport(address), "raw"
|
|
108
|
+
raise SystemExit(f"btsh: unknown transport {args.transport}")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _identity(args):
|
|
112
|
+
"""Load or create the X25519 identity used by sealed links."""
|
|
113
|
+
from .crypto import Identity
|
|
114
|
+
|
|
115
|
+
if getattr(args, "crypto", "sealed") != "sealed":
|
|
116
|
+
return None
|
|
117
|
+
path = os.path.expanduser(args.identity)
|
|
118
|
+
if os.path.exists(path):
|
|
119
|
+
return Identity.from_file(path)
|
|
120
|
+
identity = Identity()
|
|
121
|
+
identity.save(path)
|
|
122
|
+
print(f"btsh: new identity {identity.fingerprint} in {path}", file=sys.stderr)
|
|
123
|
+
return identity
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _channel(args, transport, mode: str = "acoustic") -> Channel:
|
|
127
|
+
return Channel(
|
|
128
|
+
transport,
|
|
129
|
+
codec=args.codec,
|
|
130
|
+
retries=args.retries,
|
|
131
|
+
ack_timeout=args.ack_timeout,
|
|
132
|
+
verbose=args.verbose,
|
|
133
|
+
mode=mode,
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def cmd_doctor(args) -> int:
|
|
138
|
+
report: dict = {
|
|
139
|
+
"version": __version__,
|
|
140
|
+
"ffmpeg": shutil.which(codec.FFMPEG),
|
|
141
|
+
"pw-play": shutil.which("pw-play"),
|
|
142
|
+
}
|
|
143
|
+
try:
|
|
144
|
+
report["devices"] = [{**device, "profiles": bt.profiles(bt.info(device["mac"]))} for device in bt.devices()]
|
|
145
|
+
except bt.BluetoothError as exc:
|
|
146
|
+
report["devices_error"] = str(exc)
|
|
147
|
+
try:
|
|
148
|
+
report["nodes"] = codec.bluez_nodes()
|
|
149
|
+
except codec.CodecError as exc:
|
|
150
|
+
report["nodes_error"] = str(exc)
|
|
151
|
+
try:
|
|
152
|
+
report["audio_devices"] = audio.list_devices()
|
|
153
|
+
except TransportError as exc:
|
|
154
|
+
report["audio_devices_error"] = str(exc)
|
|
155
|
+
if args.json:
|
|
156
|
+
print(json.dumps(report, indent=2))
|
|
157
|
+
return 0
|
|
158
|
+
print(f"btsh {report['version']}")
|
|
159
|
+
print(f"ffmpeg: {report['ffmpeg'] or 'missing'} pw-play: {report['pw-play'] or 'missing'}")
|
|
160
|
+
devices = report.get("devices") or []
|
|
161
|
+
if devices:
|
|
162
|
+
print("\nBluetooth devices:")
|
|
163
|
+
for device in devices:
|
|
164
|
+
flags = ",".join(name for name, ok in device["profiles"].items() if ok) or "no audio profile"
|
|
165
|
+
print(f" {device['mac']} {device['name']:<28} {flags}")
|
|
166
|
+
elif report.get("devices_error"):
|
|
167
|
+
print(f"devices: {report['devices_error']}")
|
|
168
|
+
nodes = report.get("nodes") or []
|
|
169
|
+
if nodes:
|
|
170
|
+
print("\nBlueZ audio nodes (negotiated codec):")
|
|
171
|
+
for node in nodes:
|
|
172
|
+
print(
|
|
173
|
+
f" {node['node']:<34} {node['media_class']:<14} {node['codec'] or '-':<6} "
|
|
174
|
+
f"{node['profile'] or '-'}"
|
|
175
|
+
)
|
|
176
|
+
audio_devices = report.get("audio_devices")
|
|
177
|
+
if audio_devices:
|
|
178
|
+
print("\nPortAudio devices (* = default):")
|
|
179
|
+
for device in audio_devices:
|
|
180
|
+
mark = []
|
|
181
|
+
if device["default_output"]:
|
|
182
|
+
mark.append("out")
|
|
183
|
+
if device["default_input"]:
|
|
184
|
+
mark.append("in")
|
|
185
|
+
print(
|
|
186
|
+
f" [{device['index']:>2}] {device['name'][:44]:<44} "
|
|
187
|
+
f"in={device['inputs']} out={device['outputs']} {'/'.join(mark)}"
|
|
188
|
+
)
|
|
189
|
+
elif report.get("audio_devices_error"):
|
|
190
|
+
print(f"portaudio: {report['audio_devices_error']}")
|
|
191
|
+
return 0
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def cmd_connect(args) -> int:
|
|
195
|
+
try:
|
|
196
|
+
output = bt.connect(args.device)
|
|
197
|
+
except bt.BluetoothError as exc:
|
|
198
|
+
print(f"btsh: {exc}", file=sys.stderr)
|
|
199
|
+
return 1
|
|
200
|
+
print(output)
|
|
201
|
+
try:
|
|
202
|
+
nodes = codec.bluez_nodes()
|
|
203
|
+
except codec.CodecError:
|
|
204
|
+
nodes = []
|
|
205
|
+
for node in nodes:
|
|
206
|
+
if node["media_class"] == "Audio/Sink":
|
|
207
|
+
print(f"play into: {node['node']} (codec {node['codec'] or 'unknown'})")
|
|
208
|
+
return 0
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def cmd_devices(args) -> int:
|
|
212
|
+
devices = audio.list_devices()
|
|
213
|
+
if args.json:
|
|
214
|
+
print(json.dumps(devices, indent=2))
|
|
215
|
+
return 0
|
|
216
|
+
for device in devices:
|
|
217
|
+
print(f"[{device['index']:>2}] {device['name']} in={device['inputs']} out={device['outputs']} {device['host_api']}")
|
|
218
|
+
return 0
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def cmd_scan(args) -> int:
|
|
222
|
+
found = ble.scan(args.timeout)
|
|
223
|
+
if args.json:
|
|
224
|
+
print(json.dumps(found, indent=2))
|
|
225
|
+
return 0
|
|
226
|
+
for device in found:
|
|
227
|
+
print(f"{device['address']} {device['name'] or '(no name)':<30} rssi={device['rssi']}")
|
|
228
|
+
return 0
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def cmd_serve(args) -> int:
|
|
232
|
+
key = _read_key(args.key)
|
|
233
|
+
transport, mode = _build_transport(args, "server")
|
|
234
|
+
channel = _channel(args, transport, mode)
|
|
235
|
+
session = Session(channel, key=key, identity=_identity(args), verbose=args.verbose)
|
|
236
|
+
config = ShellConfig.from_args(args.cwd, args.timeout, args.max_output, args.allow, args.deny)
|
|
237
|
+
server = ShellServer(session, config, verbose=args.verbose)
|
|
238
|
+
print(json.dumps({"listening": transport.describe(), "cwd": config.cwd, "auth": bool(key)}), flush=True)
|
|
239
|
+
try:
|
|
240
|
+
server.serve_forever()
|
|
241
|
+
except KeyboardInterrupt:
|
|
242
|
+
print("btsh: stopped", file=sys.stderr)
|
|
243
|
+
finally:
|
|
244
|
+
transport.close()
|
|
245
|
+
print(json.dumps({"served": server.served, **channel.describe()}), flush=True)
|
|
246
|
+
return 0
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def cmd_exec(args) -> int:
|
|
250
|
+
key = _read_key(args.key)
|
|
251
|
+
parts = list(args.command)
|
|
252
|
+
if parts and parts[0] == "--":
|
|
253
|
+
parts = parts[1:]
|
|
254
|
+
command = " ".join(parts).strip()
|
|
255
|
+
if not command:
|
|
256
|
+
print("btsh: empty command", file=sys.stderr)
|
|
257
|
+
return 2
|
|
258
|
+
try:
|
|
259
|
+
transport, mode = _build_transport(args, "client")
|
|
260
|
+
channel = _channel(args, transport, mode)
|
|
261
|
+
client = Client.connect(channel, key=key, verbose=args.verbose)
|
|
262
|
+
result = client.exec(command, timeout=args.command_timeout)
|
|
263
|
+
transport.close()
|
|
264
|
+
except (TransportError, ChannelError, AuthError, codec.CodecError) as exc:
|
|
265
|
+
print(f"btsh: {exc}", file=sys.stderr)
|
|
266
|
+
return 1
|
|
267
|
+
if result.get("stdout"):
|
|
268
|
+
sys.stdout.write(result["stdout"])
|
|
269
|
+
if result.get("stderr"):
|
|
270
|
+
sys.stderr.write(result["stderr"])
|
|
271
|
+
if args.json:
|
|
272
|
+
print(json.dumps({k: result.get(k) for k in ("cmd", "rc", "duration_ms", "truncated")}))
|
|
273
|
+
return int(result.get("rc") or 0)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def cmd_shell(args) -> int:
|
|
277
|
+
key = _read_key(args.key)
|
|
278
|
+
transport, mode = _build_transport(args, "client")
|
|
279
|
+
channel = _channel(args, transport, mode)
|
|
280
|
+
client = Client.connect(channel, key=key, verbose=args.verbose)
|
|
281
|
+
try:
|
|
282
|
+
return client.shell()
|
|
283
|
+
finally:
|
|
284
|
+
transport.close()
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def cmd_demo(args) -> int:
|
|
288
|
+
left, right = LoopbackTransport.pair()
|
|
289
|
+
server_channel = _channel(args, right)
|
|
290
|
+
client_channel = _channel(args, left)
|
|
291
|
+
key = b"demo-key" if args.key else None
|
|
292
|
+
server = ShellServer(
|
|
293
|
+
Session(server_channel, key=key),
|
|
294
|
+
ShellConfig(cwd=os.getcwd(), max_output=1024),
|
|
295
|
+
)
|
|
296
|
+
thread = threading.Thread(target=server.serve_forever, name="btsh-demo-server", daemon=True)
|
|
297
|
+
thread.start()
|
|
298
|
+
client = Client.connect(client_channel, key=key)
|
|
299
|
+
failures = 0
|
|
300
|
+
for command in args.command or ["uname -sr", "id -un", "echo hello from btsh"]:
|
|
301
|
+
result = client.exec(command)
|
|
302
|
+
print(f"$ {command}")
|
|
303
|
+
if result.get("stdout"):
|
|
304
|
+
sys.stdout.write(result["stdout"])
|
|
305
|
+
if result.get("stderr"):
|
|
306
|
+
sys.stderr.write(result["stderr"])
|
|
307
|
+
print(f"[rc={result.get('rc')} in {result.get('duration_ms')} ms of wall clock]")
|
|
308
|
+
if result.get("rc") != 0:
|
|
309
|
+
failures += 1
|
|
310
|
+
print(json.dumps({"client": client_channel.describe(), "server": server_channel.describe()}, indent=2))
|
|
311
|
+
return 0 if failures == 0 else 1
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def cmd_selftest(args) -> int:
|
|
315
|
+
"""Measure frame recovery over N bursts, with and without the codec."""
|
|
316
|
+
from . import framing, modem
|
|
317
|
+
|
|
318
|
+
payload = bytes(range(64))
|
|
319
|
+
wire = framing.pack(framing.Frame(ftype=framing.FT_DATA, seq=1, payload=payload))
|
|
320
|
+
rows = []
|
|
321
|
+
for mode in ("clean", "sbc"):
|
|
322
|
+
ok = 0
|
|
323
|
+
for _ in range(args.frames):
|
|
324
|
+
pcm = modem.modulate(wire)
|
|
325
|
+
if mode == "sbc":
|
|
326
|
+
pcm = codec.apply_codec(pcm, "sbc", args.bitrate)
|
|
327
|
+
try:
|
|
328
|
+
if modem.demodulate(pcm) == wire:
|
|
329
|
+
ok += 1
|
|
330
|
+
except modem.ModemError:
|
|
331
|
+
pass
|
|
332
|
+
rows.append({"channel": mode, "frames": args.frames, "recovered": ok})
|
|
333
|
+
print(json.dumps(rows, indent=2))
|
|
334
|
+
return 0 if all(row["recovered"] == row["frames"] for row in rows) else 1
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def cmd_mesh(args) -> int:
|
|
338
|
+
"""Hub plus two nodes: direct routing, then channels in both directions."""
|
|
339
|
+
from .crypto import Identity
|
|
340
|
+
from .hub import Hub
|
|
341
|
+
from .node import Node
|
|
342
|
+
|
|
343
|
+
key = b"mesh-demo-key" if args.key else None
|
|
344
|
+
sealed = args.crypto == "sealed"
|
|
345
|
+
identity = _identity(args)
|
|
346
|
+
hub_identity = identity if sealed else None
|
|
347
|
+
left_a, right_a = LoopbackTransport.pair()
|
|
348
|
+
left_b, right_b = LoopbackTransport.pair()
|
|
349
|
+
config = ShellConfig(cwd=os.getcwd(), max_output=1024)
|
|
350
|
+
hub = Hub(config=config, key=key, identity=hub_identity, verbose=args.verbose)
|
|
351
|
+
hub.add(_channel(args, right_a), "A")
|
|
352
|
+
hub.add(_channel(args, right_b), "B")
|
|
353
|
+
stop = False
|
|
354
|
+
threading.Thread(target=hub.serve_forever, kwargs={"stop": lambda: stop}, name="btsh-mesh-hub", daemon=True).start()
|
|
355
|
+
|
|
356
|
+
node_a = Node(
|
|
357
|
+
_channel(args, left_a),
|
|
358
|
+
"A",
|
|
359
|
+
config=config,
|
|
360
|
+
key=key,
|
|
361
|
+
identity=Identity() if sealed else None,
|
|
362
|
+
).start()
|
|
363
|
+
node_b = Node(
|
|
364
|
+
_channel(args, left_b),
|
|
365
|
+
"B",
|
|
366
|
+
config=config,
|
|
367
|
+
key=key,
|
|
368
|
+
identity=Identity() if sealed else None,
|
|
369
|
+
).start()
|
|
370
|
+
|
|
371
|
+
failures = 0
|
|
372
|
+
print("== direct routing")
|
|
373
|
+
for sender, node, target in (("A", node_a, "B"), ("B", node_b, "A"), ("A", node_a, "server")):
|
|
374
|
+
result = node.exec_on(target, f"echo direct-{sender}-to-{target}", timeout=180)
|
|
375
|
+
ok = result.get("rc") == 0
|
|
376
|
+
failures += 0 if ok else 1
|
|
377
|
+
print(f"{sender} -> {target}: {'ok' if ok else 'FAILED'} {json.dumps(result)[:160]}")
|
|
378
|
+
|
|
379
|
+
print("== channels")
|
|
380
|
+
node_a.subscribe("#a")
|
|
381
|
+
node_b.subscribe("#b")
|
|
382
|
+
refused = node_a.publish("#b", "echo must-not-run")
|
|
383
|
+
print(f"A publishing on #b before B allows it: {refused.get('op')} ({refused.get('error')})")
|
|
384
|
+
if refused.get("op") != "error":
|
|
385
|
+
failures += 1
|
|
386
|
+
node_b.allow("#b", "A")
|
|
387
|
+
node_a.allow("#a", "B")
|
|
388
|
+
for label, node, channel in (("A publishes #b -> B", node_a, "#b"), ("B publishes #a -> A", node_b, "#a")):
|
|
389
|
+
answer = node.publish(channel, f"echo {label.split()[0]}-on-{channel}")
|
|
390
|
+
results = answer.get("results") or []
|
|
391
|
+
good = bool(results) and all(item.get("rc") == 0 for item in results)
|
|
392
|
+
failures += 0 if good else 1
|
|
393
|
+
print(f"{label}: {'ok' if good else 'FAILED'} {json.dumps(results)[:220]}")
|
|
394
|
+
|
|
395
|
+
print("== topology")
|
|
396
|
+
print(json.dumps({"peers": node_a.peers(), "channels": node_a.channels()}, indent=2))
|
|
397
|
+
stop = True
|
|
398
|
+
node_a.stop()
|
|
399
|
+
node_b.stop()
|
|
400
|
+
return 0 if failures == 0 else 1
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def cmd_mcp(args) -> int:
|
|
404
|
+
"""Serve MCP over stdio; this process is itself a node of the mesh."""
|
|
405
|
+
from .mcp import McpServer
|
|
406
|
+
from .node import Node
|
|
407
|
+
|
|
408
|
+
transport, mode = _build_transport(args, "client")
|
|
409
|
+
channel = _channel(args, transport, mode)
|
|
410
|
+
config = ShellConfig(
|
|
411
|
+
cwd=os.path.abspath(os.path.expanduser(args.cwd)),
|
|
412
|
+
timeout=args.timeout,
|
|
413
|
+
max_output=args.max_output,
|
|
414
|
+
allow=args.allow,
|
|
415
|
+
deny=args.deny,
|
|
416
|
+
)
|
|
417
|
+
node = Node(
|
|
418
|
+
channel,
|
|
419
|
+
args.name,
|
|
420
|
+
config=config,
|
|
421
|
+
key=_read_key(args.key),
|
|
422
|
+
identity=_identity(args),
|
|
423
|
+
verbose=args.verbose,
|
|
424
|
+
)
|
|
425
|
+
try:
|
|
426
|
+
node.start()
|
|
427
|
+
print(f"btsh mcp: registered as {args.name} on {transport.describe()}", file=sys.stderr, flush=True)
|
|
428
|
+
McpServer(node, name=f"btsh-{args.name}").serve()
|
|
429
|
+
return 0
|
|
430
|
+
except KeyboardInterrupt:
|
|
431
|
+
return 0
|
|
432
|
+
finally:
|
|
433
|
+
node.stop()
|
|
434
|
+
transport.close()
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
438
|
+
parser = argparse.ArgumentParser(prog="btsh", description="Shell over a Bluetooth speaker's audio codec.")
|
|
439
|
+
parser.add_argument("--version", action="version", version=f"btsh {__version__}")
|
|
440
|
+
sub = parser.add_subparsers(dest="cmd", required=True)
|
|
441
|
+
|
|
442
|
+
doctor = sub.add_parser("doctor", help="Bluetooth devices, audio nodes, negotiated codec, audio devices")
|
|
443
|
+
doctor.add_argument("--json", action="store_true")
|
|
444
|
+
doctor.set_defaults(func=cmd_doctor)
|
|
445
|
+
|
|
446
|
+
connect = sub.add_parser("connect", help="connect a device and show where to play")
|
|
447
|
+
connect.add_argument("--device", required=True)
|
|
448
|
+
connect.set_defaults(func=cmd_connect)
|
|
449
|
+
|
|
450
|
+
devices = sub.add_parser("devices", help="list audio devices (PortAudio)")
|
|
451
|
+
devices.add_argument("--json", action="store_true")
|
|
452
|
+
devices.set_defaults(func=cmd_devices)
|
|
453
|
+
|
|
454
|
+
scan = sub.add_parser("scan", help="scan BLE peripherals")
|
|
455
|
+
scan.add_argument("--timeout", type=float, default=8.0)
|
|
456
|
+
scan.add_argument("--json", action="store_true")
|
|
457
|
+
scan.set_defaults(func=cmd_scan)
|
|
458
|
+
|
|
459
|
+
serve = sub.add_parser("serve", help="run the shell side (no sshd)")
|
|
460
|
+
_add_link_args(serve)
|
|
461
|
+
serve.add_argument("--cwd", default=".")
|
|
462
|
+
serve.add_argument("--timeout", type=float, default=20.0, help="per command timeout")
|
|
463
|
+
serve.add_argument("--max-output", type=int, default=4096)
|
|
464
|
+
serve.add_argument("--allow", action="append", default=[], help="regex a command must match")
|
|
465
|
+
serve.add_argument("--deny", action="append", default=[], help="regex a command must not match")
|
|
466
|
+
serve.set_defaults(func=cmd_serve)
|
|
467
|
+
|
|
468
|
+
run = sub.add_parser("exec", help="run one command on the peer")
|
|
469
|
+
_add_link_args(run)
|
|
470
|
+
run.add_argument("--command-timeout", type=float, default=180.0)
|
|
471
|
+
run.add_argument("--json", action="store_true")
|
|
472
|
+
run.add_argument("command", nargs=argparse.REMAINDER)
|
|
473
|
+
run.set_defaults(func=cmd_exec)
|
|
474
|
+
|
|
475
|
+
shell = sub.add_parser("shell", help="interactive shell on the peer")
|
|
476
|
+
_add_link_args(shell)
|
|
477
|
+
shell.set_defaults(func=cmd_shell)
|
|
478
|
+
|
|
479
|
+
demo = sub.add_parser("demo", help="in-process demo, loopback transport")
|
|
480
|
+
demo.add_argument("--codec", choices=("none", "sbc"), default="sbc")
|
|
481
|
+
demo.add_argument("--retries", type=int, default=6)
|
|
482
|
+
demo.add_argument("--ack-timeout", type=float, default=6.0)
|
|
483
|
+
demo.add_argument("--verbose", action="store_true")
|
|
484
|
+
demo.add_argument("--key", action="store_true", help="use the demo pre-shared key")
|
|
485
|
+
demo.add_argument("--command", action="append", default=None, help="repeatable; defaults to three small commands")
|
|
486
|
+
demo.set_defaults(func=cmd_demo)
|
|
487
|
+
|
|
488
|
+
selftest = sub.add_parser("selftest", help="measure frame recovery through the codec")
|
|
489
|
+
mesh = sub.add_parser("mesh", help="hub plus two nodes: peer to peer relay demo")
|
|
490
|
+
mesh.add_argument("--codec", choices=("none", "sbc"), default="none")
|
|
491
|
+
mesh.add_argument("--retries", type=int, default=3)
|
|
492
|
+
mesh.add_argument("--ack-timeout", type=float, default=2.0)
|
|
493
|
+
mesh.add_argument("--key", action="store_true", help="use the demo pre-shared key")
|
|
494
|
+
mesh.add_argument("--crypto", choices=("sealed", "psk", "none"), default="sealed")
|
|
495
|
+
mesh.add_argument("--identity", default="~/.btsh/identity")
|
|
496
|
+
mesh.add_argument("--verbose", action="store_true")
|
|
497
|
+
mesh.set_defaults(func=cmd_mesh)
|
|
498
|
+
|
|
499
|
+
mcp = sub.add_parser("mcp", help="serve MCP over stdio as a node of the mesh")
|
|
500
|
+
_add_link_args(mcp)
|
|
501
|
+
mcp.add_argument("--name", default=socket.gethostname())
|
|
502
|
+
mcp.add_argument("--cwd", default=".")
|
|
503
|
+
mcp.add_argument("--timeout", type=float, default=20.0, help="per command timeout on this host")
|
|
504
|
+
mcp.add_argument("--max-output", type=int, default=4096)
|
|
505
|
+
mcp.add_argument("--allow", action="append", default=[], help="regex a local command must match")
|
|
506
|
+
mcp.add_argument("--deny", action="append", default=[], help="regex a local command must not match")
|
|
507
|
+
mcp.set_defaults(func=cmd_mcp)
|
|
508
|
+
|
|
509
|
+
selftest.add_argument("--frames", type=int, default=8)
|
|
510
|
+
selftest.add_argument("--bitrate", type=int, default=200_000)
|
|
511
|
+
selftest.set_defaults(func=cmd_selftest)
|
|
512
|
+
return parser
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def main(argv: list[str] | None = None) -> int:
|
|
516
|
+
parser = build_parser()
|
|
517
|
+
args = parser.parse_args(argv)
|
|
518
|
+
try:
|
|
519
|
+
return int(args.func(args) or 0)
|
|
520
|
+
except (TransportError, codec.CodecError, ChannelError, AuthError) as exc:
|
|
521
|
+
print(f"btsh: {exc}", file=sys.stderr)
|
|
522
|
+
return 1
|
|
523
|
+
except KeyboardInterrupt:
|
|
524
|
+
return 130
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
if __name__ == "__main__": # pragma: no cover
|
|
528
|
+
raise SystemExit(main())
|
btsh/client.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Client side: ssh-like exec and interactive shell over the acoustic link."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
from .channel import Channel
|
|
9
|
+
from .session import Session
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Client:
|
|
13
|
+
def __init__(self, session: Session) -> None:
|
|
14
|
+
self.session = session
|
|
15
|
+
self.channel = session.channel
|
|
16
|
+
self.handshaked = False
|
|
17
|
+
|
|
18
|
+
@classmethod
|
|
19
|
+
def connect(cls, channel: Channel, key: bytes | None = None, verbose: bool = False) -> "Client":
|
|
20
|
+
client = cls(Session(channel, key=key, verbose=verbose))
|
|
21
|
+
client.session.hello()
|
|
22
|
+
client.handshaked = True
|
|
23
|
+
return client
|
|
24
|
+
|
|
25
|
+
def exec(self, cmd: str, timeout: float = 120.0) -> dict:
|
|
26
|
+
"""Send a command, return the peer's result message."""
|
|
27
|
+
started = time.monotonic()
|
|
28
|
+
self.session.send_message({"op": "exec", "cmd": cmd})
|
|
29
|
+
answer = self.session.recv_message(timeout=timeout)
|
|
30
|
+
if answer is None:
|
|
31
|
+
return {
|
|
32
|
+
"op": "timeout",
|
|
33
|
+
"cmd": cmd,
|
|
34
|
+
"stdout": "",
|
|
35
|
+
"stderr": "btsh: no answer from peer",
|
|
36
|
+
"rc": 124,
|
|
37
|
+
"truncated": False,
|
|
38
|
+
"duration_ms": int((time.monotonic() - started) * 1000),
|
|
39
|
+
}
|
|
40
|
+
return answer
|
|
41
|
+
|
|
42
|
+
def ping(self, timeout: float = 30.0) -> dict | None:
|
|
43
|
+
self.session.send_message({"op": "ping"})
|
|
44
|
+
return self.session.recv_message(timeout=timeout)
|
|
45
|
+
|
|
46
|
+
def close(self) -> None:
|
|
47
|
+
try:
|
|
48
|
+
self.session.send_message({"op": "bye"})
|
|
49
|
+
except Exception: # noqa: BLE001 - best effort
|
|
50
|
+
pass
|
|
51
|
+
|
|
52
|
+
def shell(self, prompt: str = "btsh> ") -> int:
|
|
53
|
+
"""Interactive REPL, like a tiny ssh session."""
|
|
54
|
+
print("btsh: connected. Ctrl-D or 'exit' to leave.", file=sys.stderr)
|
|
55
|
+
while True:
|
|
56
|
+
try:
|
|
57
|
+
line = input(prompt)
|
|
58
|
+
except (EOFError, KeyboardInterrupt):
|
|
59
|
+
print("", file=sys.stderr)
|
|
60
|
+
return 0
|
|
61
|
+
cmd = line.strip()
|
|
62
|
+
if not cmd:
|
|
63
|
+
continue
|
|
64
|
+
if cmd in ("exit", "quit", "logout"):
|
|
65
|
+
self.close()
|
|
66
|
+
return 0
|
|
67
|
+
result = self.exec(cmd)
|
|
68
|
+
if result.get("stdout"):
|
|
69
|
+
sys.stdout.write(result["stdout"])
|
|
70
|
+
sys.stdout.flush()
|
|
71
|
+
if result.get("stderr"):
|
|
72
|
+
sys.stderr.write(result["stderr"])
|
|
73
|
+
sys.stderr.flush()
|
|
74
|
+
if result.get("rc") not in (0, None):
|
|
75
|
+
print(f"btsh: exit status {result.get('rc')}", file=sys.stderr)
|