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 +6 -0
- side_cli/__main__.py +4 -0
- side_cli/ansi.py +154 -0
- side_cli/cli.py +418 -0
- side_cli/clients.py +133 -0
- side_cli/gui.py +269 -0
- side_cli/supervisor.py +411 -0
- side_cli-0.1.0.dist-info/METADATA +262 -0
- side_cli-0.1.0.dist-info/RECORD +12 -0
- side_cli-0.1.0.dist-info/WHEEL +4 -0
- side_cli-0.1.0.dist-info/entry_points.txt +4 -0
- side_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
side_cli/supervisor.py
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
"""Shared subprocess and TCP implementation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import codecs
|
|
7
|
+
import inspect
|
|
8
|
+
import os
|
|
9
|
+
import signal
|
|
10
|
+
import struct
|
|
11
|
+
from collections.abc import Awaitable, Callable, Iterator, Mapping, Sequence
|
|
12
|
+
from contextlib import suppress
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from enum import StrEnum
|
|
15
|
+
from types import TracebackType
|
|
16
|
+
from typing import Literal
|
|
17
|
+
|
|
18
|
+
HOST = "127.0.0.1"
|
|
19
|
+
CHUNK_SIZE = 64 * 1024
|
|
20
|
+
CLIENT_BUFFER_LIMIT = 4 * 1024 * 1024
|
|
21
|
+
INPUT_LINE_LIMIT = 1024 * 1024
|
|
22
|
+
SHUTDOWN_TIMEOUT = 2.0
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Stream(StrEnum):
|
|
26
|
+
STDIN = "stdin"
|
|
27
|
+
STDOUT = "stdout"
|
|
28
|
+
STDERR = "stderr"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
Endpoint = Stream | Literal["output"]
|
|
32
|
+
_FRAME_HEADER = struct.Struct("!BI")
|
|
33
|
+
_OUTPUT_STREAM_IDS = {Stream.STDOUT: 1, Stream.STDERR: 2}
|
|
34
|
+
_CLINK_PROMPT_TAG = "C\bL\bI\bN\bK\b \b"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True, slots=True)
|
|
38
|
+
class Ports:
|
|
39
|
+
"""TCP ports; zero requests an available port. Output overrides stdout and stderr."""
|
|
40
|
+
|
|
41
|
+
stdin: int = 8765
|
|
42
|
+
stdout: int = 8766
|
|
43
|
+
stderr: int = 8767
|
|
44
|
+
output: int | None = None
|
|
45
|
+
|
|
46
|
+
def __post_init__(self) -> None:
|
|
47
|
+
ports = self._bindings().values()
|
|
48
|
+
if any(type(port) is not int or not 0 <= port <= 65535 for port in ports):
|
|
49
|
+
raise ValueError("ports must be integers between 0 and 65535")
|
|
50
|
+
fixed = [port for port in ports if port]
|
|
51
|
+
if len(set(fixed)) != len(fixed):
|
|
52
|
+
raise ValueError("active TCP listeners must use different ports")
|
|
53
|
+
|
|
54
|
+
def _bindings(self) -> dict[Endpoint, int]:
|
|
55
|
+
if self.output is not None:
|
|
56
|
+
return {Stream.STDIN: self.stdin, "output": self.output}
|
|
57
|
+
return {Stream.STDIN: self.stdin, Stream.STDOUT: self.stdout, Stream.STDERR: self.stderr}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True, slots=True)
|
|
61
|
+
class PortStatus:
|
|
62
|
+
stream: Endpoint
|
|
63
|
+
host: str
|
|
64
|
+
port: int
|
|
65
|
+
listening: bool
|
|
66
|
+
clients: int
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
OutputHandler = Callable[[Stream, bytes], Awaitable[None] | None]
|
|
70
|
+
InputEcho = Callable[[str], Awaitable[None] | None]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class _InputLines:
|
|
74
|
+
"""Assemble LF-terminated byte frames for one input source."""
|
|
75
|
+
|
|
76
|
+
def __init__(self) -> None:
|
|
77
|
+
self.pending = bytearray()
|
|
78
|
+
|
|
79
|
+
def feed(self, data: bytes) -> Iterator[bytes]:
|
|
80
|
+
offset = 0
|
|
81
|
+
while offset < len(data):
|
|
82
|
+
newline = data.find(b"\n", offset)
|
|
83
|
+
end = len(data) if newline == -1 else newline + 1
|
|
84
|
+
if len(self.pending) + end - offset > INPUT_LINE_LIMIT:
|
|
85
|
+
raise ValueError("input line exceeds 1 MiB")
|
|
86
|
+
self.pending.extend(data[offset:end])
|
|
87
|
+
if newline == -1:
|
|
88
|
+
return
|
|
89
|
+
line = bytes(self.pending)
|
|
90
|
+
self.pending.clear()
|
|
91
|
+
offset = end
|
|
92
|
+
yield line
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _piped_environment(
|
|
96
|
+
executable: str, env: Mapping[str, str] | None,
|
|
97
|
+
) -> Mapping[str, str] | None:
|
|
98
|
+
"""Remove Clink's inherited prompt tag when CMD cannot use its console hooks."""
|
|
99
|
+
if os.name != "nt" or os.path.basename(executable).casefold() not in {"cmd", "cmd.exe"}:
|
|
100
|
+
return env
|
|
101
|
+
|
|
102
|
+
source = os.environ if env is None else env
|
|
103
|
+
updates = {
|
|
104
|
+
name: value.removeprefix(_CLINK_PROMPT_TAG)
|
|
105
|
+
for name, value in source.items()
|
|
106
|
+
if name.upper() == "PROMPT" and value.startswith(_CLINK_PROMPT_TAG)
|
|
107
|
+
}
|
|
108
|
+
return {**source, **updates} if updates else env
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class Supervisor:
|
|
112
|
+
"""Run one command with piped standard streams on the current asyncio loop."""
|
|
113
|
+
|
|
114
|
+
def __init__(
|
|
115
|
+
self,
|
|
116
|
+
command: Sequence[str],
|
|
117
|
+
*,
|
|
118
|
+
ports: Ports = Ports(),
|
|
119
|
+
on_output: OutputHandler | None = None,
|
|
120
|
+
on_input_echo: InputEcho | None = None,
|
|
121
|
+
input_encoding: str = "utf-8",
|
|
122
|
+
close_stdin_on_eof: bool = False,
|
|
123
|
+
cwd: str | os.PathLike[str] | None = None,
|
|
124
|
+
env: Mapping[str, str] | None = None,
|
|
125
|
+
) -> None:
|
|
126
|
+
if isinstance(command, str) or not command or not command[0]:
|
|
127
|
+
raise ValueError("command must be a nonempty argument sequence")
|
|
128
|
+
self.command = tuple(command)
|
|
129
|
+
self._port_bindings = ports._bindings()
|
|
130
|
+
self._merged_output = ports.output is not None
|
|
131
|
+
self._bound_ports: dict[Endpoint, int] = {}
|
|
132
|
+
self._servers: dict[Endpoint, asyncio.Server] = {}
|
|
133
|
+
self._clients: dict[Endpoint, set[asyncio.StreamWriter]] = {
|
|
134
|
+
endpoint: set() for endpoint in self._port_bindings
|
|
135
|
+
}
|
|
136
|
+
self._client_tasks: set[asyncio.Task[None]] = set()
|
|
137
|
+
self._connections_changed = asyncio.Event()
|
|
138
|
+
self._started = asyncio.Event()
|
|
139
|
+
self._stdin_lock = asyncio.Lock()
|
|
140
|
+
self._process: asyncio.subprocess.Process | None = None
|
|
141
|
+
self._completion: asyncio.Task[int] | None = None
|
|
142
|
+
self._on_output = on_output
|
|
143
|
+
self._on_input_echo = on_input_echo
|
|
144
|
+
self._input_decoder = codecs.getincrementaldecoder(input_encoding) if on_input_echo else None
|
|
145
|
+
self._close_stdin_on_eof = close_stdin_on_eof
|
|
146
|
+
self._cwd = cwd
|
|
147
|
+
self._env = env
|
|
148
|
+
self._closed = False
|
|
149
|
+
|
|
150
|
+
async def __aenter__(self) -> Supervisor:
|
|
151
|
+
await self.listen()
|
|
152
|
+
return self
|
|
153
|
+
|
|
154
|
+
async def __aexit__(
|
|
155
|
+
self,
|
|
156
|
+
exc_type: type[BaseException] | None,
|
|
157
|
+
exc_value: BaseException | None,
|
|
158
|
+
traceback: TracebackType | None,
|
|
159
|
+
) -> None:
|
|
160
|
+
await self.aclose()
|
|
161
|
+
|
|
162
|
+
@property
|
|
163
|
+
def pid(self) -> int | None:
|
|
164
|
+
return None if self._process is None else self._process.pid
|
|
165
|
+
|
|
166
|
+
@property
|
|
167
|
+
def returncode(self) -> int | None:
|
|
168
|
+
return None if self._process is None else self._process.returncode
|
|
169
|
+
|
|
170
|
+
@property
|
|
171
|
+
def stdin_open(self) -> bool:
|
|
172
|
+
return (
|
|
173
|
+
self._process is not None
|
|
174
|
+
and self._process.returncode is None
|
|
175
|
+
and self._process.stdin is not None
|
|
176
|
+
and not self._process.stdin.is_closing()
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
def status(self) -> dict[Endpoint, PortStatus]:
|
|
180
|
+
"""Return a snapshot of the bound ports and active client counts."""
|
|
181
|
+
return {
|
|
182
|
+
endpoint: PortStatus(
|
|
183
|
+
endpoint,
|
|
184
|
+
HOST,
|
|
185
|
+
self._bound_ports.get(endpoint, port),
|
|
186
|
+
endpoint in self._servers and self._servers[endpoint].is_serving(),
|
|
187
|
+
len(self._clients[endpoint]),
|
|
188
|
+
)
|
|
189
|
+
for endpoint, port in self._port_bindings.items()
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async def listen(self) -> None:
|
|
193
|
+
"""Bind the configured ports without launching the command."""
|
|
194
|
+
if self._closed:
|
|
195
|
+
raise RuntimeError("supervisor is closed")
|
|
196
|
+
if self._servers:
|
|
197
|
+
return
|
|
198
|
+
try:
|
|
199
|
+
for endpoint, port in self._port_bindings.items():
|
|
200
|
+
def connected(
|
|
201
|
+
reader: asyncio.StreamReader,
|
|
202
|
+
writer: asyncio.StreamWriter,
|
|
203
|
+
endpoint: Endpoint = endpoint,
|
|
204
|
+
) -> None:
|
|
205
|
+
self._connect(endpoint, reader, writer)
|
|
206
|
+
|
|
207
|
+
server = await asyncio.start_server(
|
|
208
|
+
connected, HOST, port, start_serving=False
|
|
209
|
+
)
|
|
210
|
+
self._servers[endpoint] = server
|
|
211
|
+
self._bound_ports[endpoint] = server.sockets[0].getsockname()[1]
|
|
212
|
+
for server in self._servers.values():
|
|
213
|
+
await server.start_serving()
|
|
214
|
+
except BaseException:
|
|
215
|
+
await self.aclose()
|
|
216
|
+
raise
|
|
217
|
+
|
|
218
|
+
async def wait_for_output_clients(self) -> None:
|
|
219
|
+
"""Wait until each output port has at least one connected reader."""
|
|
220
|
+
while self._servers:
|
|
221
|
+
if all(clients for endpoint, clients in self._clients.items() if endpoint is not Stream.STDIN):
|
|
222
|
+
return
|
|
223
|
+
self._connections_changed.clear()
|
|
224
|
+
await self._connections_changed.wait()
|
|
225
|
+
raise RuntimeError("output ports are not listening")
|
|
226
|
+
|
|
227
|
+
async def start(self) -> None:
|
|
228
|
+
"""Bind the listeners if necessary and launch the command without a shell."""
|
|
229
|
+
if self._process is not None:
|
|
230
|
+
raise RuntimeError("the command has already been started")
|
|
231
|
+
await self.listen()
|
|
232
|
+
try:
|
|
233
|
+
self._process = await asyncio.create_subprocess_exec(
|
|
234
|
+
*self.command,
|
|
235
|
+
stdin=asyncio.subprocess.PIPE,
|
|
236
|
+
stdout=asyncio.subprocess.PIPE,
|
|
237
|
+
stderr=asyncio.subprocess.PIPE,
|
|
238
|
+
cwd=self._cwd,
|
|
239
|
+
env=_piped_environment(self.command[0], self._env),
|
|
240
|
+
start_new_session=os.name == "posix",
|
|
241
|
+
)
|
|
242
|
+
except BaseException:
|
|
243
|
+
await self.aclose()
|
|
244
|
+
raise
|
|
245
|
+
self._started.set()
|
|
246
|
+
self._completion = asyncio.create_task(self._run(self._process))
|
|
247
|
+
|
|
248
|
+
async def wait(self) -> int:
|
|
249
|
+
"""Return the child's exit code after draining stdout and stderr."""
|
|
250
|
+
if self._completion is None:
|
|
251
|
+
raise RuntimeError("the command has not been started")
|
|
252
|
+
return await asyncio.shield(self._completion)
|
|
253
|
+
|
|
254
|
+
async def send(self, data: bytes) -> None:
|
|
255
|
+
"""Write bytes to the child's stdin, or raise BrokenPipeError if closed."""
|
|
256
|
+
async with self._stdin_lock:
|
|
257
|
+
if not self.stdin_open or self._process is None:
|
|
258
|
+
raise BrokenPipeError("child stdin is not open")
|
|
259
|
+
writer = self._process.stdin
|
|
260
|
+
assert writer is not None
|
|
261
|
+
writer.write(data)
|
|
262
|
+
await writer.drain()
|
|
263
|
+
|
|
264
|
+
async def close_stdin(self) -> None:
|
|
265
|
+
"""Send EOF to the child after all preceding writes."""
|
|
266
|
+
async with self._stdin_lock:
|
|
267
|
+
if self._process is not None and self._process.stdin is not None:
|
|
268
|
+
self._process.stdin.close()
|
|
269
|
+
|
|
270
|
+
def forward_console_interrupt(self) -> None:
|
|
271
|
+
"""Relay a terminal interrupt on POSIX; Windows delivers it natively."""
|
|
272
|
+
if os.name == "posix":
|
|
273
|
+
self._stop(signal.SIGINT)
|
|
274
|
+
|
|
275
|
+
def terminate(self) -> None:
|
|
276
|
+
"""Terminate the child (and its process group on POSIX)."""
|
|
277
|
+
self._stop(signal.SIGTERM)
|
|
278
|
+
|
|
279
|
+
async def aclose(self) -> None:
|
|
280
|
+
"""Stop a running command and release sockets; safe to call more than once."""
|
|
281
|
+
if self._closed:
|
|
282
|
+
return
|
|
283
|
+
self._closed = True
|
|
284
|
+
if self._completion is not None and not self._completion.done():
|
|
285
|
+
self.terminate()
|
|
286
|
+
try:
|
|
287
|
+
await asyncio.wait_for(self.wait(), SHUTDOWN_TIMEOUT)
|
|
288
|
+
except TimeoutError:
|
|
289
|
+
self._stop(signal.SIGKILL if os.name == "posix" else signal.SIGTERM)
|
|
290
|
+
try:
|
|
291
|
+
await asyncio.wait_for(self.wait(), SHUTDOWN_TIMEOUT)
|
|
292
|
+
except TimeoutError:
|
|
293
|
+
self._completion.cancel()
|
|
294
|
+
with suppress(asyncio.CancelledError):
|
|
295
|
+
await self._completion
|
|
296
|
+
await self._close_network()
|
|
297
|
+
|
|
298
|
+
def _stop(self, signum: int) -> None:
|
|
299
|
+
if self._process is None:
|
|
300
|
+
return
|
|
301
|
+
with suppress(ProcessLookupError):
|
|
302
|
+
if os.name == "posix":
|
|
303
|
+
os.killpg(self._process.pid, signum)
|
|
304
|
+
elif self._process.returncode is None:
|
|
305
|
+
self._process.terminate()
|
|
306
|
+
|
|
307
|
+
async def _run(self, process: asyncio.subprocess.Process) -> int:
|
|
308
|
+
assert process.stdout is not None and process.stderr is not None
|
|
309
|
+
try:
|
|
310
|
+
async with asyncio.TaskGroup() as tasks:
|
|
311
|
+
tasks.create_task(self._pump(Stream.STDOUT, process.stdout))
|
|
312
|
+
tasks.create_task(self._pump(Stream.STDERR, process.stderr))
|
|
313
|
+
return await process.wait()
|
|
314
|
+
except BaseException:
|
|
315
|
+
self._stop(signal.SIGKILL if os.name == "posix" else signal.SIGTERM)
|
|
316
|
+
raise
|
|
317
|
+
finally:
|
|
318
|
+
await self._close_network()
|
|
319
|
+
|
|
320
|
+
async def _pump(self, stream: Stream, reader: asyncio.StreamReader) -> None:
|
|
321
|
+
endpoint: Endpoint = "output" if self._merged_output else stream
|
|
322
|
+
clients = self._clients[endpoint]
|
|
323
|
+
while data := await reader.read(CHUNK_SIZE):
|
|
324
|
+
if clients:
|
|
325
|
+
packet = data
|
|
326
|
+
if self._merged_output:
|
|
327
|
+
packet = _FRAME_HEADER.pack(_OUTPUT_STREAM_IDS[stream], len(data)) + data
|
|
328
|
+
for writer in tuple(clients):
|
|
329
|
+
if writer.is_closing():
|
|
330
|
+
continue
|
|
331
|
+
writer.write(packet)
|
|
332
|
+
if writer.transport.get_write_buffer_size() > CLIENT_BUFFER_LIMIT:
|
|
333
|
+
writer.transport.abort()
|
|
334
|
+
if self._on_output is not None:
|
|
335
|
+
result = self._on_output(stream, data)
|
|
336
|
+
if inspect.isawaitable(result):
|
|
337
|
+
await result
|
|
338
|
+
|
|
339
|
+
def _connect(
|
|
340
|
+
self, endpoint: Endpoint, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
|
|
341
|
+
) -> None:
|
|
342
|
+
if endpoint not in self._servers:
|
|
343
|
+
writer.close()
|
|
344
|
+
return
|
|
345
|
+
self._clients[endpoint].add(writer)
|
|
346
|
+
self._connections_changed.set()
|
|
347
|
+
task = asyncio.create_task(self._serve_client(endpoint, reader, writer))
|
|
348
|
+
self._client_tasks.add(task)
|
|
349
|
+
task.add_done_callback(self._client_tasks.discard)
|
|
350
|
+
|
|
351
|
+
async def _serve_client(
|
|
352
|
+
self, endpoint: Endpoint, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
|
|
353
|
+
) -> None:
|
|
354
|
+
try:
|
|
355
|
+
if endpoint is Stream.STDIN:
|
|
356
|
+
await self._serve_input(reader)
|
|
357
|
+
return
|
|
358
|
+
while await reader.read(CHUNK_SIZE):
|
|
359
|
+
pass
|
|
360
|
+
except (OSError, ValueError):
|
|
361
|
+
pass
|
|
362
|
+
finally:
|
|
363
|
+
self._clients[endpoint].discard(writer)
|
|
364
|
+
writer.close()
|
|
365
|
+
|
|
366
|
+
async def _serve_input(self, reader: asyncio.StreamReader) -> None:
|
|
367
|
+
lines = _InputLines()
|
|
368
|
+
decoder = self._input_decoder("replace") if self._input_decoder is not None else None
|
|
369
|
+
|
|
370
|
+
async def echo(data: bytes, *, final: bool = False) -> None:
|
|
371
|
+
if decoder is not None and self._on_input_echo is not None:
|
|
372
|
+
if text := decoder.decode(data, final=final):
|
|
373
|
+
result = self._on_input_echo(text)
|
|
374
|
+
if inspect.isawaitable(result):
|
|
375
|
+
await result
|
|
376
|
+
|
|
377
|
+
while data := await reader.read(CHUNK_SIZE):
|
|
378
|
+
await echo(data)
|
|
379
|
+
for line in lines.feed(data):
|
|
380
|
+
await self._started.wait()
|
|
381
|
+
await self.send(line)
|
|
382
|
+
await echo(b"", final=True)
|
|
383
|
+
if self._close_stdin_on_eof:
|
|
384
|
+
await self._started.wait()
|
|
385
|
+
await self.close_stdin()
|
|
386
|
+
|
|
387
|
+
async def _close_network(self) -> None:
|
|
388
|
+
servers = tuple(self._servers.values())
|
|
389
|
+
if not servers:
|
|
390
|
+
return
|
|
391
|
+
self._servers.clear()
|
|
392
|
+
self._connections_changed.set()
|
|
393
|
+
for server in servers:
|
|
394
|
+
server.close()
|
|
395
|
+
writers = [writer for clients in self._clients.values() for writer in clients]
|
|
396
|
+
for clients in self._clients.values():
|
|
397
|
+
clients.clear()
|
|
398
|
+
for task in tuple(self._client_tasks):
|
|
399
|
+
task.cancel()
|
|
400
|
+
for writer in writers:
|
|
401
|
+
writer.close()
|
|
402
|
+
try:
|
|
403
|
+
async with asyncio.timeout(SHUTDOWN_TIMEOUT):
|
|
404
|
+
await asyncio.gather(
|
|
405
|
+
*(writer.wait_closed() for writer in writers),
|
|
406
|
+
*(server.wait_closed() for server in servers),
|
|
407
|
+
return_exceptions=True,
|
|
408
|
+
)
|
|
409
|
+
except TimeoutError:
|
|
410
|
+
for writer in writers:
|
|
411
|
+
writer.transport.abort()
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: side-cli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Supervise a command and bridge its standard streams over local TCP.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Python: >=3.11
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
|
|
10
|
+
# side-cli
|
|
11
|
+
|
|
12
|
+
Run a command with piped standard streams and bridge them to local TCP ports.
|
|
13
|
+
Use the console, the Tk desktop window, or the async Python API. Receive
|
|
14
|
+
stdout and stderr on separate ports or on one framed output port.
|
|
15
|
+
|
|
16
|
+
## Quick start
|
|
17
|
+
|
|
18
|
+
Install [uv](https://docs.astral.sh/uv/getting-started/installation/) and run
|
|
19
|
+
these commands from the project directory. The project requires Python 3.11
|
|
20
|
+
or later and has no third-party runtime dependencies.
|
|
21
|
+
|
|
22
|
+
```shell
|
|
23
|
+
uv sync --locked
|
|
24
|
+
uv run side-cli run -- python -u -c "import sys; print('Ready'); print('Status', file=sys.stderr); print(input())"
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Type a line in the terminal, or send it to the stdin TCP port. The example
|
|
28
|
+
prints the line and exits. `side_cli` and `python -m side_cli` are also entry
|
|
29
|
+
points. Put `run` options before `--` and the child command and its arguments
|
|
30
|
+
after it. Run `side-cli run --help` for supervisor options.
|
|
31
|
+
Commands run directly; use an explicit shell for shell syntax, for example
|
|
32
|
+
`-- sh -c "printf 'hello\n'"` on Linux or `-- cmd /c "echo hello"` on Windows.
|
|
33
|
+
|
|
34
|
+
```shell
|
|
35
|
+
uv run side-cli run --gui -- python -u -c "import sys; print('Ready'); print('Status', file=sys.stderr); print(input())"
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
The GUI shows stdout and stderr in the left-hand console. Both use the same
|
|
39
|
+
default colors; ANSI color sequences in each stream control their text colors.
|
|
40
|
+
When the end of the output is visible, a blinking caret marks it without
|
|
41
|
+
changing the text or taking keyboard focus.
|
|
42
|
+
Click the output to focus the input field; selecting output text keeps focus
|
|
43
|
+
in the output so it can be copied.
|
|
44
|
+
On the right, **Send** echoes the text immediately. Uncheck **Append newline**
|
|
45
|
+
to add text to the pending line without writing to the child yet. Send a
|
|
46
|
+
newline to deliver the full line, including the newline, to the child.
|
|
47
|
+
The TCP panel shows each bound address, listening state, and active connection
|
|
48
|
+
count. The window keeps the output visible after the command exits. Closing
|
|
49
|
+
the window stops a command that is still running. GUI mode requires Tkinter
|
|
50
|
+
and a desktop session; run `uv run python -m tkinter` to check. If you use the
|
|
51
|
+
system Python on Debian or Ubuntu, install its `python3-tk` package if needed.
|
|
52
|
+
|
|
53
|
+
## TCP and process behavior
|
|
54
|
+
|
|
55
|
+
| Stream | Default address | Direction |
|
|
56
|
+
| --- | --- | --- |
|
|
57
|
+
| stdin | `127.0.0.1:8765` | TCP client to child stdin |
|
|
58
|
+
| stdout | `127.0.0.1:8766` | Child stdout to connected TCP clients |
|
|
59
|
+
| stderr | `127.0.0.1:8767` | Child stderr to connected TCP clients |
|
|
60
|
+
|
|
61
|
+
- Configure ports with `--stdin-port`, `--stdout-port`, and `--stderr-port`.
|
|
62
|
+
Use `0` for an available port and `--show-ports` to print the actual addresses.
|
|
63
|
+
Listeners accept unauthenticated connections from the local machine only.
|
|
64
|
+
- The stdin port carries LF-delimited byte frames. Separate output ports
|
|
65
|
+
carry raw bytes. Output goes to clients
|
|
66
|
+
connected at the time of the write, with no replay. To capture output from
|
|
67
|
+
the first byte, use `--wait-for-output-clients` and connect to each enabled
|
|
68
|
+
output port before the child starts. Keep output clients connected in both
|
|
69
|
+
directions until done. A slow client may be disconnected to keep other
|
|
70
|
+
readers moving.
|
|
71
|
+
- Both modes mirror the child's stdout and stderr separately. Console mode
|
|
72
|
+
also forwards terminal or piped stdin, unless you set `--no-local-stdin`.
|
|
73
|
+
The GUI, local stdin, and each input connection buffer their own input
|
|
74
|
+
until a newline. Complete lines from concurrent sources can interleave
|
|
75
|
+
only between lines. On EOF an incomplete line is discarded; stdin stays
|
|
76
|
+
open for other clients unless `--close-stdin-on-eof` is set. Combine that
|
|
77
|
+
option with `--no-local-stdin` for commands that read TCP input until EOF.
|
|
78
|
+
- Input echo is a local display feature. The GUI and the terminal running
|
|
79
|
+
`side-cli run` show submitted GUI and TCP input, even before a newline.
|
|
80
|
+
A terminal keyboard already provides its own echo. Synthetic echo is not
|
|
81
|
+
sent to the child, the TCP output ports, `panel`, or redirected stdout or
|
|
82
|
+
stderr. Output echoed by the child itself is still forwarded normally.
|
|
83
|
+
- Ctrl+C reaches the child as `SIGINT` on Linux. On Windows, the child shares
|
|
84
|
+
the console and receives the native Ctrl+C event directly. A child that
|
|
85
|
+
handles the interrupt can clean up or continue. Console mode returns the
|
|
86
|
+
child's exit code, with POSIX signal exits reported as `128 + signal`.
|
|
87
|
+
- The child gets pipes, not a terminal. For timely output from buffered
|
|
88
|
+
commands, enable their unbuffered mode (such as Python's `-u`). The GUI
|
|
89
|
+
renders ANSI foreground and background colors (basic, bright, 256-color,
|
|
90
|
+
and RGB), but does not emulate cursor movement or screen clearing. If a
|
|
91
|
+
command disables colors when writing to a pipe, use its force-color option.
|
|
92
|
+
- On Windows, when launching `cmd.exe` directly, side-cli removes Clink's
|
|
93
|
+
hidden tag from the child `PROMPT` but preserves the rest of the prompt.
|
|
94
|
+
Clink's interactive editing and completion still require a console.
|
|
95
|
+
|
|
96
|
+
## Text encoding
|
|
97
|
+
|
|
98
|
+
`--encoding` describes the encoding used by the child process. It defaults to
|
|
99
|
+
`utf-8` and accepts Python text encodings such as `gb2312`, `gbk`, and `cp936`.
|
|
100
|
+
Choose the encoding that matches the command; the option does not change the
|
|
101
|
+
child's locale or code page.
|
|
102
|
+
|
|
103
|
+
```shell
|
|
104
|
+
uv run side-cli run --gui --encoding gb2312 -- cmd.exe
|
|
105
|
+
uv run side-cli panel --port 8766 --encoding gb2312
|
|
106
|
+
uv run side-cli input --port 8765 --encoding gb2312
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
`run` converts terminal and GUI text in both directions. `panel` decodes
|
|
110
|
+
output for the terminal, and `input` encodes lines typed at the terminal.
|
|
111
|
+
Redirected files and pipes, TCP payloads, and the byte-oriented Python API
|
|
112
|
+
do not transcode. Byte-framed input uses encodings with an ASCII LF, such as
|
|
113
|
+
UTF-8, GB2312, and GBK. Each client sets its own encoding for terminal display or
|
|
114
|
+
entry; the TCP protocol does not negotiate encodings.
|
|
115
|
+
|
|
116
|
+
## Single framed output port
|
|
117
|
+
|
|
118
|
+
Set `--output-port` to replace both output TCP listeners with one connection
|
|
119
|
+
point carrying both streams. This option cannot be combined with
|
|
120
|
+
`--stdout-port` or `--stderr-port`. The stdin listener, local output, and GUI
|
|
121
|
+
ANSI rendering keep their existing behavior. The GUI and `--show-ports`
|
|
122
|
+
report one combined output listener; `--wait-for-output-clients` waits for
|
|
123
|
+
one client on it.
|
|
124
|
+
|
|
125
|
+
```shell
|
|
126
|
+
uv run side-cli run --output-port 8766 --wait-for-output-clients --no-local-stdin -- python -u -c "import sys; print('Ready'); print('Status', file=sys.stderr); sys.stdout.writelines(sys.stdin)"
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
In a second terminal, connect to the framed output port:
|
|
130
|
+
|
|
131
|
+
```shell
|
|
132
|
+
uv run side-cli panel --port 8766
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
`panel` writes frames to its own stdout or stderr according to their stream
|
|
136
|
+
ID. Redirect either stream independently to capture its raw bytes. The child
|
|
137
|
+
still writes to the supervisor's own stdout and stderr too.
|
|
138
|
+
|
|
139
|
+
In a third terminal, send lines to the stdin port:
|
|
140
|
+
|
|
141
|
+
```shell
|
|
142
|
+
uv run side-cli input --port 8765
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
`input` writes nothing to stdout and reports connection errors to stderr.
|
|
146
|
+
It forwards complete lines, preserving line endings, and drops any final
|
|
147
|
+
unterminated line at local EOF. Multiple input clients can connect at once.
|
|
148
|
+
Ctrl+C disconnects
|
|
149
|
+
that input client without sending a signal or an orderly EOF to the child.
|
|
150
|
+
An ordinary local EOF disconnects cleanly and leaves child stdin open unless
|
|
151
|
+
the supervisor was started with `--close-stdin-on-eof`. Use separate terminals
|
|
152
|
+
for the supervisor and its clients so Ctrl+C goes to the intended command.
|
|
153
|
+
|
|
154
|
+
### Frame format
|
|
155
|
+
|
|
156
|
+
The **stdin** connection uses LF (`0x0a`) as the frame delimiter. A frame
|
|
157
|
+
includes its delimiter; CRLF is passed through unchanged. One TCP read may
|
|
158
|
+
contain several frames, and a single frame can span reads. The supervisor
|
|
159
|
+
buffers at most 1 MiB per line, including the delimiter. An oversized line
|
|
160
|
+
closes that input connection. An incomplete line is never written to the child.
|
|
161
|
+
|
|
162
|
+
The combined **output** port uses a separate protocol:
|
|
163
|
+
|
|
164
|
+
The connection carries consecutive binary frames with no initial preamble:
|
|
165
|
+
|
|
166
|
+
| Field | Size | Value |
|
|
167
|
+
| --- | --- | --- |
|
|
168
|
+
| Stream ID | 1 byte | `1` = stdout, `2` = stderr |
|
|
169
|
+
| Payload length | 4 bytes | Unsigned big-endian byte count, 1–65,536 |
|
|
170
|
+
| Payload | As specified above | Raw bytes from the selected stream, including ANSI escapes |
|
|
171
|
+
|
|
172
|
+
Read five bytes for the header, then exactly the specified number of payload
|
|
173
|
+
bytes. Frames represent chunks, not lines, characters, or individual child
|
|
174
|
+
writes. Each stream retains its own byte order. Frames from the two streams
|
|
175
|
+
interleave in the order side-cli reads them. EOF at a frame boundary ends the
|
|
176
|
+
connection; EOF inside a frame indicates truncation.
|
|
177
|
+
|
|
178
|
+
## Python API
|
|
179
|
+
|
|
180
|
+
Import `Supervisor`, `Ports`, and `Stream` from `side_cli`. An async context
|
|
181
|
+
opens the listeners on entry and releases them on exit. `start()` launches
|
|
182
|
+
the child; `wait()` drains its output and returns its original exit code.
|
|
183
|
+
|
|
184
|
+
```python
|
|
185
|
+
import asyncio
|
|
186
|
+
import sys
|
|
187
|
+
|
|
188
|
+
from side_cli import Ports, Stream, Supervisor
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def show_output(stream: Stream, data: bytes) -> None:
|
|
192
|
+
destination = sys.stdout if stream is Stream.STDOUT else sys.stderr
|
|
193
|
+
destination.buffer.write(data)
|
|
194
|
+
destination.buffer.flush()
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
async def main() -> int:
|
|
198
|
+
command = [sys.executable, "-u", "-c", "print(input())"]
|
|
199
|
+
async with Supervisor(command, ports=Ports(0, 0, 0), on_output=show_output) as child:
|
|
200
|
+
print(child.status()[Stream.STDIN].port, flush=True)
|
|
201
|
+
await child.start()
|
|
202
|
+
await child.send(b"Hello from Python\n")
|
|
203
|
+
await child.close_stdin()
|
|
204
|
+
return await child.wait()
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
if __name__ == "__main__":
|
|
208
|
+
raise SystemExit(asyncio.run(main()))
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
`on_output` can also be an async function. It receives raw chunks in order
|
|
212
|
+
within each stream; stdout and stderr may interleave. `status()` exposes port
|
|
213
|
+
and connection information, including when the child has not started yet.
|
|
214
|
+
`Supervisor.send()` is the low-level raw stdin write for programs that need
|
|
215
|
+
to bypass line framing. To display TCP input separately, supply
|
|
216
|
+
`on_input_echo` with a synchronous or async callback that receives text
|
|
217
|
+
decoded with `input_encoding` (UTF-8 by default).
|
|
218
|
+
Pass `Ports(stdin=0, output=0)` to enable framed mode with automatic ports.
|
|
219
|
+
In this mode, `status()["output"]` reports the combined listener, and
|
|
220
|
+
`on_output` still receives the original `Stream.STDOUT` or `Stream.STDERR`.
|
|
221
|
+
The `stdout` and `stderr` port settings apply only in separate-port mode.
|
|
222
|
+
Call `listen()` directly if you need to bind before starting without a context
|
|
223
|
+
manager, and use `aclose()` to clean up. An embedding app owns its own signal
|
|
224
|
+
handlers. On Windows, use the default asyncio Proactor event loop.
|
|
225
|
+
|
|
226
|
+
### TCP clients
|
|
227
|
+
|
|
228
|
+
Import `PanelClient` and `InputClient` from `side_cli`. Both connect to the
|
|
229
|
+
local supervisor as async context managers. `PanelClient` yields
|
|
230
|
+
`(Stream.STDOUT, bytes)` or `(Stream.STDERR, bytes)` pairs until the connection
|
|
231
|
+
ends; malformed or truncated frames raise `ValueError`. `InputClient.send()`
|
|
232
|
+
writes bytes unchanged to the TCP connection, and `send_line()` appends an LF
|
|
233
|
+
if one is missing. The supervisor only forwards complete LF-delimited lines.
|
|
234
|
+
Context cancellation aborts the input connection rather than sending an
|
|
235
|
+
orderly EOF. Use `close(abort=True)` for an explicit abort.
|
|
236
|
+
|
|
237
|
+
```python
|
|
238
|
+
import sys
|
|
239
|
+
|
|
240
|
+
from side_cli import InputClient, PanelClient, Stream
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
async def receive_output(port: int = 8766) -> None:
|
|
244
|
+
async with PanelClient(port) as panel:
|
|
245
|
+
async for stream, data in panel:
|
|
246
|
+
destination = sys.stdout if stream is Stream.STDOUT else sys.stderr
|
|
247
|
+
destination.buffer.write(data)
|
|
248
|
+
destination.buffer.flush()
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
async def send_input(port: int = 8765) -> None:
|
|
252
|
+
async with InputClient(port) as client:
|
|
253
|
+
await client.send_line(b"Hello from Python")
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
## Build
|
|
257
|
+
|
|
258
|
+
```shell
|
|
259
|
+
uv build
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
Released under the [MIT License](LICENSE).
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
side_cli/__init__.py,sha256=F2w3E5fl2hZCj1mc-eETvNrUGKgOU4Wg5DpJ0NSAYOI,290
|
|
2
|
+
side_cli/__main__.py,sha256=MHKZ_ae3fSLGTLUUMOx15fWdeOnJSHhq-zslRP5F5Lc,79
|
|
3
|
+
side_cli/ansi.py,sha256=-KoixNOs30U6hQgpl5x-8fNHHyA4VUH_Q_zKlyof00E,5985
|
|
4
|
+
side_cli/cli.py,sha256=qzPXKmDi7ljiT4izDUbzpvB0H8jfOc9dTplkR_YQvfY,16648
|
|
5
|
+
side_cli/clients.py,sha256=BaWTl-HxlnC98Gm47S2tQqvG1kOG_zNbGxFbJrAzK7k,5012
|
|
6
|
+
side_cli/gui.py,sha256=uGl94gz1BDMLp1j-_SALGL6LPS58gDOpuw6UAfS1ObA,11642
|
|
7
|
+
side_cli/supervisor.py,sha256=xzBwND4hla0qHPrFSmw2L1DSiEzUkWhZPHfd4cyV3eM,15383
|
|
8
|
+
side_cli-0.1.0.dist-info/licenses/LICENSE,sha256=Bp5L8QrzCqB7bWBnz3EAAbQqa3MiiFsPl_LKJbEILTQ,1065
|
|
9
|
+
side_cli-0.1.0.dist-info/WHEEL,sha256=G_-rrEibZr7OEM7zdH1dSO6s-VdjfnS5PA4CLAdI9Vw,80
|
|
10
|
+
side_cli-0.1.0.dist-info/entry_points.txt,sha256=JD6w7UUYwh7O7StF_0vIrEsh0IXMrxyn5DEIrUcalD4,77
|
|
11
|
+
side_cli-0.1.0.dist-info/METADATA,sha256=3ghB3dZvdplAtPEXAtfCESe6epEX0rj4cnhCb6vUJbM,12007
|
|
12
|
+
side_cli-0.1.0.dist-info/RECORD,,
|