libvt 0.0.1a0__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.
libvt/aio.py ADDED
@@ -0,0 +1,787 @@
1
+ """Transport-only ``asyncio`` stream and POSIX PTY adapters over :class:`Terminal`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import collections.abc
7
+ import contextlib
8
+ import dataclasses
9
+ import errno
10
+ import os
11
+ import signal
12
+ import socket
13
+ import struct
14
+ import sys
15
+ import time
16
+ import typing as t
17
+
18
+ from libvt.config import (
19
+ DEFAULT_LIMITS,
20
+ DEFAULT_OSC7_HOSTS,
21
+ DEFAULT_POLICY,
22
+ DEFAULT_PROFILE,
23
+ Limits,
24
+ Policy,
25
+ Profile,
26
+ )
27
+ from libvt.exc import TerminalTimeoutError
28
+ from libvt.input import InputEvent, KeyEvent, PasteEvent
29
+ from libvt.terminal import FlightRecorder, Snapshot, Terminal
30
+
31
+ type TtyMode = t.Literal["cooked", "cbreak", "raw"]
32
+
33
+ _PTY_TRAMPOLINE = (
34
+ "stage = 'bootstrap'\n"
35
+ "err_fd = -1\n"
36
+ "try:\n"
37
+ " import errno, fcntl, os, signal, sys, termios\n"
38
+ " err_fd = int(sys.argv[1])\n"
39
+ " os.set_inheritable(err_fd, False)\n"
40
+ " stage = 'ctty'\n"
41
+ " if hasattr(termios, 'TIOCSCTTY'):\n"
42
+ " fcntl.ioctl(0, termios.TIOCSCTTY, 0)\n"
43
+ " stage = 'signal'\n"
44
+ " signal.signal(signal.SIGPIPE, signal.SIG_DFL)\n"
45
+ " if hasattr(signal, 'SIGXFSZ'):\n"
46
+ " signal.signal(signal.SIGXFSZ, signal.SIG_DFL)\n"
47
+ " stage = 'exec'\n"
48
+ " os.write(err_fd, b'\\x00')\n"
49
+ " os.execvp(sys.argv[2], sys.argv[2:])\n"
50
+ "except BaseException as exc:\n"
51
+ " try:\n"
52
+ " import errno as _e, os as _os\n"
53
+ " if err_fd >= 0:\n"
54
+ " code = getattr(exc, 'errno', None)\n"
55
+ " if not isinstance(code, int):\n"
56
+ " code = _e.ENOEXEC\n"
57
+ " msg = (getattr(exc, 'strerror', None) or str(exc))[:360]\n"
58
+ " pkt = b'\\x01' + f'{stage}:{code}:{msg}'.encode('utf-8', 'replace')\n"
59
+ " _os.write(err_fd, pkt[:500])\n"
60
+ " except BaseException:\n"
61
+ " pass\n"
62
+ " import os as _os2\n"
63
+ " _os2._exit(127)\n"
64
+ )
65
+
66
+
67
+ def _raise_exec_error(err_payload: bytes, cmd: str, default_errno: int) -> t.NoReturn:
68
+ if not err_payload:
69
+ msg = f"PTY launcher exited before pre-exec handoff while starting {cmd!r}"
70
+ raise RuntimeError(msg)
71
+ idx = err_payload.find(b"\x01")
72
+ body = err_payload[idx + 1 :] if idx != -1 else err_payload
73
+ parts = body.decode("utf-8", "replace").split(":", 2)
74
+ if len(parts) == 3:
75
+ stage, code_s, err_msg = parts
76
+ else:
77
+ stage, code_s, err_msg = "exec", "", body.decode("utf-8", "replace")
78
+ err_no = int(code_s) if code_s.isdigit() else default_errno
79
+ target = cmd if stage == "exec" else f"open_pty({stage})"
80
+ raise OSError(err_no, err_msg or os.strerror(err_no), target)
81
+
82
+
83
+ async def _read_cloexec_pipe(loop: asyncio.AbstractEventLoop, fd: int) -> bytes:
84
+ """Read non-blocking *fd* until EOF without spawning executor threads."""
85
+ chunks: list[bytes] = []
86
+ done = loop.create_future()
87
+
88
+ def _on_ready() -> None:
89
+ while True:
90
+ try:
91
+ data = os.read(fd, 4_096)
92
+ except (BlockingIOError, InterruptedError):
93
+ return
94
+ except OSError as exc:
95
+ loop.remove_reader(fd)
96
+ if not done.done():
97
+ done.set_exception(exc)
98
+ return
99
+ if not data:
100
+ loop.remove_reader(fd)
101
+ if not done.done():
102
+ done.set_result(b"".join(chunks))
103
+ return
104
+ chunks.append(data)
105
+
106
+ loop.add_reader(fd, _on_ready)
107
+ try:
108
+ return await done
109
+ finally:
110
+ with contextlib.suppress(Exception):
111
+ loop.remove_reader(fd)
112
+
113
+
114
+ def _make_timeout_error(
115
+ terminal: Terminal,
116
+ snap: Snapshot,
117
+ header: str,
118
+ *,
119
+ eof: bool,
120
+ attach_note: bool = True,
121
+ ) -> TerminalTimeoutError:
122
+ from libvt.testing import format_flight_recorder, format_screen_box
123
+
124
+ rec = terminal.recorder
125
+ recent = rec.tail(256) if rec is not None else b""
126
+ box = format_screen_box(snap, rows=min(snap.rows, 12), cols=min(snap.cols, 80))
127
+ diag = format_flight_recorder(terminal)
128
+ return TerminalTimeoutError(
129
+ header,
130
+ parser_state=terminal.parser_state,
131
+ screen_text=snap.text,
132
+ recent_bytes=recent,
133
+ eof=eof,
134
+ diagnostics=f"{box}\n{diag}",
135
+ attach_note=attach_note,
136
+ )
137
+
138
+
139
+ class ReplyWriter(t.Protocol):
140
+ """Structural writer protocol satisfied by :class:`asyncio.StreamWriter`."""
141
+
142
+ def write(self, data: bytes, /) -> object:
143
+ """Buffer outbound *data* bytes."""
144
+
145
+ async def drain(self) -> None:
146
+ """Flush buffered outbound bytes."""
147
+
148
+ def close(self) -> object:
149
+ """Initiate writer close."""
150
+
151
+ async def wait_closed(self) -> None:
152
+ """Wait until writer close completes."""
153
+
154
+
155
+ class AsyncTerminalStream:
156
+ """Drive a sans-I/O :class:`~libvt.terminal.Terminal` from ``asyncio`` streams.
157
+
158
+ Coalesces frame wakeups across DEC mode ``?2026`` synchronized-output
159
+ batches (bounded by *sync_timeout* using generation-safe expiry) and
160
+ automatically flushes :meth:`~libvt.terminal.Terminal.drain_replies` when a
161
+ ``StreamWriter`` is attached.
162
+ """
163
+
164
+ def __init__(
165
+ self,
166
+ reader: asyncio.StreamReader,
167
+ writer: ReplyWriter | None = None,
168
+ *,
169
+ terminal: Terminal | None = None,
170
+ rows: int = 24,
171
+ cols: int = 80,
172
+ chunk_size: int = 4_096,
173
+ sync_timeout: float = 1.0,
174
+ ) -> None:
175
+ self.reader = reader
176
+ self.writer = writer
177
+ self.terminal = (
178
+ terminal
179
+ if terminal is not None
180
+ else Terminal(rows=rows, cols=cols, recorder=FlightRecorder())
181
+ )
182
+ self.chunk_size = chunk_size
183
+ self.sync_timeout = sync_timeout
184
+ self._frame_event = asyncio.Event()
185
+ self._eof = False
186
+ self._sync_started_at: float | None = None
187
+ self._sync_gen_tracked: int | None = None
188
+ self._task: asyncio.Task[None] | None = None
189
+
190
+ @property
191
+ def eof(self) -> bool:
192
+ """Return ``True`` once ``reader`` reaches end-of-stream."""
193
+ return self._eof
194
+
195
+ def _update_sync_timer(self, now: float) -> None:
196
+ if self.terminal.synchronized:
197
+ cur_gen = self.terminal.sync_generation
198
+ if self._sync_gen_tracked != cur_gen or self._sync_started_at is None:
199
+ self._sync_gen_tracked = cur_gen
200
+ self._sync_started_at = now
201
+ elif (
202
+ now - self._sync_started_at >= self.sync_timeout
203
+ and self.terminal.expire_synchronized_output(cur_gen)
204
+ ):
205
+ self._sync_started_at = None
206
+ self._sync_gen_tracked = None
207
+ self._frame_event.set()
208
+ else:
209
+ self._sync_started_at = None
210
+ self._sync_gen_tracked = None
211
+ self._frame_event.set()
212
+
213
+ async def pump_once(self) -> bool:
214
+ """Read and feed one chunk; return ``False`` on EOF."""
215
+ chunk = await self.reader.read(self.chunk_size)
216
+ if not chunk:
217
+ self._eof = True
218
+ self._frame_event.set()
219
+ return False
220
+ self.terminal.feed(chunk)
221
+ replies = self.terminal.drain_replies()
222
+ if replies and self.writer is not None:
223
+ self.writer.write(replies)
224
+ await self.writer.drain()
225
+ self._update_sync_timer(time.monotonic())
226
+ return True
227
+
228
+ async def _pump_loop(self) -> None:
229
+ try:
230
+ while await self.pump_once():
231
+ pass
232
+ finally:
233
+ self._frame_event.set()
234
+
235
+ def start(self) -> asyncio.Task[None]:
236
+ """Start background stream pumping on the running event loop."""
237
+ if self._task is None or self._task.done():
238
+ self._task = asyncio.create_task(self._pump_loop())
239
+ return self._task
240
+
241
+ async def aclose(self) -> None:
242
+ """Cancel background pump task and close the writer if present."""
243
+ if self._task is not None:
244
+ self._task.cancel()
245
+ with contextlib.suppress(asyncio.CancelledError):
246
+ await self._task
247
+ self._task = None
248
+ if self.writer is not None:
249
+ self.writer.close()
250
+ with contextlib.suppress(OSError):
251
+ await self.writer.wait_closed()
252
+
253
+ async def __aenter__(self) -> t.Self:
254
+ """Start background pumping when entering an ``async with`` block."""
255
+ self.start()
256
+ return self
257
+
258
+ async def __aexit__(
259
+ self,
260
+ exc_type: type[BaseException] | None,
261
+ exc: BaseException | None,
262
+ tb: object,
263
+ ) -> None:
264
+ """Stop background pumping and close writer when leaving ``async with``."""
265
+ await self.aclose()
266
+
267
+ async def wait_for(
268
+ self,
269
+ predicate: collections.abc.Callable[[Snapshot], bool] | str,
270
+ *,
271
+ timeout: float = 2.0,
272
+ attach_note: bool = True,
273
+ ) -> Snapshot:
274
+ """Wait until *predicate* matches the committed :class:`Snapshot`.
275
+
276
+ Parameters
277
+ ----------
278
+ predicate : collections.abc.Callable[[Snapshot], bool] | str
279
+ Callable tested against each committed snapshot, or a substring
280
+ searched inside ``snapshot.text``.
281
+ timeout : float
282
+ Maximum wait duration in seconds before raising
283
+ :exc:`~libvt.exc.TerminalTimeoutError`.
284
+ attach_note : bool
285
+ When ``True`` (default), attach multi-line screen and flight
286
+ recorder diagnostics via PEP 678 ``__notes__``.
287
+
288
+ Returns
289
+ -------
290
+ Snapshot
291
+ First matching :class:`~libvt.terminal.Snapshot`.
292
+
293
+ Raises
294
+ ------
295
+ TerminalTimeoutError
296
+ If the stream reaches EOF before matching (``eof=True``) or
297
+ *timeout* expires (``eof=False``).
298
+ """
299
+ check = (
300
+ (lambda snap: predicate in snap.text)
301
+ if isinstance(predicate, str)
302
+ else predicate
303
+ )
304
+ deadline = time.monotonic() + timeout
305
+ while True:
306
+ if self._task is not None and self._task.done():
307
+ if self._task.cancelled():
308
+ self._task = None
309
+ else:
310
+ task_exc = self._task.exception()
311
+ if task_exc is not None:
312
+ raise task_exc
313
+ now = time.monotonic()
314
+ if self.terminal.synchronized:
315
+ self._update_sync_timer(now)
316
+ snap = self.terminal.snapshot() if self._eof else self.terminal.committed
317
+ if check(snap):
318
+ return snap
319
+ if self._eof:
320
+ raise _make_timeout_error(
321
+ self.terminal,
322
+ snap,
323
+ "stream reached EOF before predicate matched",
324
+ eof=True,
325
+ attach_note=attach_note,
326
+ )
327
+ remaining = deadline - now
328
+ if remaining <= 0:
329
+ live = self.terminal.snapshot()
330
+ if check(live):
331
+ return live
332
+ raise _make_timeout_error(
333
+ self.terminal,
334
+ live,
335
+ f"timed out after {timeout:.2f}s waiting for terminal state",
336
+ eof=False,
337
+ attach_note=attach_note,
338
+ )
339
+ self._frame_event.clear()
340
+ if self.terminal.synchronized:
341
+ sync_rem = (
342
+ self.sync_timeout
343
+ if self._sync_started_at is None
344
+ else max(0.0, self._sync_started_at + self.sync_timeout - now)
345
+ )
346
+ wait_slice = min(remaining, sync_rem)
347
+ else:
348
+ wait_slice = remaining
349
+ if self._task is None:
350
+ with contextlib.suppress(TimeoutError):
351
+ await asyncio.wait_for(self.pump_once(), timeout=wait_slice)
352
+ if self.terminal.synchronized:
353
+ self._update_sync_timer(time.monotonic())
354
+ else:
355
+ with contextlib.suppress(TimeoutError):
356
+ await asyncio.wait_for(
357
+ self._frame_event.wait(),
358
+ timeout=wait_slice,
359
+ )
360
+ if self.terminal.synchronized:
361
+ self._update_sync_timer(time.monotonic())
362
+
363
+
364
+ class PtySession:
365
+ """Async POSIX pseudo-terminal subprocess session backed by :class:`Terminal`."""
366
+
367
+ def __init__(
368
+ self,
369
+ *,
370
+ master_fd: int,
371
+ process: asyncio.subprocess.Process,
372
+ terminal: Terminal,
373
+ sync_timeout: float = 1.0,
374
+ ) -> None:
375
+ self._master_fd = master_fd
376
+ self.process = process
377
+ self.terminal = terminal
378
+ self.sync_timeout = sync_timeout
379
+ self._frame_event = asyncio.Event()
380
+ self._eof = False
381
+ self._closed = False
382
+ self._sync_started_at: float | None = None
383
+ self._sync_gen_tracked: int | None = None
384
+ self._loop: asyncio.AbstractEventLoop | None = None
385
+
386
+ @property
387
+ def eof(self) -> bool:
388
+ """Return ``True`` once the PTY master reaches EOF."""
389
+ return self._eof
390
+
391
+ def _drain_nonblocking_master(self) -> None:
392
+ """Consume any buffered non-blocking bytes from ``master_fd``."""
393
+ if self._closed or self._eof:
394
+ return
395
+ while True:
396
+ try:
397
+ chunk = os.read(self._master_fd, 16_384)
398
+ except (BlockingIOError, InterruptedError):
399
+ return
400
+ except OSError as exc:
401
+ if exc.errno == errno.EIO:
402
+ chunk = b""
403
+ else:
404
+ return
405
+ if not chunk:
406
+ self._eof = True
407
+ return
408
+ self.terminal.feed(chunk)
409
+
410
+ def _on_readable(self) -> None:
411
+ if self._closed:
412
+ return
413
+ try:
414
+ chunk = os.read(self._master_fd, 16_384)
415
+ except (BlockingIOError, InterruptedError):
416
+ return
417
+ except OSError as exc:
418
+ if exc.errno == errno.EIO:
419
+ chunk = b""
420
+ else:
421
+ raise
422
+ if not chunk:
423
+ self._eof = True
424
+ if self._loop is not None:
425
+ self._loop.remove_reader(self._master_fd)
426
+ self._frame_event.set()
427
+ return
428
+ self.terminal.feed(chunk)
429
+ replies = self.terminal.drain_replies()
430
+ if replies:
431
+ with contextlib.suppress(OSError):
432
+ os.write(self._master_fd, replies)
433
+ now = time.monotonic()
434
+ if self.terminal.synchronized:
435
+ cur_gen = self.terminal.sync_generation
436
+ if self._sync_gen_tracked != cur_gen or self._sync_started_at is None:
437
+ self._sync_gen_tracked = cur_gen
438
+ self._sync_started_at = now
439
+ else:
440
+ self._sync_started_at = None
441
+ self._sync_gen_tracked = None
442
+ self._frame_event.set()
443
+
444
+ def send(self, data: bytes | str, /) -> None:
445
+ """Write raw *data* bytes (or UTF-8 string) to the PTY master."""
446
+ raw = data.encode("utf-8") if isinstance(data, str) else data
447
+ os.write(self._master_fd, raw)
448
+
449
+ def send_event(self, event: InputEvent, /) -> None:
450
+ """Encode *event* via :meth:`Terminal.encode` and write to the PTY."""
451
+ encoded = self.terminal.encode(event)
452
+ if encoded:
453
+ os.write(self._master_fd, encoded)
454
+
455
+ def send_key(self, chord: str, /) -> None:
456
+ """Parse *chord* (e.g. ``"ctrl+c"``, ``"enter"``) and send to the PTY."""
457
+ self.send_event(KeyEvent.parse(chord))
458
+
459
+ def paste(self, text: str, /, *, sanitize: bool = False) -> None:
460
+ """Encode *text* as a :class:`PasteEvent` and write to the PTY."""
461
+ self.send_event(PasteEvent(text=text, sanitize=sanitize))
462
+
463
+ def resize(
464
+ self,
465
+ *,
466
+ rows: int,
467
+ cols: int,
468
+ reflow: bool | None = None,
469
+ ) -> None:
470
+ """Update kernel ``TIOCSWINSZ`` and resize :attr:`terminal`."""
471
+ import fcntl
472
+ import termios
473
+
474
+ winsz = struct.pack("HHHH", rows, cols, 0, 0)
475
+ fcntl.ioctl(self._master_fd, termios.TIOCSWINSZ, winsz)
476
+ self.terminal.resize(rows=rows, cols=cols, reflow=reflow)
477
+
478
+ async def wait_for(
479
+ self,
480
+ predicate: collections.abc.Callable[[Snapshot], bool] | str,
481
+ *,
482
+ timeout: float = 2.0,
483
+ attach_note: bool = True,
484
+ ) -> Snapshot:
485
+ """Wait until *predicate* matches the committed :class:`Snapshot`.
486
+
487
+ Parameters
488
+ ----------
489
+ predicate : collections.abc.Callable[[Snapshot], bool] | str
490
+ Callable tested against each committed snapshot, or a substring
491
+ searched inside ``snapshot.text``.
492
+ timeout : float
493
+ Maximum wait duration in seconds before raising
494
+ :exc:`~libvt.exc.TerminalTimeoutError`.
495
+ attach_note : bool
496
+ When ``True`` (default), attach multi-line screen and flight
497
+ recorder diagnostics via PEP 678 ``__notes__``.
498
+
499
+ Returns
500
+ -------
501
+ Snapshot
502
+ First matching :class:`~libvt.terminal.Snapshot`.
503
+
504
+ Raises
505
+ ------
506
+ TerminalTimeoutError
507
+ If the PTY reaches EOF before matching (``eof=True``) or *timeout*
508
+ expires (``eof=False``).
509
+ """
510
+ check = (
511
+ (lambda snap: predicate in snap.text)
512
+ if isinstance(predicate, str)
513
+ else predicate
514
+ )
515
+ deadline = time.monotonic() + timeout
516
+ while True:
517
+ now = time.monotonic()
518
+ if (
519
+ self.terminal.synchronized
520
+ and self._sync_started_at is not None
521
+ and now - self._sync_started_at >= self.sync_timeout
522
+ ):
523
+ self.terminal.expire_synchronized_output(self._sync_gen_tracked)
524
+ self._sync_started_at = None
525
+ self._sync_gen_tracked = None
526
+ snap = self.terminal.snapshot() if self._eof else self.terminal.committed
527
+ if check(snap):
528
+ return snap
529
+ if self._eof:
530
+ raise _make_timeout_error(
531
+ self.terminal,
532
+ snap,
533
+ "PTY reached EOF before predicate matched",
534
+ eof=True,
535
+ attach_note=attach_note,
536
+ )
537
+ remaining = deadline - now
538
+ if remaining <= 0:
539
+ live = self.terminal.snapshot()
540
+ if check(live):
541
+ return live
542
+ raise _make_timeout_error(
543
+ self.terminal,
544
+ live,
545
+ f"timed out after {timeout:.2f}s waiting for PTY state",
546
+ eof=False,
547
+ attach_note=attach_note,
548
+ )
549
+ self._frame_event.clear()
550
+ if self.terminal.synchronized:
551
+ sync_rem = (
552
+ self.sync_timeout
553
+ if self._sync_started_at is None
554
+ else max(0.0, self._sync_started_at + self.sync_timeout - now)
555
+ )
556
+ wait_slice = min(remaining, sync_rem)
557
+ else:
558
+ wait_slice = remaining
559
+ with contextlib.suppress(TimeoutError):
560
+ await asyncio.wait_for(self._frame_event.wait(), timeout=wait_slice)
561
+
562
+ async def aclose(self) -> int:
563
+ """Signal the owned process group, drain PTY output, and close master fd."""
564
+ if self.process.returncode is None:
565
+ pid = self.process.pid
566
+ for sig, wait_s in (
567
+ (signal.SIGHUP, 0.4),
568
+ (signal.SIGTERM, 0.4),
569
+ ):
570
+ if self.process.returncode is not None:
571
+ break
572
+ with contextlib.suppress(ProcessLookupError, PermissionError):
573
+ os.killpg(pid, sig)
574
+ with contextlib.suppress(TimeoutError):
575
+ await asyncio.wait_for(self.process.wait(), timeout=wait_s)
576
+ if self.process.returncode is None:
577
+ with contextlib.suppress(ProcessLookupError, PermissionError):
578
+ os.killpg(pid, signal.SIGKILL)
579
+ with contextlib.suppress(ProcessLookupError):
580
+ self.process.kill()
581
+ await self.process.wait()
582
+
583
+ if not self._closed:
584
+ self._drain_nonblocking_master()
585
+ self._closed = True
586
+ if self._loop is not None:
587
+ with contextlib.suppress(Exception):
588
+ self._loop.remove_reader(self._master_fd)
589
+ with contextlib.suppress(OSError):
590
+ os.close(self._master_fd)
591
+
592
+ self.terminal.notify_process_exit()
593
+ return self.process.returncode or 0
594
+
595
+
596
+ @contextlib.asynccontextmanager
597
+ async def open_pty(
598
+ argv: collections.abc.Sequence[str],
599
+ *,
600
+ rows: int = 24,
601
+ cols: int = 80,
602
+ scrollback: int = 2_000,
603
+ env: collections.abc.Mapping[str, str] | None = None,
604
+ cwd: str | os.PathLike[str] | None = None,
605
+ tty_mode: TtyMode = "cooked",
606
+ python_executable: str | os.PathLike[str] | None = None,
607
+ profile: Profile = DEFAULT_PROFILE,
608
+ policy: Policy = DEFAULT_POLICY,
609
+ limits: Limits = DEFAULT_LIMITS,
610
+ sync_timeout: float = 1.0,
611
+ ) -> collections.abc.AsyncGenerator[PtySession]:
612
+ """Spawn *argv* with a controlling POSIX PTY driven by :class:`Terminal`.
613
+
614
+ Parameters
615
+ ----------
616
+ argv : collections.abc.Sequence[str]
617
+ Command and arguments executed via ``os.execvp``.
618
+ rows : int
619
+ Initial PTY height in rows.
620
+ cols : int
621
+ Initial PTY width in columns.
622
+ scrollback : int
623
+ Primary-screen scrollback line capacity.
624
+ env : collections.abc.Mapping[str, str] | None
625
+ Environment variables passed to the child process (defaults to
626
+ ``os.environ`` with ``TERM=xterm-256color``).
627
+ cwd : str | os.PathLike[str] | None
628
+ Working directory for the child process.
629
+ tty_mode : TtyMode
630
+ Initial slave terminal mode (``"cooked"``, ``"cbreak"``, or ``"raw"``).
631
+ python_executable : str | os.PathLike[str] | None
632
+ Python interpreter used for the ``TIOCSCTTY`` pre-exec trampoline.
633
+ profile : Profile
634
+ Terminal compatibility profile.
635
+ policy : Policy
636
+ Host security and query policy.
637
+ limits : Limits
638
+ Parser and state resource ceilings.
639
+ sync_timeout : float
640
+ Watchdog timeout in seconds before expiring stalled ``?2026`` frames.
641
+
642
+ Yields
643
+ ------
644
+ PtySession
645
+ Active session connected to the child process and master PTY fd.
646
+
647
+ Raises
648
+ ------
649
+ NotImplementedError
650
+ On platforms lacking POSIX ``pty.openpty()`` (Windows).
651
+ ValueError
652
+ If *argv* is empty or *tty_mode* is invalid.
653
+ OSError
654
+ If PTY allocation or ``execvp`` fails.
655
+ """
656
+ if sys.platform == "win32":
657
+ msg = "open_pty requires POSIX pty.openpty()"
658
+ raise NotImplementedError(msg)
659
+ if not argv:
660
+ msg = "argv must not be empty"
661
+ raise ValueError(msg)
662
+ if tty_mode not in ("cooked", "cbreak", "raw"):
663
+ msg = f"unsupported tty_mode: {tty_mode!r}"
664
+ raise ValueError(msg)
665
+
666
+ if python_executable is None:
667
+ if getattr(sys, "frozen", False) or not sys.executable:
668
+ msg = (
669
+ "open_pty requires python_executable in frozen or embedded "
670
+ "Python runtimes"
671
+ )
672
+ raise RuntimeError(msg)
673
+ py_bin = sys.executable
674
+ else:
675
+ py_bin = os.fspath(python_executable)
676
+
677
+ import fcntl
678
+ import pty
679
+ import termios
680
+ import tty
681
+
682
+ loop = asyncio.get_running_loop()
683
+ master_fd, slave_fd = pty.openpty()
684
+ err_r, err_w = os.pipe()
685
+ slave_closed = False
686
+ err_w_closed = False
687
+ proc: asyncio.subprocess.Process | None = None
688
+ try:
689
+ fcntl.ioctl(
690
+ slave_fd,
691
+ termios.TIOCSWINSZ,
692
+ struct.pack("HHHH", rows, cols, 0, 0),
693
+ )
694
+ if tty_mode == "cbreak":
695
+ tty.setcbreak(slave_fd)
696
+ elif tty_mode == "raw":
697
+ tty.setraw(slave_fd)
698
+ os.set_blocking(master_fd, False)
699
+ os.set_blocking(err_r, False)
700
+ child_env = dict(os.environ if env is None else env)
701
+ child_env.setdefault("TERM", "xterm-256color")
702
+ proc = await asyncio.create_subprocess_exec(
703
+ py_bin,
704
+ "-I",
705
+ "-S",
706
+ "-c",
707
+ _PTY_TRAMPOLINE,
708
+ str(err_w),
709
+ *argv,
710
+ stdin=slave_fd,
711
+ stdout=slave_fd,
712
+ stderr=slave_fd,
713
+ cwd=cwd,
714
+ env=child_env,
715
+ start_new_session=True,
716
+ pass_fds=(err_w,),
717
+ close_fds=True,
718
+ )
719
+ os.close(slave_fd)
720
+ slave_closed = True
721
+ os.close(err_w)
722
+ err_w_closed = True
723
+
724
+ err_payload = await _read_cloexec_pipe(loop, err_r)
725
+ if err_payload != b"\x00":
726
+ await proc.wait()
727
+ _raise_exec_error(err_payload, argv[0], errno.ENOEXEC)
728
+ except BaseException:
729
+ if proc is not None and proc.returncode is None:
730
+ with contextlib.suppress(ProcessLookupError, PermissionError):
731
+ os.killpg(proc.pid, signal.SIGKILL)
732
+ with contextlib.suppress(ProcessLookupError):
733
+ proc.kill()
734
+ await proc.wait()
735
+ with contextlib.suppress(OSError):
736
+ os.close(master_fd)
737
+ raise
738
+ finally:
739
+ if not slave_closed:
740
+ with contextlib.suppress(OSError):
741
+ os.close(slave_fd)
742
+ if not err_w_closed:
743
+ with contextlib.suppress(OSError):
744
+ os.close(err_w)
745
+ with contextlib.suppress(OSError):
746
+ os.close(err_r)
747
+
748
+ eff_policy = policy
749
+ if policy.osc7_hosts is None:
750
+ fqdn = socket.gethostname().lower()
751
+ short = fqdn.partition(".")[0]
752
+ eff_policy = dataclasses.replace(
753
+ policy,
754
+ osc7_hosts=DEFAULT_OSC7_HOSTS | frozenset({fqdn, short}),
755
+ )
756
+
757
+ recorder = FlightRecorder(max_bytes=limits.max_recorder_bytes)
758
+ terminal = Terminal(
759
+ rows=rows,
760
+ cols=cols,
761
+ scrollback=scrollback,
762
+ profile=profile,
763
+ policy=eff_policy,
764
+ limits=limits,
765
+ recorder=recorder,
766
+ )
767
+ session = PtySession(
768
+ master_fd=master_fd,
769
+ process=proc,
770
+ terminal=terminal,
771
+ sync_timeout=sync_timeout,
772
+ )
773
+ session._loop = loop
774
+ loop.add_reader(master_fd, session._on_readable)
775
+ try:
776
+ yield session
777
+ finally:
778
+ await session.aclose()
779
+
780
+
781
+ __all__ = [
782
+ "AsyncTerminalStream",
783
+ "PtySession",
784
+ "ReplyWriter",
785
+ "TtyMode",
786
+ "open_pty",
787
+ ]