From d4842e69a774abde296ec925f9b984810c2e4b57 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Mon, 5 Oct 2026 05:40:09 -0400 Subject: [PATCH] make python kernel friendlier based on traces --- priv/python/albedo_api.py | 17 ++++- priv/python/albedo_kernel.py | 41 +++++++++++- priv/python/albedo_plugins/agents.py | 16 ++++- priv/python/albedo_plugins/files.py | 14 +++- priv/python/albedo_plugins/remote.py | 18 +++-- priv/python/albedo_plugins/run.py | 17 +++-- priv/python/albedo_shell.py | 27 +++++++- robot-docs/agents.md | 4 +- robot-docs/files.md | 2 +- robot-docs/kernel.md | 4 ++ robot-docs/provider-requests.md | 2 +- .../harness/extensions/agents/extension.gleam | 66 +++++++++++++++++-- .../harness/extensions/python/cells.gleam | 24 +++++++ .../harness/extensions/python/extension.gleam | 4 +- .../harness/extensions/run/extension.gleam | 2 +- src/albedo/harness/loop.gleam | 6 +- src/albedo/openai_api.gleam | 2 +- test/e2e/agents_test.py | 37 +++++++++++ test/e2e/cell_background_test.py | 2 +- test/e2e/kernel_detach_test.py | 2 +- test/e2e/lifecycle_test.py | 4 +- test/e2e/python_test.py | 36 ++++++++++ test/e2e/remote_kernels_test.py | 2 +- test/harness/cell_repair_test.gleam | 11 ++++ 24 files changed, 312 insertions(+), 48 deletions(-) diff --git a/priv/python/albedo_api.py b/priv/python/albedo_api.py index 3c796b56c..b1bbf3392 100644 --- a/priv/python/albedo_api.py +++ b/priv/python/albedo_api.py @@ -83,14 +83,25 @@ class Record(dict): return _ready(self) -def excerpt(text: str, chars: int, lines: int | None, *, end: bool) -> str: +def check_timeout(timeout: float) -> None: + """Raise unless a job timeout is within 0 < timeout <= 3600 seconds.""" + if not 0 < timeout <= 3600: + raise ValueError( + f"timeout is in seconds: 0 < timeout <= 3600 required, got {timeout:g}" + + (" (milliseconds?)" if timeout > 3600 else "") + ) + + +def excerpt(text: str, chars: int, lines: int | None, *, end: bool) -> Text: """Output's first or last `lines` lines, else its first or last `chars` characters: what a job handle's head() and tail() answer.""" if lines is not None: kept = text.splitlines(keepends=True) - return "".join(kept[-lines:] if end else kept[:lines]) if lines > 0 else "" + return Text( + "".join(kept[-lines:] if end else kept[:lines]) if lines > 0 else "" + ) chars = max(1, chars) - return text[-chars:] if end else text[:chars] + return Text(text[-chars:] if end else text[:chars]) class OutputCapture(Protocol): diff --git a/priv/python/albedo_kernel.py b/priv/python/albedo_kernel.py index 059579011..4b4b59923 100644 --- a/priv/python/albedo_kernel.py +++ b/priv/python/albedo_kernel.py @@ -12,7 +12,7 @@ import albedo_proc import albedo_shell from collections.abc import Awaitable, Callable, Iterable, Sequence from typing import cast -from types import CodeType, FrameType +from types import CodeType, FrameType, ModuleType import albedo_trace import asyncio import builtins @@ -21,9 +21,11 @@ import collections import contextvars import dataclasses import inspect +import importlib import io import json import os +import pathlib import reprlib import select import shutil @@ -396,7 +398,7 @@ def watch_output(id: str, notify: Callable[[], None]) -> None: class Output: - def read(self, id: str, *, offset: int = 0, limit: int = 4000) -> str: + def read(self, id: str, offset: int = 0, limit: int = 4000) -> albedo_api.Text: """Read retained output by cell or job id: up to 1 MiB each, for the 16 most recent cells and 64 most recent jobs.""" capture = retained(id) @@ -1422,6 +1424,37 @@ def open_link(argv: list[str]) -> list[str]: return cast(list[str], json.loads(argv[3])) +PRELOADED = ( + "asyncio base64 collections datetime functools hashlib itertools json math os re shutil sys textwrap time" +).split() + + +def session_builtins(bindings: dict[str, object]) -> dict[str, object]: + """Python's builtins plus the common standard-library modules and the + injected bindings. Cells may shadow any of them and `del` reveals it again; + a binding wins over a module of the same name.""" + modules = {name: importlib.import_module(name) for name in PRELOADED} + return vars(builtins) | modules | {"Path": pathlib.Path} | bindings + + +class Bindings(ModuleType): + """`import albedo` and `from albedo import files` answer the injected + bindings, for code written as if they were a library.""" + + def __init__(self, bindings: dict[str, object]) -> None: + super().__init__("albedo", "The tool bindings every cell already has.") + self.bindings = bindings + + def __getattr__(self, name: str) -> object: + try: + return self.bindings[name] + except KeyError: + raise AttributeError(f"albedo has no binding {name!r}") from None + + def __dir__(self) -> list[str]: + return sorted(self.bindings) + + def main(): global NATIVE_FD if os.getpgrp() != os.getpid(): @@ -1473,9 +1506,11 @@ def main(): # Plugin bindings and session objects are rebuilt on every start, never saved. INJECTED.update(NAMESPACE) # Cell globals may shadow tools; deletion reveals the original session binding. - NAMESPACE["__builtins__"] = vars(builtins) | { + bindings = { name: value for name, value in NAMESPACE.items() if not name.startswith("_") } + NAMESPACE["__builtins__"] = session_builtins(bindings) + sys.modules["albedo"] = Bindings(bindings) # Declare our own process group; a group we do not lead is never the supervisor's target. pgid = os.getpgid(0) send( diff --git a/priv/python/albedo_plugins/agents.py b/priv/python/albedo_plugins/agents.py index 12c062e76..10e50ab30 100644 --- a/priv/python/albedo_plugins/agents.py +++ b/priv/python/albedo_plugins/agents.py @@ -106,9 +106,12 @@ class Agent: ) return [_agent(item) for item in cast(list, await host("agents.siblings", {}))] - async def cancel(self) -> bool: - """Stop this child's running turn. It keeps its session and work.""" - return bool(await host("agents.cancel", {"id": self.id})) + async def cancel(self, *, tree: bool = False) -> bool: + """Stop this child's running turn; it keeps its session and work. With + `tree=True` its own children, and theirs, are stopped too. True when a + turn was running.""" + stopped = await host("agents.cancel", {"id": self.id, "tree": tree}) + return bool(cast(list, stopped)) async def close(self) -> bool: """Done with this child: stop it, keep its messages and files, free its kernel.""" @@ -206,6 +209,13 @@ class Agents: _models_seen = True return list(cast(list, await host("agents.models", {}))) + async def cancel_all(self, *, tree: bool = True) -> list[str]: + """Stop the running turn of every one of your children, and with + `tree=True` (the default) everything beneath them. Returns the ids of the + sessions that were running. They keep their sessions and work.""" + stopped = await host("agents.cancel_all", {"tree": tree}) + return list(cast(list, stopped)) + async def progress(self, text: str) -> bool: """A short status (≤512 chars) the agents view shows without starting a turn. At most one per 10 seconds; returns False when throttled.""" diff --git a/priv/python/albedo_plugins/files.py b/priv/python/albedo_plugins/files.py index 5efca77f5..19b717328 100644 --- a/priv/python/albedo_plugins/files.py +++ b/priv/python/albedo_plugins/files.py @@ -548,7 +548,14 @@ class Files: if not found: closest = _closest(content, old_str) raise ValueError( - f"string not found in {path}" + (f"\n{closest}" if closest else "") + f"string not found in {path}" + + ( + "; the text is there, but whitespace differs (indentation, " + "tabs, trailing spaces or line endings)" + if _words(old_str) in _words(content) and _words(old_str) + else "" + ) + + (f"\n{closest}" if closest else "") ) chosen = _choose(content, old_str, found, line_hint, path) replacement = ( @@ -868,6 +875,11 @@ def _candidates(content: str, found: list[_Occurrence]) -> str: return "\n\n".join(blocks) +def _words(text: str) -> str: + """text with every run of whitespace as one space, to see a whitespace-only miss.""" + return " ".join(text.split()) + + def _closest(content: str, needle: str) -> str: lines, needle_lines = content.splitlines(), needle.splitlines() head = next((line.strip() for line in needle_lines if line.strip()), "") diff --git a/priv/python/albedo_plugins/remote.py b/priv/python/albedo_plugins/remote.py index 1004f7d17..001e81849 100644 --- a/priv/python/albedo_plugins/remote.py +++ b/priv/python/albedo_plugins/remote.py @@ -28,7 +28,7 @@ from typing import Any from albedo_protocol import RemoteCall, RemoteMessage, parse_remote -from albedo_api import PythonApi, ReadyList, excerpt +from albedo_api import PythonApi, ReadyList, Text, check_timeout, excerpt import albedo_bundle from albedo_values import InvalidValue, decode import albedo_shell @@ -272,7 +272,7 @@ class RemoteRef: # --- mirrored job state: sync, like the local handle --- - def tail(self, n: int = 4000, *, lines: int | None = None) -> str: + def tail(self, n: int = 4000, *, lines: int | None = None) -> Text: """The recent output of the remote job this reference holds: the last n characters, or its last `lines` lines.""" state = self._mirror() @@ -861,8 +861,7 @@ class RemoteConnection: stdin: str | bytes | None = None, timeout: float = 300, ) -> FallbackJob: - if not 0 < timeout <= 3600: - raise ValueError("0 < timeout <= 3600 required") + check_timeout(timeout) if not (stdin is None or isinstance(stdin, (str, bytes))): raise TypeError("in ssh command mode stdin is text or bytes") argv = albedo_shell.words((program, *args)) @@ -891,10 +890,9 @@ class RemoteConnection: stdin: str | bytes | None = None, timeout: float = 300, ) -> FallbackJob: - if not isinstance(script, str) or not 0 < timeout <= 3600: - raise ValueError( - "shell script must be text; 0 < timeout <= 3600 required" - ) + if not isinstance(script, str): + raise ValueError("shell script must be text") + check_timeout(timeout) if not (stdin is None or isinstance(stdin, (str, bytes))): raise TypeError("in ssh command mode stdin is text or bytes") return FallbackJob( @@ -1170,7 +1168,7 @@ class FallbackJob: """`exit_code` under subprocess's name; both spellings answer.""" return self.poll() - def tail(self, n: int = 4000, *, lines: int | None = None) -> str: + def tail(self, n: int = 4000, *, lines: int | None = None) -> Text: if self.exit_code is not None: self._read = True return excerpt( @@ -1180,7 +1178,7 @@ class FallbackJob: end=True, ) - def head(self, n: int = 4000, *, lines: int | None = None) -> str: + def head(self, n: int = 4000, *, lines: int | None = None) -> Text: if self.exit_code is not None: self._read = True return excerpt(self.capture.read(0, 65536), min(n, 65536), lines, end=False) diff --git a/priv/python/albedo_plugins/run.py b/priv/python/albedo_plugins/run.py index 5ab94edb5..16415715e 100644 --- a/priv/python/albedo_plugins/run.py +++ b/priv/python/albedo_plugins/run.py @@ -22,7 +22,15 @@ from __future__ import annotations from collections import OrderedDict from collections.abc import Callable, Generator from typing import cast -from albedo_api import Host, PythonApi, OutputCapture, Send, excerpt +from albedo_api import ( + Host, + PythonApi, + OutputCapture, + Send, + Text, + check_timeout, + excerpt, +) import albedo_proc import albedo_shell import albedo_trace @@ -439,14 +447,14 @@ class Job: """`exit_code` under subprocess's name; both spellings answer.""" return self.poll() - def tail(self, n: int = 4000, *, lines: int | None = None) -> str: + def tail(self, n: int = 4000, *, lines: int | None = None) -> Text: """The last n characters of output, or its last `lines` lines.""" if self.exit_code is not None: self._read = True text = self.capture.tail().decode("utf-8", errors="replace") return excerpt(text, min(n, preview_limit), lines, end=True) - def head(self, n: int = 4000, *, lines: int | None = None) -> str: + def head(self, n: int = 4000, *, lines: int | None = None) -> Text: """The first n characters of output, or its first `lines` lines.""" if self.exit_code is not None: self._read = True @@ -683,8 +691,7 @@ def run( 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. """ - if not 0 < timeout <= 3600: - raise ValueError("0 < timeout <= 3600 required") + 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__}" diff --git a/priv/python/albedo_shell.py b/priv/python/albedo_shell.py index a8752427e..2e90f2451 100644 --- a/priv/python/albedo_shell.py +++ b/priv/python/albedo_shell.py @@ -3,7 +3,8 @@ Cells start programs with run(program, *args): no shell, supervised, traced. A shell line or a raw process API from a cell is refused with the run() call it means when the line is simple enough to read, so the refusal teaches by -example. This is guidance, not a sandbox: libraries and plugins still spawn. +example. A time.sleep of a second or more is refused too: it blocks the whole +kernel, and the refusal says to run the work async or to wait on purpose. This is guidance, not a sandbox: libraries and plugins still spawn. """ from __future__ import annotations @@ -17,6 +18,7 @@ import sysconfig SHELLS = {"sh", "bash", "zsh", "dash", "ksh", "fish", "nu"} CELL_PREFIX = " list[str]: return [] +def sleep_refusal(seconds: float) -> Refused: + """Why a cell may not block the kernel with time.sleep.""" + return Refused( + f"time.sleep({seconds:g}) is refused here: it blocks the whole kernel, so nothing " + "else in this session runs while it waits. Start the work with run() and do other " + "useful work while it runs; its completion wakes you. If there is nothing else to " + "do, give the user a status report first, then wait with " + f"`await asyncio.sleep({seconds:g})`." + ) + + def guard(event: str, args: tuple[object, ...]) -> None: - """Audit hook: a cell that spawns through subprocess or os gets run() instead.""" + """Audit hook: a cell that spawns through subprocess or os gets run() instead, + and one that sleeps the kernel is told to run async work or wait explicitly.""" + if event == "time.sleep": + seconds = args[0] + if ( + isinstance(seconds, (int, float)) + and seconds >= BLOCKING_SLEEP + and _from_cell(skip=2) + ): + raise sleep_refusal(seconds) + return if event not in SPAWN_EVENTS or not _from_cell(skip=2): return if event == "os.system": diff --git a/robot-docs/agents.md b/robot-docs/agents.md index 0e72e11be..e255fc8aa 100644 --- a/robot-docs/agents.md +++ b/robot-docs/agents.md @@ -11,6 +11,8 @@ kid = await agents.self.spawn("map every wake path", name="scout", model=m[0], await mail.submit(kid, "also cover schedules") # or "parent", a name, a session id kids = await agents.self.children() # snapshots: running, closed await kid.cancel() # stop its turn, keep everything +await kid.cancel(tree=True) # ...and the turns of everything beneath it +await agents.cancel_all() # every child and descendant (tree=True by default) await kid.close() # done: keep messages + files, free the kernel other = await agents.get("a1b2c3") # "parent", a family name, or any session id page = await other.messages(seq=0) # page of its rows: content, next_offset @@ -20,7 +22,7 @@ await agents.progress("on turn.gleam now") # shows in /agents, starts no turn - spawn never returns the child's answer: the answer arrives later as `` and starts the parent's next turn. a child whose turn ends without answering forwards its last message, marked `unreviewed`. - names resolve inside the family (children, siblings, parent); anything else takes a session id. -- any session may look up and read any other: `get`, `messages`, and `search_messages` resolve names and ids the way mail does, and closed agents stay readable. cancel and close work on your own children only. the model cannot delete an agent; it asks the user. +- any session may look up and read any other: `get`, `messages`, and `search_messages` resolve names and ids the way mail does, and closed agents stay readable. cancel and close work on your own children only. `cancel(tree=True)` and `cancel_all()` stop parents before their children, so a stopped agent cannot answer by spawning, and answer the sessions that were running; they never close or delete anything. the model cannot delete an agent; it asks the user. - limits: 3 deep, 12 open children per parent, 1 MiB per letter, 1000 undelivered letters per session. ## mail delivery diff --git a/robot-docs/files.md b/robot-docs/files.md index 0ed5599ac..04f247f3e 100644 --- a/robot-docs/files.md +++ b/robot-docs/files.md @@ -24,7 +24,7 @@ Reads decode UTF-8 with replacement and recognize Python line boundaries, includ `edit(path, old_str, new_str, line_hint=None)` replaces one exact, unique occurrence: - The file is read with its identity (device, inode, mode, size, mtime), written to a temporary file with the same mode, and published with `os.replace` only while that identity still matches. A concurrent change fails the edit instead of overwriting it. -- A string that does not appear reports the closest candidates with line numbers and a similarity score. +- A string that does not appear reports the closest candidates with line numbers and a similarity score. When the text is there and only whitespace differs (indentation, tabs, trailing spaces, line endings) the message says so first. `cells.run` replacements say the same. - A string that appears several times changes nothing and lists every occurrence's line range with numbered context. Retry with `line_hint=`, or widen `old_str`. A hint only chooses between exact occurrences; it never moves the edit elsewhere. `write(path, content)` replaces a whole file and creates parent directories, for new files rather than edits. diff --git a/robot-docs/kernel.md b/robot-docs/kernel.md index 5f4638f84..80b2aeed9 100644 --- a/robot-docs/kernel.md +++ b/robot-docs/kernel.md @@ -8,6 +8,10 @@ session layer that neither loses nor repeats a message across a reconnect. ## tool bindings +Cells also see the common standard-library modules (`asyncio base64 collections datetime functools hashlib itertools json math os re shutil sys textwrap time`, and `Path`) without importing them; these live in the same session-private builtins, so they are not saved as user variables. `import albedo` and `from albedo import files` answer the injected bindings (`albedo_kernel.Bindings`). + +A cell may not block the kernel with `time.sleep` of a second or more: `albedo_shell` refuses it through the same audit hook that refuses raw subprocess calls, and says to start the work with `run()` and do other useful work while it runs, and when nothing else is left to give the user a status report first, then wait with `await asyncio.sleep(n)`. Job timeouts are seconds (`albedo_api.check_timeout`). + The kernel keeps injected helpers in cell globals and in a session-private copy of Python's builtins. An assignment such as `files = [...]` shadows the helper; `del files` reveals the original binding again, including inside functions and diff --git a/robot-docs/provider-requests.md b/robot-docs/provider-requests.md index 428cbfb6f..4633bd0d0 100644 --- a/robot-docs/provider-requests.md +++ b/robot-docs/provider-requests.md @@ -2,7 +2,7 @@ Every provider call the daemon makes leaves one row in `provider_requests`, a durable account of what the transcript cannot say later: what the request cost, which account served it, how it ended, and what its prefix looked like. This is the recording half of cache- and quota-aware compaction; the analysis (a meter estimator and λ) is derived from these rows on demand, so nothing beyond them is stored. -Rows are written by the worker that streams the call, one per upstream attempt: a turn retried after a gateway hiccup leaves the failed attempt and the successful one as separate rows. Recording must never fail a turn — a failed row write is logged and swallowed, and the call proceeds. +Rows are written by the worker that streams the call, one per upstream attempt (up to 8, doubling from 250 ms, for transport failures, timeouts, an early end, a mid-stream `Overloaded`, and HTTP 502-504, 520-524 and 529 (a plain 500 is not retried); 429s belong to account rotation): a turn retried after a gateway hiccup leaves the failed attempt and the successful one as separate rows. Recording must never fail a turn — a failed row write is logged and swallowed, and the call proceeds. ## What a row holds diff --git a/src/albedo/harness/extensions/agents/extension.gleam b/src/albedo/harness/extensions/agents/extension.gleam index 1b910e280..0ea2dbd42 100644 --- a/src/albedo/harness/extensions/agents/extension.gleam +++ b/src/albedo/harness/extensions/agents/extension.gleam @@ -22,7 +22,7 @@ import gleam/option.{type Option, None, Some} import gleam/result import gleam/string -const instructions = "Agents are sessions you spawn to work in parallel; every call is async. agents.self is your handle (id, name, depth, parent). Call await agents.models() once before spawning; other providers appear as provider/model, and selecting one routes the child through that provider. Then child = await agents.self.spawn(task, name=\"scout\", model=, deliverable=None, evidence_bar=None, falsifier=None): it returns as soon as the child exists, never with its answer. Answers arrive later as in your conversation and start your next turn, so spawn independent children back to back and end your turn instead of waiting; never sleep or poll. Talk with await mail.submit(child, text). await agents.self.children() and siblings() return live snapshots (running, closed). await child.cancel() stops its turn; await child.close() when you are done with it keeps its messages and files and frees its kernel. await agents.get(to) returns a live handle for \"parent\", a family name, or any session id. On any handle, await h.messages(seq=0, offset=0, limit=4000) reads a page of that session's messages from row seq on (content, next_offset) and await h.search_messages(pattern) finds rows by seq: any session may read any other, so you can see what a child or another session did without waiting for mail. await agents.sessions(query=\"\", cwd=None, limit=20, offset=0) lists every session, most recently active first, as snapshots that also carry cwd, model, last_active, and matches; with a query it keeps sessions whose title or name contains it or whose messages do, and matches holds up to 3 of each one's newest matching rows as {seq, preview} to read with messages(seq=...). cwd keeps one directory. Only the user deletes agents: if one should go, ask them. Children nest at most 3 deep and 12 open per parent; mail any session by id instead of nesting to reach it. Children share your workspace, so give two children the same files only if one only reads." +const instructions = "Agents are sessions you spawn to work in parallel; every call is async. agents.self is your handle (id, name, depth, parent). Call await agents.models() once before spawning; other providers appear as provider/model, and selecting one routes the child through that provider. Then child = await agents.self.spawn(task, name=\"scout\", model=, deliverable=None, evidence_bar=None, falsifier=None): it returns as soon as the child exists, never with its answer. Answers arrive later as in your conversation and start your next turn, so spawn independent children back to back and end your turn instead of waiting; never sleep or poll. Talk with await mail.submit(child, text). await agents.self.children() and siblings() return live snapshots (running, closed). await child.cancel() stops its turn, and child.cancel(tree=True) the turns of everything beneath it; await agents.cancel_all(tree=True) stops every child you have, and their descendants, in one call, so use it when the user says to stop the swarm; await child.close() when you are done with it keeps its messages and files and frees its kernel. await agents.get(to) returns a live handle for \"parent\", a family name, or any session id. On any handle, await h.messages(seq=0, offset=0, limit=4000) reads a page of that session's messages from row seq on (content, next_offset) and await h.search_messages(pattern) finds rows by seq: any session may read any other, so you can see what a child or another session did without waiting for mail. await agents.sessions(query=\"\", cwd=None, limit=20, offset=0) lists every session, most recently active first, as snapshots that also carry cwd, model, last_active, and matches; with a query it keeps sessions whose title or name contains it or whose messages do, and matches holds up to 3 of each one's newest matching rows as {seq, preview} to read with messages(seq=...). cwd keeps one directory. Only the user deletes agents: if one should go, ask them. Children nest at most 3 deep and 12 open per parent; mail any session by id instead of nesting to reach it. Children share your workspace, so give two children the same files only if one only reads." pub fn extension() -> extension.Extension { extension.Extension( @@ -126,12 +126,19 @@ fn dispatch( } _ -> Ok(json.array([], json.string)) } - "agents.cancel" | "agents.close" -> { + "agents.close" -> { use child <- result.try(own_child(db, session, args)) - agents.call(case method { - "agents.cancel" -> agents.Stop(child.session) - _ -> agents.Close(child.session) - }) + agents.call(agents.Close(child.session)) + } + "agents.cancel" -> { + use child <- result.try(own_child(db, session, args)) + use tree <- result.try(tree_flag(args)) + stop_all(db, [child], tree) + } + "agents.cancel_all" -> { + use tree <- result.try(tree_flag(args)) + use children <- result.try(family.children(db, session)) + stop_all(db, children, tree) } "agents.messages" -> { use target <- result.try(addressed(db, session, args)) @@ -200,6 +207,53 @@ fn dispatch( } } +fn tree_flag(args: dynamic.Dynamic) -> Result(Bool, String) { + rpc.args( + args, + decode.field("tree", decode.bool, decode.success), + "tree must be a boolean", + ) +} + +/// Interrupts each member's running turn, and with `tree` the turns of +/// everything beneath it, parents first so none can answer a stop by spawning. +/// Answers the sessions that were running. +fn stop_all( + db: store.Store, + members: List(family.Member), + tree: Bool, +) -> Result(json.Json, String) { + use stopped <- result.try(stop_each(db, members, tree)) + Ok(json.array(stopped, json.string)) +} + +fn stop_each( + db: store.Store, + members: List(family.Member), + tree: Bool, +) -> Result(List(String), String) { + list.try_fold(members, [], fn(stopped, member) { + use running <- result.try( + agents.call(agents.Stop(member.session)) + |> result.try(fn(answer) { + read(answer, decode.bool) |> result.replace_error("stop answered oddly") + }), + ) + let stopped = case running { + True -> list.append(stopped, [member.session]) + False -> stopped + } + case tree { + False -> Ok(stopped) + True -> { + use below <- result.try(family.children(db, member.session)) + use more <- result.try(stop_each(db, below, tree)) + Ok(list.append(stopped, more)) + } + } + }) +} + fn own_child( db: store.Store, session: String, diff --git a/src/albedo/harness/extensions/python/cells.gleam b/src/albedo/harness/extensions/python/cells.gleam index 690146724..e4b9c855b 100644 --- a/src/albedo/harness/extensions/python/cells.gleam +++ b/src/albedo/harness/extensions/python/cells.gleam @@ -273,6 +273,7 @@ fn rewritten( }) use changed <- result.try(case string.split(source, old) { [before, after] -> Ok(before <> new <> after) + [_] -> Error(missed(source, old)) _ -> Error("replacement must match exactly once; inspect cells.read first") }) @@ -281,6 +282,29 @@ fn rewritten( }) } +/// The error for old text the cell does not contain, naming a difference in +/// whitespace alone when that is all that separates them. +fn missed(source: String, old: String) -> String { + let base = "replacement must match exactly once; inspect cells.read first" + case string.contains(squash(source), squash(old)) { + True -> + base + <> ". The text is there, but whitespace differs (indentation, tabs," + <> " trailing spaces or line endings)" + False -> base + } +} + +fn squash(text: String) -> String { + text + |> string.replace("\r", " ") + |> string.replace("\t", " ") + |> string.replace("\n", " ") + |> string.split(" ") + |> list.filter(fn(word) { word != "" }) + |> string.join(" ") +} + /// The rewritten source of a dry run: nothing is saved and nothing may execute. pub fn draft( storage: store.Store, diff --git a/src/albedo/harness/extensions/python/extension.gleam b/src/albedo/harness/extensions/python/extension.gleam index f0d8b0636..0d4f6648a 100644 --- a/src/albedo/harness/extensions/python/extension.gleam +++ b/src/albedo/harness/extensions/python/extension.gleam @@ -24,7 +24,7 @@ const default_timeout_ms = 300_000 fn definition() -> types.Tool { types.Tool( "python", - "Execute Python in your persistent session. Provide code (string); timeout_ms (integer, 1–3600000) is optional and defaults to 300000. Cells still running after 60 seconds return status=backgrounded and keep running under their cell id, with the original timeout_ms deadline. The session wakes automatically when they finish: do not poll or sleep. Do other useful work without changing variables the running cell uses, or give the user a short status report and end your turn. await cells.cancel(id) cancels a running cell and suppresses its wake. Read finished results with output.read(id) and await cells.info(id); reading output, source, status, or trace after completion suppresses its wake. Top-level await works. Variables stay alive. If you shadow an injected helper (files, run, cells, etc.), delete that variable with del files to recover the original binding. Only printed output and the final expression return; duration is the cell's wall seconds; truncated=true means the output passed the 64 KiB preview, and the rest (up to 1 MiB) is readable with output.read(cell_id, offset=65536) while the cell is among the 16 most recent; read it before running many more cells, or print less. Failed cells are retained: await cells.read(id) for bounded source, await cells.info(id) for its status (ok, error, interrupted, started, saved) without source, await cells.trace(id) for what the cell read, ran and changed. Repair exact unique text without resending the source with await cells.run(id, replacements=[(old,new)]), or pass check=True first to compile the rewrite and get the syntax error back without running anything. A cell that started requires allow_partial=True after checking side effects; never retry blindly.", + "Execute Python in your persistent session. Provide code (string); timeout_ms (integer, 1–3600000) is optional and defaults to 300000. Cells still running after 60 seconds return status=backgrounded and keep running under their cell id, with the original timeout_ms deadline. The session wakes automatically when they finish: do not poll or sleep. Do other useful work without changing variables the running cell uses, or give the user a short status report and end your turn. await cells.cancel(id) cancels a running cell and suppresses its wake. Read finished results with output.read(id) and await cells.info(id); reading output, source, status, or trace after completion suppresses its wake. Top-level await works. Variables stay alive. asyncio, base64, collections, datetime, functools, hashlib, itertools, json, math, os, pathlib.Path, re, shutil, sys, textwrap and time are already imported, and `from albedo import files` reaches any injected helper. A time.sleep of a second or more is refused because it blocks the whole kernel: start the work with run() and do other useful work while it runs, and if nothing else is left, give the user a status report first, then wait with await asyncio.sleep(n). If you shadow an injected helper (files, run, cells, etc.), delete that variable with del files to recover the original binding. Only printed output and the final expression return; duration is the cell's wall seconds; truncated=true means the output passed the 64 KiB preview, and the rest (up to 1 MiB) is readable with output.read(cell_id, offset=65536) while the cell is among the 16 most recent; read it before running many more cells, or print less. Failed cells are retained: await cells.read(id) for bounded source, await cells.info(id) for its status (ok, error, interrupted, started, saved) without source, await cells.trace(id) for what the cell read, ran and changed. Repair exact unique text without resending the source with await cells.run(id, replacements=[(old,new)]), or pass check=True first to compile the rewrite and get the syntax error back without running anything. A cell that started requires allow_partial=True after checking side effects; never retry blindly.", json.object([ #("type", json.string("object")), #("additionalProperties", json.bool(False)), @@ -181,7 +181,7 @@ pub fn extension() -> extension.Extension { ]), extension.ContextPlugin(place.context), extension.ToolPlugin( - "Python cells automatically background after 60 seconds; the session wakes when they finish, so do not poll or sleep. Python has a persistent namespace, top-level await, cells.read/info/trace and cells.run for saved-source repair (all async), and output.read/output.list for bounded retained output (synchronous; awaiting them also works). cells.last_id is the id of the latest cell, and await cells.list(limit=20) lists this session's cells newest first with their status and first line, even after their output has rolled out. output.read(id, offset=0, limit=4000) returns up to limit characters. output.list() names every retained channel, which is also how to find earlier cells: cells, background jobs, and 'native' for bytes written to fd 1/2 while no cell was running. show_image(source) returns a PNG, JPEG, or WebP (bytes or a file path) to you with this cell's result, so you see it after the cell ends; at most 4 images and 5 MiB per cell.", + "Python cells automatically background after 60 seconds; the session wakes when they finish, so do not poll or sleep. Python has a persistent namespace, top-level await, cells.read/info/trace and cells.run for saved-source repair (all async), and output.read/output.list for bounded retained output (synchronous; awaiting them also works). cells.last_id is the id of the latest cell, and await cells.list(limit=20) lists this session's cells newest first with their status and first line, even after their output has rolled out. output.read(id, offset=0, limit=4000) returns up to limit characters; offset and limit may be positional, and job.tail()/job.head() answer awaitably too. output.list() names every retained channel, which is also how to find earlier cells: cells, background jobs, and 'native' for bytes written to fd 1/2 while no cell was running. show_image(source) returns a PNG, JPEG, or WebP (bytes or a file path) to you with this cell's result, so you see it after the cell ends; at most 4 images and 5 MiB per cell.", [extension.Tool(definition(), invoke, recover)], [], [#("cells", cells.handle)], diff --git a/src/albedo/harness/extensions/run/extension.gleam b/src/albedo/harness/extensions/run/extension.gleam index a21424f14..7dddc53c4 100644 --- a/src/albedo/harness/extensions/run/extension.gleam +++ b/src/albedo/harness/extensions/run/extension.gleam @@ -12,7 +12,7 @@ import gleam/json import gleam/option.{None} import gleam/result -const instructions = "run(program, *args, cwd=None, env=None, stdin=None, timeout=300) starts one program without a shell and returns its job handle right away; run is not async, and awaiting the handle waits for the program: job = run(\"go\", \"test\", \"./...\", cwd=\"cli\"), then await job, then job.exit_code and job.tail(lines=20). Bind the handle before awaiting it: job = await run(...) blocks before the assignment, so a cell interrupted mid-wait leaves the running job only in jobs. There is no shell, so shell syntax has Python spellings: cd dir && ... is cwd=, NAME=value is env= (added to the kernel's environment), | tail -n 20 is job.tail(lines=20), | head -n 20 is job.head(lines=20), a | b is .pipe(): run() and job.pipe(program, *args) return handles at once, so chain first and await once, as in job = run(\"git\", \"log\", \"--oneline\").pipe(\"rg\", \"fix\").pipe(\"sort\", \"-u\"); await job; the stages stream like a shell pipe, the await waits for the last one, and job.pipeline is the whole line, 2>&1 is implied (stderr joins stdout), stdin= takes text, bytes, a path, or another job, and &&, loops, and globs are Python over job.exit_code and the output. `sh -c` and subprocess/os.system from a cell are refused with the run() call they mean. Programs start at once at low priority and are never paused for admission. The timeout (seconds) counts wall time after the program starts. Await the handle for completion, or keep it in a variable. jobs is a dict of job id to handle for this session. A job's output lives on its handle (job.tail(n=4000) for the last n characters, lines= for lines; job.command is what ran, job.argv as a list) and stays readable in full with output.read(job.id, offset=0, limit=4000); await job.stop() ends it. job.exit_code, job.duration, and job.timed_out report the exit status, the seconds it ran, and deadline state once the program ends (job.poll() and job.returncode are subprocess-style spellings of job.exit_code). A job that finishes with its result unread wakes the session by itself, so polling a handle is optional: leave it in a variable, end the cell, and a notice naming the job arrives once the session is idle. A job that finishes while you are still working is reported after your turn ends, unless you read it first. Awaiting the job, reading its result, or stopping it first means no wake." +const instructions = "run(program, *args, cwd=None, env=None, stdin=None, timeout=300) starts one program without a shell and returns its job handle right away; run is not async, and awaiting the handle waits for the program: job = run(\"go\", \"test\", \"./...\", cwd=\"cli\"), then await job, then job.exit_code and job.tail(lines=20). Bind the handle before awaiting it: job = await run(...) blocks before the assignment, so a cell interrupted mid-wait leaves the running job only in jobs. There is no shell, so shell syntax has Python spellings: cd dir && ... is cwd=, NAME=value is env= (added to the kernel's environment), | tail -n 20 is job.tail(lines=20), | head -n 20 is job.head(lines=20), a | b is .pipe(): run() and job.pipe(program, *args) return handles at once, so chain first and await once, as in job = run(\"git\", \"log\", \"--oneline\").pipe(\"rg\", \"fix\").pipe(\"sort\", \"-u\"); await job; the stages stream like a shell pipe, the await waits for the last one, and job.pipeline is the whole line, 2>&1 is implied (stderr joins stdout), stdin= takes text, bytes, a path, or another job, and &&, loops, and globs are Python over job.exit_code and the output. `sh -c` and subprocess/os.system from a cell are refused with the run() call they mean, and so is a time.sleep of a second or more: start the work with run() and do other useful work while it runs; if nothing else is left, give the user a status report first, then wait with await asyncio.sleep(n). Programs start at once at low priority and are never paused for admission. The timeout (seconds) counts wall time after the program starts. Await the handle for completion, or keep it in a variable. jobs is a dict of job id to handle for this session. A job's output lives on its handle (job.tail(n=4000) for the last n characters, lines= for lines; job.command is what ran, job.argv as a list) and stays readable in full with output.read(job.id, offset=0, limit=4000); await job.stop() ends it. job.exit_code, job.duration, and job.timed_out report the exit status, the seconds it ran, and deadline state once the program ends (job.poll() and job.returncode are subprocess-style spellings of job.exit_code). A job that finishes with its result unread wakes the session by itself, so polling a handle is optional: leave it in a variable, end the cell, and a notice naming the job arrives once the session is idle. A job that finishes while you are still working is reported after your turn ends, unless you read it first. Awaiting the job, reading its result, or stopping it first means no wake." pub fn extension() -> harness_extension.Extension { harness_extension.Extension( diff --git a/src/albedo/harness/loop.gleam b/src/albedo/harness/loop.gleam index 66c37f51c..9c605fb62 100644 --- a/src/albedo/harness/loop.gleam +++ b/src/albedo/harness/loop.gleam @@ -744,9 +744,9 @@ fn describe(upstream: extension.Upstream, error: types.Error) -> String { fn retryable(error: types.Error) -> Bool { case error { types.ConnectionError(_) | types.Timeout | types.UnexpectedEnd -> True - types.HttpError(502, _) - | types.HttpError(503, _) - | types.HttpError(504, _) -> True + types.HttpError(status, _) -> + list.contains([502, 503, 504, 520, 521, 522, 523, 524, 529], status) + types.ProviderError("Overloaded") -> True _ -> False } } diff --git a/src/albedo/openai_api.gleam b/src/albedo/openai_api.gleam index 5fbc9fe03..0d504a9f9 100644 --- a/src/albedo/openai_api.gleam +++ b/src/albedo/openai_api.gleam @@ -13,7 +13,7 @@ //// ``` //// //// Callbacks run in the calling process. Returning Stop closes the connection. -//// There are no automatic retries: an interrupted attempt may have incurred cost. +//// This module does not retry; the tool loop reissues transient failures. //// Replay final output using types.Replay; never flatten it to assistant text. //// Supports text, image input, and function tools. Audio and custom tools are //// unsupported. Function arguments must be validated before execution. diff --git a/test/e2e/agents_test.py b/test/e2e/agents_test.py index 88b868ec2..8b93c7e7f 100644 --- a/test/e2e/agents_test.py +++ b/test/e2e/agents_test.py @@ -826,6 +826,43 @@ class AgentsTests(unittest.TestCase): self.assertIsNone(snapshot["workspace_change"]) self.assertFalse((self.app.workspace / "restored-child-cwd").exists()) + def test_cancel_all_stops_every_running_turn_beneath_the_caller(self): + entered = {"mid": threading.Event(), "leaf": threading.Event()} + release = threading.Event() + self.addCleanup(release.set) + answer = self.provider.script + + def held(request): + user = user_message(request) + for name, gate in entered.items(): + if f"hold {name}" in user: + gate.set() + release.wait(30) + return text("held turn ended") + if request["messages"][-1].get("role") == "user" and user == "stop all": + return python("print(sorted(await agents.cancel_all()))") + return answer(request) + + self.provider.script = held + parent = self.app.session() + mid = self.spawn(parent, "mid", "hold mid")["id"] + leaf = self.spawn(mid, "leaf", "hold leaf")["id"] + for gate in entered.values(): + self.assertTrue(gate.wait(30), "a held turn never reached the provider") + self.send(parent, "stop all") + for session in (parent, mid, leaf): + self.app.idle(session) + self.assertFalse(release.is_set()) + result = next( + json.loads(part["value"]) + for entry in reversed(self.app.history(parent)["items"]) + if entry["kind"] == "tool_result" + for part in entry["content"] + if part["kind"] == "json" and part["field"] == "result" + ) + self.assertEqual(result["status"], "ok", result) + self.assertEqual(result["output"].strip(), str(sorted([mid, leaf]))) + def test_qualified_and_inferred_cross_provider_models(self): parent = self.app.session() self.change(parent, {"name": "radio desk"}) diff --git a/test/e2e/cell_background_test.py b/test/e2e/cell_background_test.py index 4df1d60f6..e46d4a485 100644 --- a/test/e2e/cell_background_test.py +++ b/test/e2e/cell_background_test.py @@ -59,7 +59,7 @@ class CellBackgroundTests(unittest.TestCase): "{'answer': 42}" ) if self.synchronous: - code = "import time\nprint('before detach')\ntime.sleep(10)\nprint('after detach')" + code = "import threading\nprint('before detach')\nthreading.Event().wait(10)\nprint('after detach')" if self.deadline: return Reply( "python", tool_arguments={"code": code, "timeout_ms": 1800} diff --git a/test/e2e/kernel_detach_test.py b/test/e2e/kernel_detach_test.py index 57b34e32f..37712d207 100644 --- a/test/e2e/kernel_detach_test.py +++ b/test/e2e/kernel_detach_test.py @@ -91,7 +91,7 @@ class KernelDetachTests(unittest.TestCase): os.kill(bridge, signal.SIGKILL) slept = self.cell( - "import time\ntime.sleep(3)\nprint('woke')\nos.getpid()", + "import threading\nthreading.Event().wait(3)\nprint('woke')\nos.getpid()", during=kill_bridge, ) self.assertEqual(slept["status"], "ok", slept) diff --git a/test/e2e/lifecycle_test.py b/test/e2e/lifecycle_test.py index 478df0711..fc19d513d 100644 --- a/test/e2e/lifecycle_test.py +++ b/test/e2e/lifecycle_test.py @@ -330,11 +330,11 @@ class LifecycleTest(unittest.TestCase): if messages[-1]["role"] == "tool": return text("tool finished") return python( - "from pathlib import Path\nimport time\n" + "from pathlib import Path\nimport threading\n" f"with Path({str(fixture['effect'])!r}).open('a') as effect:\n" " effect.write('effect applied\\n')\n" " effect.flush()\n" - "time.sleep(60)" + "threading.Event().wait(60)" ) provider = Provider(script) diff --git a/test/e2e/python_test.py b/test/e2e/python_test.py index bc122a18c..fd0732f3f 100644 --- a/test/e2e/python_test.py +++ b/test/e2e/python_test.py @@ -77,6 +77,17 @@ class PythonToolsTests(unittest.TestCase): self.assertIn("same", output) self.assertIn("changed", output) + def test_an_edit_miss_says_when_only_whitespace_differs(self): + (self.app.workspace / "note.txt").write_text("if ok:\n run()\n") + output = self.execute( + "for old in ('if ok:\\n\\trun()', 'absent'):\n" + " try:\n files.edit('note.txt', old, 'x')\n" + " except ValueError as error:\n print(str(error).splitlines()[0])" + ) + lines = output.splitlines() + self.assertIn("whitespace differs", lines[0]) + self.assertNotIn("whitespace differs", lines[1]) + def test_find_searches_workspace_and_returns_context(self): (self.app.workspace / "note.txt").write_text("before\nneedle\nafter\n") output = self.execute( @@ -301,6 +312,31 @@ class PythonToolsTests(unittest.TestCase): ) self.assertEqual(output.strip(), "range and path errors preserved") + def test_cells_get_the_api_a_model_reaches_for(self): + output = self.execute( + "job = run('echo', 'hello')\n" + "await job\n" + "assert (await job.tail()).strip() == 'hello'\n" + "assert (await job.head(lines=1)).strip() == 'hello'\n" + "assert output.read(job.id, 0, 3) == 'hel'\n" + "from albedo import files as imported\n" + "assert imported is files\n" + "assert re.fullmatch('a+', 'aa') and Path('.').is_dir()\n" + "assert hashlib.md5(b'').hexdigest() and json.dumps(os.sep)\n" + "try:\n" + " run('true', timeout=120000)\n" + "except ValueError as error:\n" + " assert 'seconds' in str(error) and 'milliseconds' in str(error), error\n" + "try:\n" + " time.sleep(2)\n" + "except PermissionError as error:\n" + " assert 'run()' in str(error) and 'asyncio.sleep' in str(error), error\n" + "time.sleep(0.01)\n" + "await asyncio.sleep(0.01)\n" + "print('api shapes ok')" + ) + self.assertEqual(output.strip(), "api shapes ok") + def test_a_cell_reports_how_long_it_ran(self): session = self.app.session() slept = self.run_cell("import asyncio\nawait asyncio.sleep(0.3)", session) diff --git a/test/e2e/remote_kernels_test.py b/test/e2e/remote_kernels_test.py index 7226a663a..016493a0f 100644 --- a/test/e2e/remote_kernels_test.py +++ b/test/e2e/remote_kernels_test.py @@ -276,7 +276,7 @@ class RemoteKernelTests(unittest.TestCase): slept = self.cell( session, - "import time\ntime.sleep(3)\nprint('woke')\nos.getpid()", + "import threading\nthreading.Event().wait(3)\nprint('woke')\nos.getpid()", during=kill_bridge, ) self.assertEqual(slept["status"], "ok", slept) diff --git a/test/harness/cell_repair_test.gleam b/test/harness/cell_repair_test.gleam index d0b72a779..ac686d09b 100644 --- a/test/harness/cell_repair_test.gleam +++ b/test/harness/cell_repair_test.gleam @@ -59,6 +59,17 @@ pub fn ambiguous_repairs_and_compile_errors_do_not_execute_test() -> Nil { let assert Ok(denied) = denied.result denied.status |> should.equal(python.Failed) denied.output |> string.contains("exactly once") |> should.be_true + let assert Ok(spaced) = + runtime.execute( + host, + session, + "await cells.run('" + <> original.id + <> "', replacements=[('state =\\n1', '2')])", + 5000, + ) + let assert Ok(spaced) = spaced.result + spaced.output |> string.contains("whitespace differs") |> should.be_true let assert Ok(state) = runtime.execute(host, session, "'state' in globals()", 5000) let assert Ok(state) = state.result -- knotmirror 0.0.1