side-cli 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.
side_cli/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Public API for supervising a command and bridging its standard streams."""
2
+
3
+ from .clients import InputClient, PanelClient
4
+ from .supervisor import HOST, PortStatus, Ports, Stream, Supervisor
5
+
6
+ __all__ = ["HOST", "InputClient", "PanelClient", "PortStatus", "Ports", "Stream", "Supervisor"]
side_cli/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
side_cli/ansi.py ADDED
@@ -0,0 +1,154 @@
1
+ """Incremental ANSI color decoding for the GUI text viewer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Iterator, Sequence
7
+ from itertools import islice
8
+
9
+ Colors = tuple[str | None, str | None]
10
+ ColorRun = tuple[str, Colors]
11
+
12
+ _CONTROL = re.compile(r"[\x1b\x90\x98\x9b\x9d\x9e\x9f]")
13
+ _ESCAPE = re.compile(r"[ -/]*[0-~]")
14
+ _ESCAPE_PREFIX = re.compile(r"[ -/]*")
15
+ _CSI = re.compile(r"([0-?]*)([ -/]*)([@-~])")
16
+ _CSI_PREFIX = re.compile(r"[0-?]*[ -/]*")
17
+ _SGR_PARAMETERS = re.compile(r"[0-9:;]*")
18
+ _STRING_END = re.compile(r"\x1b\\|\x9c")
19
+ _OSC_END = re.compile(r"\x1b\\|\x9c|\x07")
20
+ _MAX_PARAMETERS = 128
21
+
22
+ _PALETTE = (
23
+ "#000000", "#cd0000", "#00cd00", "#cdcd00", "#0000ee", "#cd00cd", "#00cdcd", "#e5e5e5",
24
+ "#7f7f7f", "#ff0000", "#00ff00", "#ffff00", "#5c5cff", "#ff00ff", "#00ffff", "#ffffff",
25
+ )
26
+ _CUBE_LEVELS = (0, 95, 135, 175, 215, 255)
27
+
28
+
29
+ def _indexed_color(index: int) -> str:
30
+ if index < 16:
31
+ return _PALETTE[index]
32
+ if index >= 232:
33
+ gray = 8 + 10 * (index - 232)
34
+ return f"#{gray:02x}{gray:02x}{gray:02x}"
35
+ red, remainder = divmod(index - 16, 36)
36
+ green, blue = divmod(remainder, 6)
37
+ return f"#{_CUBE_LEVELS[red]:02x}{_CUBE_LEVELS[green]:02x}{_CUBE_LEVELS[blue]:02x}"
38
+
39
+
40
+ def _extended_color(mode: str, params: Sequence[str]) -> str | None:
41
+ if any(not param.isdecimal() for param in params):
42
+ return None
43
+ values = [int(param) for param in params]
44
+ if any(value > 255 for value in values):
45
+ return None
46
+ if mode == "5" and len(values) == 1:
47
+ return _indexed_color(values[0])
48
+ if mode == "2" and len(values) == 3:
49
+ return "#" + "".join(f"{value:02x}" for value in values)
50
+ return None
51
+
52
+
53
+ class AnsiColors:
54
+ """Convert one stream's chunks to visible text and foreground/background pairs."""
55
+
56
+ def __init__(self) -> None:
57
+ self._foreground: str | None = None
58
+ self._background: str | None = None
59
+ self._partial = ""
60
+ self._string_end: re.Pattern[str] | None = None
61
+
62
+ def feed(self, text: str, *, final: bool = False) -> Iterator[ColorRun]:
63
+ text = self._partial + text
64
+ self._partial = ""
65
+ offset = 0
66
+ while offset < len(text):
67
+ if self._string_end is not None:
68
+ string_end = self._string_end.search(text, offset)
69
+ if string_end is None:
70
+ if not final and text.endswith("\x1b"):
71
+ self._partial = "\x1b"
72
+ return
73
+ self._string_end = None
74
+ offset = string_end.end()
75
+ continue
76
+
77
+ control = _CONTROL.search(text, offset)
78
+ end = control.start() if control else len(text)
79
+ if offset < end:
80
+ yield text[offset:end], (self._foreground, self._background)
81
+ if control is None:
82
+ return
83
+
84
+ offset = control.end()
85
+ if control[0] == "\x1b":
86
+ kind = text[offset:offset + 1]
87
+ if kind == "[":
88
+ offset += 1
89
+ elif kind and kind in "]PX^_":
90
+ self._string_end = _OSC_END if kind == "]" else _STRING_END
91
+ offset += 1
92
+ continue
93
+ else:
94
+ escape = _ESCAPE.match(text, offset)
95
+ if escape is not None:
96
+ offset = escape.end()
97
+ elif _ESCAPE_PREFIX.fullmatch(text, offset):
98
+ if not final and len(text) - offset <= _MAX_PARAMETERS:
99
+ self._partial = text[end:]
100
+ return
101
+ continue
102
+ elif control[0] != "\x9b":
103
+ self._string_end = _OSC_END if control[0] == "\x9d" else _STRING_END
104
+ continue
105
+
106
+ csi = _CSI.match(text, offset)
107
+ if csi is not None:
108
+ params, intermediate, command = csi.groups()
109
+ if command == "m" and not intermediate:
110
+ self._set_colors(params)
111
+ offset = csi.end()
112
+ elif _CSI_PREFIX.fullmatch(text, offset):
113
+ if not final and len(text) - offset <= _MAX_PARAMETERS:
114
+ self._partial = text[end:]
115
+ return
116
+
117
+ def _set_colors(self, params: str) -> None:
118
+ if len(params) > _MAX_PARAMETERS or not _SGR_PARAMETERS.fullmatch(params):
119
+ return
120
+ parameters = iter(params.split(";"))
121
+ for parameter in parameters:
122
+ if ":" in parameter:
123
+ target, mode, *values = parameter.split(":")
124
+ if mode == "2" and len(values) == 4 and values[0] in ("", "0"):
125
+ values = values[1:]
126
+ self._set_extended(target, mode, values)
127
+ continue
128
+
129
+ code = int(parameter or "0")
130
+ if code == 0:
131
+ self._foreground = self._background = None
132
+ elif 30 <= code <= 37:
133
+ self._foreground = _PALETTE[code - 30]
134
+ elif 40 <= code <= 47:
135
+ self._background = _PALETTE[code - 40]
136
+ elif 90 <= code <= 97:
137
+ self._foreground = _PALETTE[code - 90 + 8]
138
+ elif 100 <= code <= 107:
139
+ self._background = _PALETTE[code - 100 + 8]
140
+ elif code == 39:
141
+ self._foreground = None
142
+ elif code == 49:
143
+ self._background = None
144
+ elif code in (38, 48, 58):
145
+ mode = next(parameters, "")
146
+ count = {"2": 3, "5": 1}.get(mode, 0)
147
+ self._set_extended(str(code), mode, list(islice(parameters, count)))
148
+
149
+ def _set_extended(self, target: str, mode: str, values: Sequence[str]) -> None:
150
+ if target in ("38", "48") and (color := _extended_color(mode, values)) is not None:
151
+ if target == "38":
152
+ self._foreground = color
153
+ else:
154
+ self._background = color
side_cli/cli.py ADDED
@@ -0,0 +1,418 @@
1
+ """Console entry point and frontend lifecycle."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import codecs
8
+ import os
9
+ import signal
10
+ import sys
11
+ import threading
12
+ from concurrent.futures import CancelledError
13
+ from contextlib import suppress
14
+ from typing import BinaryIO, TextIO
15
+
16
+ from .clients import InputClient, PanelClient
17
+ from .supervisor import CHUNK_SIZE, Ports, Stream, Supervisor, _InputLines
18
+
19
+ _ECHO_CONTROLS = dict.fromkeys(
20
+ code for code in (*range(32), *range(127, 160)) if code not in (9, 10)
21
+ )
22
+
23
+
24
+ def _visible_input(text: str) -> str:
25
+ return text.translate(_ECHO_CONTROLS)
26
+
27
+
28
+ class ConsoleInterrupt:
29
+ def __init__(self, supervisor: Supervisor) -> None:
30
+ self.supervisor = supervisor
31
+ self.before_start = False
32
+
33
+ def __enter__(self) -> ConsoleInterrupt:
34
+ self.previous = signal.getsignal(signal.SIGINT)
35
+ if os.name == "posix":
36
+ asyncio.get_running_loop().add_signal_handler(signal.SIGINT, self._receive)
37
+ else:
38
+ signal.signal(signal.SIGINT, self._receive)
39
+ return self
40
+
41
+ def __exit__(self, *exc_info: object) -> None:
42
+ if os.name == "posix":
43
+ asyncio.get_running_loop().remove_signal_handler(signal.SIGINT)
44
+ signal.signal(signal.SIGINT, self.previous)
45
+
46
+ def _receive(self, *_: object) -> None:
47
+ if self.supervisor.pid is None:
48
+ self.before_start = True
49
+ else:
50
+ self.supervisor.forward_console_interrupt()
51
+
52
+ async def launch(self, wait_for_clients: bool) -> bool:
53
+ if wait_for_clients:
54
+ ready = asyncio.create_task(self.supervisor.wait_for_output_clients())
55
+ try:
56
+ while not ready.done() and not self.before_start:
57
+ await asyncio.wait((ready,), timeout=0.1)
58
+ if ready.done():
59
+ ready.result()
60
+ finally:
61
+ ready.cancel()
62
+ with suppress(asyncio.CancelledError):
63
+ await ready
64
+ if self.before_start:
65
+ return False
66
+ await self.supervisor.start()
67
+ if self.before_start:
68
+ if os.name == "posix":
69
+ self.supervisor.forward_console_interrupt()
70
+ else:
71
+ self.supervisor.terminate()
72
+ return True
73
+
74
+
75
+ def _terminal_encoding(file: TextIO, raw: BinaryIO) -> str | None:
76
+ if type(raw).__name__ == "_WindowsConsoleIO":
77
+ return "utf-8"
78
+ return (file.encoding or "utf-8") if file.isatty() else None
79
+
80
+
81
+ class _Transcoder:
82
+ def __init__(self, source: str, target: str) -> None:
83
+ self.decoder = codecs.getincrementaldecoder(source)("replace")
84
+ self.encoder = codecs.getincrementalencoder(target)("replace")
85
+ self.started = False
86
+
87
+ def convert(self, data: bytes, *, final: bool = False) -> bytes:
88
+ text = self.decoder.decode(data, final=final)
89
+ if not text and not (self.started and final):
90
+ return b""
91
+ self.started = True
92
+ return self.encoder.encode(text, final=final)
93
+
94
+
95
+ def _start_local_input(
96
+ supervisor: Supervisor, close_on_eof: bool, encoding: str, output: ConsoleOutput | None = None,
97
+ ) -> threading.Event:
98
+ loop = asyncio.get_running_loop()
99
+ stopped = threading.Event()
100
+ binary = getattr(sys.stdin, "buffer", None)
101
+ if binary is None:
102
+ return stopped
103
+ raw = getattr(binary, "raw", binary)
104
+ terminal_encoding = _terminal_encoding(sys.stdin, raw)
105
+ transcoder = _Transcoder(terminal_encoding, encoding) if terminal_encoding else None
106
+ echo_decoder = (
107
+ codecs.getincrementaldecoder(encoding)("replace")
108
+ if terminal_encoding is None and output is not None else None
109
+ )
110
+ lines = _InputLines()
111
+
112
+ async def forward(data: bytes, eof: bool) -> None:
113
+ if echo_decoder is not None and output is not None:
114
+ await output.echo_input(echo_decoder.decode(data, final=eof))
115
+ for line in lines.feed(data):
116
+ if transcoder is not None:
117
+ line = transcoder.convert(line)
118
+ if line:
119
+ await supervisor.send(line)
120
+ if eof and close_on_eof:
121
+ await supervisor.close_stdin()
122
+
123
+ def read_stdin() -> None:
124
+ while not stopped.is_set():
125
+ try:
126
+ data = raw.read(CHUNK_SIZE)
127
+ if stopped.is_set() or data is None:
128
+ return
129
+ eof = not data
130
+ if data or (eof and (close_on_eof or echo_decoder is not None)):
131
+ operation = forward(data, eof)
132
+ try:
133
+ future = asyncio.run_coroutine_threadsafe(operation, loop)
134
+ except RuntimeError:
135
+ operation.close()
136
+ return
137
+ future.result()
138
+ if eof:
139
+ return
140
+ except ValueError as error:
141
+ print(f"side-cli: {error}", file=sys.stderr)
142
+ return
143
+ except (OSError, RuntimeError, CancelledError):
144
+ return
145
+
146
+ threading.Thread(target=read_stdin, name="side-cli-stdin", daemon=True).start()
147
+ return stopped
148
+
149
+
150
+ class ConsoleOutput:
151
+ def __init__(self, encoding: str) -> None:
152
+ self.sinks = {}
153
+ self.transcoders: dict[Stream, _Transcoder] = {}
154
+ self._stdout_lock = asyncio.Lock()
155
+ self._stdout_encoding = None
156
+ for stream, file in ((Stream.STDOUT, sys.stdout), (Stream.STDERR, sys.stderr)):
157
+ binary = getattr(file, "buffer", None)
158
+ if binary is not None:
159
+ raw = getattr(binary, "raw", binary)
160
+ self.sinks[stream] = raw
161
+ if target := _terminal_encoding(file, raw):
162
+ self.transcoders[stream] = _Transcoder(encoding, target)
163
+ if stream is Stream.STDOUT:
164
+ self._stdout_encoding = target
165
+
166
+ async def write(self, stream: Stream, data: bytes, *, final: bool = False) -> None:
167
+ if stream not in self.sinks:
168
+ return
169
+ if transcoder := self.transcoders.get(stream):
170
+ data = transcoder.convert(data, final=final)
171
+ if stream is Stream.STDOUT:
172
+ async with self._stdout_lock:
173
+ await self._emit(stream, data)
174
+ else:
175
+ await self._emit(stream, data)
176
+
177
+ async def echo_input(self, text: str) -> None:
178
+ if self._stdout_encoding is None:
179
+ return
180
+ text = _visible_input(text)
181
+ if os.name == "nt":
182
+ text = text.replace("\n", "\r\n")
183
+ async with self._stdout_lock:
184
+ await self._emit(Stream.STDOUT, text.encode(self._stdout_encoding, "replace"))
185
+
186
+ async def _emit(self, stream: Stream, data: bytes) -> None:
187
+ if not data or stream not in self.sinks:
188
+ return
189
+ try:
190
+ await asyncio.to_thread(self._write_all, stream, data)
191
+ except OSError:
192
+ del self.sinks[stream]
193
+
194
+ def _write_all(self, stream: Stream, data: bytes) -> None:
195
+ remaining = memoryview(data)
196
+ while remaining:
197
+ written = self.sinks[stream].write(remaining)
198
+ if not written:
199
+ raise OSError("console output is not writable")
200
+ remaining = remaining[written:]
201
+
202
+ async def finish(self) -> None:
203
+ for stream in self.transcoders:
204
+ await self.write(stream, b"", final=True)
205
+
206
+
207
+ async def _run_panel(port: int, encoding: str) -> int:
208
+ output = ConsoleOutput(encoding)
209
+ async with PanelClient(port) as client:
210
+ try:
211
+ async for stream, data in client:
212
+ await output.write(stream, data)
213
+ finally:
214
+ await output.finish()
215
+ return 0
216
+
217
+
218
+ async def _send_stdin_lines(client: InputClient, encoding: str) -> int:
219
+ binary = getattr(sys.stdin, "buffer", None)
220
+ if binary is None:
221
+ return 0
222
+ raw = getattr(binary, "raw", binary)
223
+ terminal_encoding = _terminal_encoding(sys.stdin, raw)
224
+ transcoder = _Transcoder(terminal_encoding, encoding) if terminal_encoding else None
225
+ loop = asyncio.get_running_loop()
226
+ stopped = threading.Event()
227
+ chunks: asyncio.Queue[bytes | OSError] = asyncio.Queue(maxsize=1)
228
+
229
+ async def send(data: bytes) -> None:
230
+ if transcoder is not None:
231
+ data = transcoder.convert(data)
232
+ if data:
233
+ await client.send(data)
234
+
235
+ def read_stdin() -> None:
236
+ while not stopped.is_set():
237
+ try:
238
+ item: bytes | OSError = raw.read(CHUNK_SIZE) or b""
239
+ except OSError as error:
240
+ item = error
241
+ if stopped.is_set():
242
+ return
243
+ operation = chunks.put(item)
244
+ try:
245
+ future = asyncio.run_coroutine_threadsafe(operation, loop)
246
+ except RuntimeError:
247
+ operation.close()
248
+ return
249
+ try:
250
+ future.result()
251
+ except CancelledError:
252
+ return
253
+ if not item or isinstance(item, OSError):
254
+ return
255
+
256
+ threading.Thread(target=read_stdin, name="side-cli-input", daemon=True).start()
257
+ lines = _InputLines()
258
+ try:
259
+ while item := await chunks.get():
260
+ if isinstance(item, OSError):
261
+ return 1
262
+ for line in lines.feed(item):
263
+ await send(line)
264
+ return 0
265
+ finally:
266
+ stopped.set()
267
+
268
+
269
+ async def _run_input(port: int, encoding: str) -> int:
270
+ async with InputClient(port) as client:
271
+ sending = asyncio.create_task(_send_stdin_lines(client, encoding))
272
+ disconnected = asyncio.create_task(client.wait_for_disconnect())
273
+ try:
274
+ done, _ = await asyncio.wait((sending, disconnected), return_when=asyncio.FIRST_COMPLETED)
275
+ if disconnected in done:
276
+ disconnected.result()
277
+ return sending.result() if sending in done else 0
278
+ finally:
279
+ sending.cancel()
280
+ disconnected.cancel()
281
+ await asyncio.gather(sending, disconnected, return_exceptions=True)
282
+
283
+
284
+ def show_ports(supervisor: Supervisor) -> None:
285
+ for port in supervisor.status().values():
286
+ print(f"side-cli: {port.stream} {port.host}:{port.port}", file=sys.stderr, flush=True)
287
+
288
+
289
+ async def _run_console(args: argparse.Namespace, ports: Ports) -> int:
290
+ output = ConsoleOutput(args.encoding)
291
+ supervisor = Supervisor(
292
+ args.command, ports=ports, on_output=output.write,
293
+ on_input_echo=output.echo_input, input_encoding=args.encoding,
294
+ close_stdin_on_eof=args.close_stdin_on_eof,
295
+ )
296
+ with ConsoleInterrupt(supervisor) as interrupts:
297
+ async with supervisor:
298
+ if args.show_ports:
299
+ show_ports(supervisor)
300
+ if not await interrupts.launch(args.wait_for_output_clients):
301
+ return 130
302
+ local_input = None
303
+ try:
304
+ if not args.no_local_stdin:
305
+ local_input = _start_local_input(
306
+ supervisor, args.close_stdin_on_eof, args.encoding, output,
307
+ )
308
+ return await supervisor.wait()
309
+ finally:
310
+ if local_input is not None:
311
+ local_input.set()
312
+ await output.finish()
313
+
314
+
315
+ def _encoding(value: str) -> str:
316
+ try:
317
+ decoder = codecs.getincrementaldecoder(value)
318
+ codecs.getincrementalencoder(value)
319
+ if not isinstance(decoder("replace").decode(b""), str):
320
+ raise ValueError(f"{value!r} is not a text encoding")
321
+ "".encode(value)
322
+ except (ValueError, LookupError, TypeError) as error:
323
+ raise argparse.ArgumentTypeError(str(error)) from error
324
+ return value
325
+
326
+
327
+ def _client_port(value: str) -> int:
328
+ try:
329
+ port = int(value)
330
+ except ValueError:
331
+ port = 0
332
+ if not 1 <= port <= 65535:
333
+ raise argparse.ArgumentTypeError("port must be an integer between 1 and 65535")
334
+ return port
335
+
336
+
337
+ def _configure_run(parser: argparse.ArgumentParser, defaults: Ports) -> None:
338
+ parser.add_argument("--gui", action="store_true", help="open the desktop interface")
339
+ parser.add_argument("--stdin-port", type=int, default=defaults.stdin,
340
+ help="TCP port for stdin (default: %(default)s; 0: auto)")
341
+ for stream in (Stream.STDOUT, Stream.STDERR):
342
+ parser.add_argument(f"--{stream}-port", type=int,
343
+ help=f"TCP port for {stream} (default: {getattr(defaults, stream)}; 0: auto)")
344
+ parser.add_argument("--output-port", type=int,
345
+ help="one TCP port for framed stdout and stderr (replaces both output ports; 0: auto)")
346
+ parser.add_argument("--show-ports", action="store_true", help="print bound ports to stderr")
347
+ parser.add_argument("--wait-for-output-clients", action="store_true",
348
+ help="wait for a client on each output port before launching")
349
+ parser.add_argument("--no-local-stdin", action="store_true",
350
+ help="read stdin only from TCP in console mode")
351
+ parser.add_argument("--close-stdin-on-eof", action="store_true",
352
+ help="close child stdin on EOF from a TCP or local input source")
353
+ parser.add_argument("--encoding", type=_encoding, default="utf-8",
354
+ help="child text encoding for terminal and GUI I/O (default: %(default)s)")
355
+ parser.add_argument("command", nargs=argparse.REMAINDER)
356
+
357
+
358
+ def _parse_run_ports(parser: argparse.ArgumentParser, args: argparse.Namespace, defaults: Ports) -> Ports:
359
+ if args.command and args.command[0] == "--":
360
+ del args.command[0]
361
+ if not args.command or not args.command[0]:
362
+ parser.error("a command is required")
363
+ if args.output_port is not None and (args.stdout_port is not None or args.stderr_port is not None):
364
+ parser.error("--output-port cannot be combined with --stdout-port or --stderr-port")
365
+ try:
366
+ return Ports(
367
+ stdin=args.stdin_port,
368
+ stdout=defaults.stdout if args.stdout_port is None else args.stdout_port,
369
+ stderr=defaults.stderr if args.stderr_port is None else args.stderr_port,
370
+ output=args.output_port,
371
+ )
372
+ except ValueError as error:
373
+ parser.error(str(error))
374
+
375
+
376
+ def main(argv: list[str] | None = None) -> int:
377
+ defaults = Ports()
378
+ parser = argparse.ArgumentParser(
379
+ prog="side-cli", description="Bridge a command's standard streams over local TCP."
380
+ )
381
+ commands = parser.add_subparsers(dest="action", required=True)
382
+ run = commands.add_parser("run", help="run and supervise a command",
383
+ usage="%(prog)s [options] -- command [arguments ...]")
384
+ _configure_run(run, defaults)
385
+ panel = commands.add_parser("panel", help="mirror stdout and stderr from a framed output port")
386
+ panel.add_argument("--port", type=_client_port, default=defaults.stdout,
387
+ help="framed output port (default: %(default)s)")
388
+ panel.add_argument("--encoding", type=_encoding, default="utf-8",
389
+ help="child text encoding for terminal output (default: %(default)s)")
390
+ input_parser = commands.add_parser("input", help="send local stdin lines to a running command")
391
+ input_parser.add_argument("--port", type=_client_port, default=defaults.stdin,
392
+ help="stdin port (default: %(default)s)")
393
+ input_parser.add_argument("--encoding", type=_encoding, default="utf-8",
394
+ help="child text encoding for terminal input (default: %(default)s)")
395
+ args = parser.parse_args(argv)
396
+ try:
397
+ if args.action == "panel":
398
+ return asyncio.run(_run_panel(args.port, args.encoding))
399
+ if args.action == "input":
400
+ if "\n".encode(args.encoding) != b"\n":
401
+ input_parser.error("--encoding must use a single LF byte for newlines")
402
+ return asyncio.run(_run_input(args.port, args.encoding))
403
+ ports = _parse_run_ports(run, args, defaults)
404
+ if args.gui:
405
+ try:
406
+ from .gui import run_gui
407
+ except ImportError as error:
408
+ raise RuntimeError("GUI mode requires Tkinter; try 'python -m tkinter'") from error
409
+
410
+ code = asyncio.run(run_gui(args, ports))
411
+ else:
412
+ code = asyncio.run(_run_console(args, ports))
413
+ except KeyboardInterrupt:
414
+ return 130
415
+ except (OSError, RuntimeError, ValueError) as error:
416
+ print(f"side-cli: {error}", file=sys.stderr)
417
+ return 1
418
+ return 128 - code if code < 0 else code