Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188"""Own helper commands until their groups are stopped and their leaders reaped.
The control byte after the request, or stdin EOF, cancels the helper. Commandcreation and cancellation share a lock. Leaders remain unreaped until groupcleanup so their process group IDs cannot be reused while we signal them."""
from __future__ import annotations
import ctypesimport errnoimport osimport signalimport structimport subprocessimport sysimport threadingimport timefrom typing import IO
import albedo_proc
_DARWIN_P_PID = 1_DARWIN_WNOHANG = 0x1_DARWIN_WEXITED = 0x4_DARWIN_WNOWAIT = 0x20_DARWIN_SIGINFO_BYTES = 104_DARWIN_SI_PID_OFFSET = 12
def _darwin_libc() -> ctypes.CDLL | None: if sys.platform != "darwin": return None libc = ctypes.CDLL(None, use_errno=True) libc.waitid.argtypes = [ctypes.c_int, ctypes.c_uint, ctypes.c_void_p, ctypes.c_int] libc.waitid.restype = ctypes.c_int return libc
_DARWIN_LIBC = _darwin_libc()
def _exited_unreaped(pid: int) -> bool: waitid = getattr(os, "waitid", None) if waitid is not None: try: return ( waitid( getattr(os, "P_PID"), pid, getattr(os, "WEXITED") | getattr(os, "WNOWAIT") | getattr(os, "WNOHANG"), ) is not None ) except ChildProcessError: return True if _DARWIN_LIBC is None: raise RuntimeError("os.waitid is unavailable on this platform") info = ctypes.create_string_buffer(_DARWIN_SIGINFO_BYTES) ctypes.set_errno(0) if ( _DARWIN_LIBC.waitid( _DARWIN_P_PID, pid, info, _DARWIN_WEXITED | _DARWIN_WNOWAIT | _DARWIN_WNOHANG, ) == -1 ): err = ctypes.get_errno() if err == errno.ECHILD: return True if err == errno.EINTR: return False raise OSError(err, os.strerror(err)) return struct.unpack_from("=i", info.raw, _DARWIN_SI_PID_OFFSET)[0] == pid
def read_request() -> bytes: """Read exactly one line without buffering the subsequent control byte.""" data = bytearray() while byte := os.read(sys.stdin.fileno(), 1): if byte == b"\n": break data.extend(byte) return bytes(data)
class Commands: def __init__(self) -> None: self._lock = threading.Lock() self._processes: set[subprocess.Popen[bytes]] = set() self._cancelled = False threading.Thread(target=self._watch, daemon=True).start()
def _watch(self) -> None: os.read(sys.stdin.fileno(), 1) try: self.close() except OSError as error: print(f"helper cleanup failed: {error}", flush=True) os._exit(125) os._exit(124)
def start( self, command: str, *, cwd: str | None, stdin: IO[bytes], stdout: IO[bytes], stderr: IO[bytes] | int, ) -> subprocess.Popen[bytes]: with self._lock: if self._cancelled: raise RuntimeError("helper cancelled") process = subprocess.Popen( command, shell=True, cwd=cwd, stdin=stdin, stdout=stdout, stderr=stderr, start_new_session=True, ) self._processes.add(process) return process
def wait(self, process: subprocess.Popen[bytes], timeout: float) -> None: deadline = time.monotonic() + timeout while True: # WNOWAIT pins the leader even after it exits, including while # descendants remain in its group. Popen.wait would reap it. if _exited_unreaped(process.pid): return if time.monotonic() >= deadline: raise subprocess.TimeoutExpired(process.args, timeout) time.sleep(0.01)
def finish(self, process: subprocess.Popen[bytes]) -> None: with self._lock: if process not in self._processes: return stop(process.pid) self._settle(process) self._processes.remove(process)
def close(self) -> None: with self._lock: self._cancelled = True for process in self._processes: stop(process.pid) for process in self._processes: self._settle(process) self._processes.clear()
@staticmethod def _settle(process: subprocess.Popen[bytes]) -> None: await_stopped(process.pid) process.wait(timeout=2)
def stop(group: int) -> None: """Kill a command's group. A group that is already gone needs nothing.""" try: os.killpg(group, signal.SIGKILL) except ProcessLookupError: pass except PermissionError: # Darwin returns EPERM when only the un-reaped zombie leader remains. if sys.platform != "darwin" or albedo_proc.live_members(group) != []: raise
def await_stopped(group: int) -> None: """Wait until a killed group has no live member.
Where the process table cannot be read there is nothing to wait on, and the kill already sent is all this can do. """ deadline = time.monotonic() + 2 while albedo_proc.live_members(group): if time.monotonic() >= deadline: raise OSError(f"command group {group} did not stop") time.sleep(0.01)