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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871"""Programs start as background jobs, and the jobs helper owns them.
run(program, *args) starts one program without a shell. A job runs in its ownsession, so its program leads a process group and one signal reaches it plusevery descendant that stayed in that group. The jobs are owned by a helperprocess beside this kernel (albedo_jobs.py), not by this interpreter: itkeeps them, their output and their process groups through a kernel restart,swap or crash, and it is what ends them when the command ends, when itsdeadline passes, or when the session is deleted. This module is the kernel'send of it: the handle a cell holds, run(), and a connection to the helper.
A job that finishes with its result unread wakes the session: the helpertells whoever takes its notices, that submits a user turn naming the job, andthe model never has to poll or await. Reading the result (tail, poll, await,output.read) or stopping the job withdraws the wake; an await cut short by aninterrupt or a deadline read nothing, so it leaves the wake owed. A busysession is retried until it goes idle, so a notice can never overtake theread that satisfies it. Jobs still owed when the retry lands share onenotice, and so one turn."""
from __future__ import annotations
from albedo_output import JobOutput, plain, read_windowfrom albedo_jobs import NOTICE_RETRY, PROTOCOL, SOCKET, notice
from collections.abc import Awaitable, Callable, Coroutine, Generator, Iterator, Mappingfrom typing import Any, castfrom albedo_api import ( OUTPUT_PREVIEW, PythonApi, Text, check_timeout,)import albedo_captureimport albedo_direnvimport albedo_linkimport albedo_procimport albedo_shellfrom albedo_plugins import hookimport albedo_shimsimport albedo_traceimport asyncioimport base64import contextlibimport osimport reimport selectimport shleximport shutilimport socketimport subprocessimport tempfileimport threadingimport weakref
__all__ = ["NOTICE_RETRY", "notice"] # remote.py relays notices in this shape
loop: asyncio.AbstractEventLoophelper: Helperhandles: weakref.WeakValueDictionary[str, Job] = weakref.WeakValueDictionary()current_cell: Callable[[], str | None] | None = None
CALL_TIMEOUT = 10.0 # seconds a request to the helper may takeSPAWN_TIMEOUT = 10.0 # seconds a new helper has to listenData = str | bytes | os.PathLike[str]
class OutputLost(ValueError, LookupError): """Output the helper no longer holds: past what a job kept, or a job it displaced."""
class HelperGone(Exception): """The helper's end of a connection closed before it answered."""
def failure(reply: dict[str, object]) -> Exception: text = str(reply.get("error", "")) match reply.get("code"): case "missing": return LookupError(text) case "lost": return OutputLost(text) case "invalid": return ValueError(text) case "failed": return OSError(text) return RuntimeError(text)
def send_frame(connection: socket.socket, frame: dict[str, object]) -> None: albedo_link.write_frame(connection.send, albedo_link.encode(frame))
class Helper: """The kernel's connections to its jobs helper: one for requests, and one the helper pushes events down. A kernel launched by the daemon has a directory of its own to find it in and leaves wake notices to the daemon; a stdio kernel (a remote.connect target) makes one that ends with it and takes its notices itself."""
def __init__( self, directory: str | None, notify: Callable[[str, dict[str, object]], Awaitable[object]], send: Callable[[dict[str, object]], None], ) -> None: self.directory = directory self.stdio = directory is None self.notify = notify self.send = send self.lock = threading.RLock() self.requests: socket.socket | None = None self.events: socket.socket | None = None self.threads: set[threading.Thread] = set() self.owner: int | None = None # a stdio kernel's end of its helper's lifeline self.numbered = 0
def resources(self) -> tuple[set[threading.Thread], set[int]]: """What the connections hold, which is not the namespace's.""" sockets = [self.requests, self.events] return set(self.threads), {s.fileno() for s in sockets if s is not None}
def _dial(self, **attach: object) -> socket.socket: if self.directory is None: raise FileNotFoundError("no jobs helper yet") connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) connection.settimeout(CALL_TIMEOUT) try: path = os.path.join(self.directory, SOCKET) if len(os.fsencode(path)) < 100: connection.connect(path) else: # sun_path is short; a temporary home can use most of it previous = os.getcwd() os.chdir(self.directory) try: connection.connect(SOCKET) finally: os.chdir(previous) hello = cast( dict[str, dict[str, object]], albedo_link.read_frame(connection.recv) ) if hello["hello"]["protocol"] != PROTOCOL: raise RuntimeError( "the jobs helper speaks another protocol; albedo ends it and " "its jobs, and the next run() starts a new one" ) send_frame(connection, {"id": 0, "op": "attach", **attach}) self._answer(connection, 0) except BaseException: connection.close() raise return connection
def _answer(self, connection: socket.socket, number: int) -> dict[str, object]: while True: frame = cast(dict[str, object], albedo_link.read_frame(connection.recv)) if frame.get("re") == number: if frame.get("ok") is not True: raise failure(frame) return frame
def _spawn(self) -> None: if self.directory is None: self.directory = tempfile.mkdtemp(prefix="albedo-jobs-") os.makedirs(self.directory, mode=0o700, exist_ok=True) spill = albedo_capture.SPILL_DIR or os.path.join( tempfile.gettempdir(), "albedo-output" ) arguments = [ albedo_proc.named_python("jobs"), "-u", os.path.join( os.path.dirname(os.path.abspath(__file__)), "..", "albedo_jobs.py" ), self.directory, spill, ] keep: tuple[int, ...] = () if self.stdio: lifeline, self.owner = os.pipe() arguments.append(str(lifeline)) keep = (lifeline,) process = subprocess.Popen( arguments, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, cwd=self.directory, start_new_session=True, pass_fds=keep, ) for descriptor in keep: os.close(descriptor) assert process.stdout is not None ready = select_line(process.stdout, SPAWN_TIMEOUT) process.stdout.close() process.wait() # the helper forks away at once; this reaps the first if not ready: raise RuntimeError( f"the jobs helper did not start (see {self.directory}/jobs.log)" )
def open(self) -> None: """Connect, starting the helper first when there is none to reach.""" try: self.requests = self._dial() except (OSError, EOFError): self._spawn() self.requests = self._dial() self.events = self._dial(watch=True, sink=self.stdio) self.events.settimeout(None) thread = threading.Thread(target=self._pump, args=(self.events,), daemon=True) self.threads.add(thread) thread.start() if not self.stdio: loop.create_task(self._attached())
async def _attached(self) -> None: with contextlib.suppress(Exception): await self.notify("jobs.attached", {})
def close(self) -> None: for connection in (self.requests, self.events): if connection is not None: with contextlib.suppress(OSError): connection.close() self.requests = self.events = None
def call( self, operation: str, spawn: bool = True, **fields: object ) -> dict[str, object]: """One request, answered. A helper that left since the last one is started again; nothing else is retried.""" with self.lock: for attempt in (1, 2): try: if self.requests is None: if not spawn and not self.running(): raise HelperGone() self.open() assert self.requests is not None self.numbered += 1 send_frame( self.requests, {"id": self.numbered, "op": operation, **fields} ) return self._answer(self.requests, self.numbered) except (OSError, EOFError, HelperGone) as error: self.close() if attempt == 2 or not spawn or isinstance(error, TimeoutError): raise RuntimeError( f"the jobs helper is not answering: {error!r}" ) from error except BaseException: self.close() # an interrupt may have cut an exchange in two raise raise AssertionError("unreachable")
def running(self) -> bool: """Whether a helper answers, without starting one.""" try: self._dial().close() return True except (OSError, EOFError): return False
def once(self, operation: str, **fields: object) -> dict[str, object]: """One request on a connection of its own, for those that take a while.""" connection = self._dial() try: send_frame(connection, {"id": 1, "op": operation, **fields}) return self._answer(connection, 1) finally: connection.close()
def _pump(self, connection: socket.socket) -> None: connection.settimeout(None) try: while True: frame = albedo_link.read_frame(connection.recv) loop.call_soon_threadsafe(self._event, connection, frame) except (OSError, EOFError, ValueError, RuntimeError): pass finally: with contextlib.suppress(RuntimeError): loop.call_soon_threadsafe(self._lost, connection)
def _event(self, connection: socket.socket, frame: dict[str, object]) -> None: job = cast("dict[str, object] | None", frame.get("job")) event = frame.get("event") if self.stdio and job is not None and event in ("started", "ended"): # The kernel that holds this one over remote.connect lists and stops # its jobs by these two frames. shared = { "id": job["id"], "pid": job["pid"], "pgid": job["pgid"], "leader": job["leader"], "command": str(job["pipeline"])[:4096], "service": job["service"], } if event == "started": self.send({"type": "job_start", **shared}) else: self.send( { "type": "job", **shared, "exit_code": job["exit_code"], "timed_out": job["timed_out"], "cleanup": frame.get("cleanup"), } ) if event == "ended" and job is not None: handle = handles.get(str(job["id"])) if handle is not None: handle._ended(job) elif frame.get("op") == "wake": loop.create_task(self._wake(connection, frame))
async def _wake(self, connection: socket.socket, frame: dict[str, object]) -> None: reply: dict[str, object] try: await self.notify( "jobs.completed", cast(dict[str, object], frame["notice"]) ) reply = {"re": frame["id"], "ok": True} except Exception as error: code = getattr(error, "code", "unavailable") reply = {"re": frame["id"], "ok": False, "code": code, "error": str(error)} with contextlib.suppress(OSError): send_frame(connection, reply)
def _lost(self, connection: socket.socket) -> None: """The events connection ended. Jobs that never reported their end are asked after; a helper that is gone took them with it.""" with self.lock: if connection is not self.events: return self.events = None for handle in list(handles.values()): if not handle._finished.done(): handle._reconcile()
def select_line(stream: object, timeout: float) -> bool: """Whether the helper said `ready` before it closed its stdout.""" descriptor = cast(int, getattr(stream, "fileno")()) ready, _, _ = select.select([descriptor], [], [], timeout) return bool(ready) and os.read(descriptor, 16).startswith(b"ready")
class RemoteCapture: """A job's output as the helper holds it, shaped like a Capture so output.read and the job's own readers page through it unchanged."""
kind = "job"
def __init__(self, id: str) -> None: self.id = id
def _fact(self, name: str) -> Any: return cast(dict[str, Any], helper.call("facts", job=self.id)["job"])[name]
seen = property(lambda self: self._fact("seen")) retained = property(lambda self: self._fact("retained")) spill = property(lambda self: self._fact("spill"))
def tail(self, limit: int = OUTPUT_PREVIEW) -> bytes: data = base64.b64decode(cast(str, helper.call("tail", job=self.id)["data"])) return data[-limit:] if limit > 0 else b""
def read_bytes(self, offset: int, limit: int) -> bytes: reply = helper.call("bytes", job=self.id, offset=offset, size=limit) return base64.b64decode(cast(str, reply["data"]))
def read(self, offset: int = 0, limit: int = 4000) -> str: data = self.read_bytes(max(0, offset), min(max(0, limit), OUTPUT_PREVIEW)) return data.decode("utf-8", errors="ignore")
WAIT_POLL = 0.1 # seconds between looks at a job's output in wait_forFAILED_LINES = 30 # last lines a JobFailed quotes
def _shown(pattern: str | re.Pattern[str]) -> str: return repr(pattern.pattern if isinstance(pattern, re.Pattern) else pattern)
def _last(output: str) -> str: return "\n".join(output.rstrip("\n").split("\n")[-FAILED_LINES:])
class JobFailed(RuntimeError): """A job that exited nonzero or timed out when text() read it, or that ended before wait_for saw its pattern. `output` is what it printed."""
def __init__( self, job: Job, output: str, waiting: str | re.Pattern[str] | None = None ) -> None: self.job, self.exit_code, self.output = job, job.exit_code, output how = ( f"timed out after {job.duration or 0:.0f}s" if job.timed_out else f"exited {job.exit_code}" ) head = f"{job.pipeline} {how}" + ( f" without printing {_shown(waiting)}" if waiting is not None else "" ) last = _last(output) super().__init__(f"{head}. Its last lines:\n{last}" if last.strip() else head)
class PendingText: """`job.text()` before it is awaited. `await` binds to everything after it, so `await job.text()[-2000:]` slices this object, not the text; each slice is kept and applied once the text arrives."""
__slots__ = ("_read", "_keys")
def __init__( self, read: Callable[[], Coroutine[object, object, Text]], keys: tuple[int | slice, ...] = (), ) -> None: self._read = read self._keys = keys
def __getitem__(self, key: int | slice) -> PendingText: return PendingText(self._read, (*self._keys, key))
def __await__(self) -> Generator[object, None, Text]: return self._text().__await__()
async def _text(self) -> Text: text = await self._read() for key in self._keys: text = Text(text[key]) return text
def __repr__(self) -> str: return "<job output not read yet: await job.text()>"
class Job(JobOutput): """One background program, as the helper reports it. The helper owns the process, its group and its output; this holds the facts last heard and asks for the rest."""
def __init__(self, facts: dict[str, object], *, begun: bool = False) -> None: self.id = str(facts["id"]) self.capture = cast(Any, RemoteCapture(self.id)) self._facts: dict[str, Any] = facts self._hooked: hook.Call | None = None # set by run() self._done = albedo_trace.note("run", self.command) if begun else None self._marked = False self._finished: asyncio.Future[None] = loop.create_future() handles[self.id] = self if watch_output is not None: watch_output(self.id, self._mark_read) if facts["done"]: self._finished.set_result(None)
command = property(lambda self: cast(str, self._facts["command"])) service = property(lambda self: cast(bool, self._facts["service"])) timeout = property(lambda self: cast(float, self._facts["timeout"])) pipeline = property(lambda self: cast(str, self._facts["pipeline"]))
def _fact(self, name: str) -> Any: """A fact that changes until the job is done: asked for again until then.""" if not self._facts["done"]: with contextlib.suppress(Exception): self._facts = cast( dict[str, Any], helper.call("facts", job=self.id)["job"] ) return self._facts[name]
@property def exit_code(self) -> int | None: return self._fact("exit_code")
@property def timed_out(self) -> bool: return self._fact("timed_out")
@property def duration(self) -> float | None: return self._fact("duration")
@property def _read(self) -> bool: return self._marked
@_read.setter def _read(self, value: bool) -> None: """The result was read: the helper owes no wake for it.""" if value and not self._marked: self._marked = True with contextlib.suppress(Exception): helper.call("mark_read", job=self.id)
def _mark_read(self) -> None: """output.read reached this job's channel; a finished result is read.""" if self.exit_code is not None: self._read = True
def _ended(self, facts: dict[str, Any]) -> None: self._facts = facts loop.create_task(self._close_out())
async def _close_out(self) -> None: """What the kernel does when its job ends, before anyone awaiting it goes on.""" if self._done is not None: self._done(ok=self.exit_code == 0 and not self.timed_out) if self._hooked is not None: text = await hook.job_ended(self._hooked, self.exit_code, self.timed_out) if text: with contextlib.suppress(Exception): helper.call("append", job=self.id, text=text) if not self._finished.done(): self._finished.set_result(None)
def _reconcile(self) -> None: """The helper's connection ended without this job's end: ask whether it went on, and treat one the helper no longer knows as ended.""" facts: dict[str, Any] try: facts = cast( dict[str, Any], helper.call("facts", spawn=False, job=self.id)["job"] ) except Exception: facts = {**self._facts, "done": True, "exit_code": None} if facts["done"]: self._ended(facts)
def pipe( self, program: object, *args: object, cwd: str | os.PathLike[str] | None = None, env: dict[str, object] | None = None, timeout: float | None = None, ) -> Job: """Start a program reading this job's output, like a shell `|`: run("git", "log").pipe("rg", "fix"). Returns the reader's handle, which keeps this job's timeout unless given its own.""" timeout = self.timeout if timeout is None else timeout return run(program, *args, cwd=cwd, env=env, stdin=self, timeout=timeout)
def __await__(self) -> Generator[object, None, Job]: return self._wait().__await__()
async def _wait(self) -> Job: """Wait for the job. An await cut short (an interrupted cell, a wait_for deadline) never delivered the result and did not stop the job, so the cell says so, and the job still wakes the session when it ends.""" helper.call("wait_begin", job=self.id) delivered = False try: await asyncio.shield(self._finished) delivered = True except (KeyboardInterrupt, asyncio.CancelledError): if not self._finished.done(): print( f"\n[job {self.id} is still running: {self.command}. " "the interrupted await did not stop it, and it wakes the session " f"when it ends; jobs[{self.id!r}] reaches it, " f"await jobs[{self.id!r}].stop() ends it]" ) raise finally: with contextlib.suppress(Exception): helper.call("wait_end", job=self.id, delivered=delivered) return self
def poll(self): if self.exit_code is not None: self._read = True return self.exit_code
def text(self, check: bool = True) -> PendingText: """Wait for the job and return its whole output as plain text: escape codes dropped, a redrawn line at its last draw. A job that exits nonzero or times out raises JobFailed with its last lines, unless check=False. A slice taken before the await applies to the text, so `await job.text()[-2000:]` is its last 2000 characters.""" return PendingText(lambda: self._text(check))
async def _text(self, check: bool) -> Text: await self output = plain(self.read()) if check and (self.exit_code != 0 or self.timed_out): raise JobFailed(self, output) return Text(output)
async def wait_for( self, pattern: str | re.Pattern[str], timeout: float = 60 ) -> Text: """Wait until a line of output contains `pattern` (text, or a compiled regex) and return that line; output already written counts. Raises TimeoutError after `timeout` seconds, and JobFailed when the job ends without it. Neither stops the job.""" check_timeout(timeout)
def matches(line: str) -> bool: if isinstance(pattern, re.Pattern): return pattern.search(line) is not None return str(pattern) in line
deadline = loop.time() + timeout scanned, carry = 0, "" while True: finished = self._finished.done() try: _, scanned, chunk = read_window( self.capture, scanned, OUTPUT_PREVIEW, finished ) except LookupError: # Past retention: carry on from what is still kept. scanned, carry = self.capture.seen - len(self.capture.tail()), "" continue *lines, carry = (carry + chunk).split("\n") # The line still being written counts too: a prompt has no newline. for line in (*lines, carry): shown = plain(line) if matches(shown): return Text(shown) if scanned < self.capture.seen: continue if finished: raise JobFailed(self, self._plain_tail(), waiting=pattern) if loop.time() >= deadline: raise TimeoutError( f"{self.pipeline} printed no {_shown(pattern)} in {timeout:g}s; " f"it is still running. Its last lines:\n{_last(self._plain_tail())}" ) await asyncio.sleep(WAIT_POLL)
def _plain_tail(self) -> str: return plain(self.capture.tail().decode("utf-8", errors="replace"))
def _plain_tail(self) -> str: return plain(self.capture.tail().decode("utf-8", errors="replace"))
@property def returncode(self) -> int | None: """`exit_code` under subprocess's name; both spellings answer.""" return self.poll()
async def stop(self) -> albedo_proc.Termination: """End the job's process group. A failed attempt stays retryable.""" if self._facts["done"]: return albedo_proc.Termination(None, (), True) reply = await loop.run_in_executor( None, lambda: helper.once("stop", job=self.id) ) ending = cast(dict[str, Any], reply["termination"]) if ending["gone"] and not self._finished.done(): with contextlib.suppress(Exception, asyncio.CancelledError): await asyncio.shield(self._finished) return albedo_proc.Termination( ending["pgid"], tuple(ending["signals"]), ending["gone"], tuple(ending["failures"]), ending["note"], )
def __repr__(self) -> str: return ( f"Job(id={self.id!r}, exit_code={self.exit_code!r}, " f"timed_out={self.timed_out!r}, duration={self.duration!r}, " f"bytes={self.capture.seen})" )
def __reduce__(self): # Saved kernel state keeps a variable holding a job: a later kernel # asks the helper for it again. return _revive, (self.id,)
def _revive(id: str) -> Job: return Jobs()[id]
class Jobs(Mapping[str, Job]): """Every job the helper still keeps, newest first; `jobs[id]` is its handle."""
def __getitem__(self, id: str) -> Job: try: facts = helper.call("facts", job=id)["job"] except LookupError: raise KeyError(id) from None handle = handles.get(id) return handle if handle is not None else Job(cast(dict[str, object], facts))
def __iter__(self) -> Iterator[str]: return iter([str(job["id"]) for job in listed()])
def __len__(self) -> int: return len(listed())
def copy(self) -> dict[str, Job]: return dict(self.items())
def __repr__(self) -> str: return f"<jobs: {len(self)} kept>"
def listed(spawn: bool = True) -> list[dict[str, object]]: """The helper's jobs, newest first; with `spawn` off, none when it is not running.""" try: return cast("list[dict[str, object]]", helper.call("list", spawn=spawn)["jobs"]) except RuntimeError: if spawn: raise return []
def run( program: object, *args: object, cwd: str | os.PathLike[str] | None = None, env: dict[str, object] | None = None, stdin: Data | Job | None = None, timeout: float = 300, service: bool = False,) -> Job: """Start one program, without a shell, and return its handle immediately: run("go", "test", "./...", cwd="cli"). It starts at once, at low priority. The timeout, in seconds and at most a day, counts wall time after the program starts.
`env` adds to the kernel's environment. `stdin` is text or bytes to feed the program, a path to read, or another job, whose output streams in like a shell pipe (job.pipe(...) says the same). stderr joins stdout.
Output stays on the handle: job.tail(lines=20) and job.head(lines=20) for its ends, output.read(job.id) for the retained whole. Jobs survive cell completion, the kernel itself, and each owns its process group. Only unfinished work counts against the concurrent quota; the 64 newest finished jobs stay usable in `jobs`, and an older one is gone.
A job that finishes with its result unread wakes the session by itself, so polling or trailing a handle is optional: leave it in a variable, end the cell, and the wake names the job when it lands. Awaiting the job, reading its result, or stopping it first means no wake.
`nix` never copies a jj workspace into the store (a flake there is read from its commit), and `nix develop -c program ...` reuses a cached dev shell. `cargo` runs through mbx when it is installed, so every checkout shares compiled work; env={"ALBEDO_NO_MBX": "1"} runs plain cargo.
Pass service=True for a program that is meant to keep running (a dev server, a file watcher): you are not waiting for it to finish, so it does not keep your prompt cache warm while you are idle. """ check_timeout(timeout) if not (stdin is None or isinstance(stdin, (str, bytes, os.PathLike, Job))): raise TypeError( f"stdin is text, bytes, a path, or a job on this kernel, not {type(stdin).__name__}" ) argv = albedo_shell.words((program, *args)) script = albedo_shell.shell_script(argv) if script is not None: raise albedo_shell.refusal(f"`{os.path.basename(argv[0])} -c`", script=script) albedo_direnv.refresh() environment = albedo_shims.prepend( None if env is None else {**os.environ, **{str(k): str(v) for k, v in env.items()}} ) directory = os.path.abspath(os.getcwd() if cwd is None else os.fsdecode(cwd)) if os.sep not in argv[0]: found = shutil.which(argv[0], path=(environment or os.environ).get("PATH")) if found is None: if any(char.isspace() for char in argv[0]): raise albedo_shell.refusal( "a whole command line as the program", script=argv[0] ) raise FileNotFoundError(f"{argv[0]}: no such program on PATH") line = shlex.join(argv) hooked = hook.before("run", {"command": line}) command = hooked.arguments.get("command") if isinstance(command, str) and command != line: argv = shlex.split(command) reply = helper.call( "start", argv=argv, timeout=timeout, cwd=directory, env=dict(os.environ) if environment is None else environment, stdin=feed(stdin), service=service, cell=current_cell() if current_cell else None, ) job = Job(cast(dict[str, object], reply["job"]), begun=True) job._hooked = hooked return job
def feed(stdin: Data | Job | None) -> dict[str, str] | None: """What the helper is told to feed the program: text and bytes travel, a path is opened on the helper's side, a job streams from the helper.""" if stdin is None: return None if isinstance(stdin, Job): return {"job": stdin.id} if isinstance(stdin, str): return {"text": stdin} if isinstance(stdin, bytes): return {"bytes": base64.b64encode(stdin).decode()} return {"path": os.path.abspath(os.fsdecode(stdin))}
def cell_jobs(cell: str) -> list[tuple[str, str]]: """The jobs `cell` started that still run, services aside: they are meant to.""" return [ (str(job["id"]), str(job["pipeline"])) for job in listed(spawn=False) if job["cell"] == cell and not job["done"] and not job["service"] ]
watch_output: Callable[[str, Callable[[], None]], None] | None = None
def setup(api: PythonApi) -> dict[str, object]: global loop, helper, current_cell, watch_output loop, current_cell, watch_output = api.loop, api.cell, api.watch_output helper = Helper(os.environ.get("ALBEDO_JOBS_DIR"), api.host, api.send)
def output(id: str) -> object | None: try: helper.call("facts", spawn=False, job=id) except (LookupError, RuntimeError): return None return RemoteCapture(id)
async def stop_local(id: str) -> dict[str, object] | None: """A remote.connect parent stopping a job of this kernel by its id.""" try: await Jobs()[id].stop() except KeyError: return None return {"ok": True}
api.background_handle(Job) if api.on_stop_job is not None: api.on_stop_job(stop_local) if api.on_output is not None: api.on_output( output, lambda: [ { "id": job["id"], "kind": "job", "bytes": job["seen"], "retained": job["retained"], } for job in listed(spawn=False) ], ) if api.internal_resources is not None: api.internal_resources(helper.resources) if api.on_cell_jobs is not None: api.on_cell_jobs(cell_jobs) api.on_shutdown(helper.close) return {"run": run, "jobs": Jobs()}