Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(agent-core): one timeout decider, edits bound to the file read, best-effort stop records, Node file URLs
cyhc89526faf2d9
diff --git a/core/agent_core/tools/bash.py b/core/agent_core/tools/bash.pyindex df2b34f59..f441e19d5 100644--- a/core/agent_core/tools/bash.py+++ b/core/agent_core/tools/bash.py@@ -180,8 +180,8 @@ class BashTool:if ctx.cancel.cancelled:return error_result("Command aborted")- # Measured from before the start, so this deadline passes no later than the job's recorded one and- # the foreground reports the timeout itself.+ # The job host enforces the timeout (its wrapper decides timeout versus exit); bash only reports+ # the recorded reason. This clock times the handover.started = time.monotonic()try:job_id = await self._jobs.start(@@ -208,8 +208,6 @@ class BashTool:hand_over = handover_error is None and elapsed >= handover_at# A handover is decided only after a fresh status: a command that already ended keeps its own result.slice_s = 0.0 if hand_over else _PROGRESS_INTERVAL_S- if timeout is not None:- slice_s = min(slice_s, max(0.0, timeout - elapsed))if handover_error is None:slice_s = min(slice_s, max(0.0, handover_at - elapsed))status = await self._wait_or_cancel(job_id, slice_s, ctx.cancel)@@ -227,9 +225,6 @@ class BashTool:if ctx.cancel.cancelled:await self._jobs.kill(job_id, reason=STOP_ABORTED)return stopped_result(output, "Command aborted")- if timeout is not None and time.monotonic() - started >= timeout:- await self._jobs.kill(job_id, reason=STOP_TIMEOUT)- return stopped_result(output, _timed_out_line(timeout))if hand_over:watch_id, handover_error = await self._hand_over(job_id)if watch_id is not None:diff --git a/core/agent_core/tools/edit.py b/core/agent_core/tools/edit.pyindex f13335abb..ace4ea92a 100644--- a/core/agent_core/tools/edit.py+++ b/core/agent_core/tools/edit.py@@ -28,7 +28,7 @@ from core.agent_core.tools.paths import ()from core.agent_core.tools.text import decode_file, encode_file, model_textfrom core.agent_core.tools.truncate import format_size-from core.agent_core.tools.write import write_bytes+from core.agent_core.tools.write import FileChanged, FileIdentity, write_bytes#: Avibe: larger files are refused rather than loaded whole; the display diff stops at a smaller size.MAX_EDIT_BYTES = 10 * 1024 * 1024@@ -131,16 +131,19 @@ class _TooLarge(Exception):self.size = size-def _plan_edits(absolute: str, edits: list[Edit], path: str) -> tuple[int, bytes, str, str]:- """Read the file and compute its new bytes: ``(size, data, view_before, view_after)``.+def _plan_edits(absolute: str, edits: list[Edit], path: str) -> tuple[int, bytes, str, str, FileIdentity]:+ """Read the file and compute its new bytes: ``(size, data, view_before, view_after, identity)``.One descriptor gives the size and the contents, read up to the limit, so a file that grew after anearlier check by path cannot get past it. ``surrogateescape`` carries bytes that are not UTF-8- through unchanged; only replaced spans change.+ through unchanged; only replaced spans change. ``identity`` is the file that was read, so the+ result is published only over it."""- fd = open_regular(absolute)+ real = os.path.realpath(absolute)+ fd = open_regular(real)try:- size = os.fstat(fd).st_size+ st = os.fstat(fd)+ size = st.st_sizeif size > MAX_EDIT_BYTES:raise _TooLarge(size)raw = read_at_most(fd, MAX_EDIT_BYTES)@@ -149,7 +152,7 @@ def _plan_edits(absolute: str, edits: list[Edit], path: str) -> tuple[int, bytesif len(raw) > MAX_EDIT_BYTES:raise _TooLarge(max(size, len(raw)))new_text, before, after = apply_edits(decode_file(raw), edits, path)- return len(raw), encode_file(new_text), before, after+ return len(raw), encode_file(new_text), before, after, FileIdentity.of(real, st)class EditTool:@@ -184,7 +187,7 @@ class EditTool:if not os.access(absolute, os.R_OK | os.W_OK):return error_result(f"Could not edit file: {path}. Error code: EACCES.")try:- size, data, base, new_content = await to_thread_joined(_plan_edits, absolute, edits, path)+ size, data, base, new_content, identity = await to_thread_joined(_plan_edits, absolute, edits, path)if len(data) > MAX_EDIT_BYTES:return error_result(f"File {path} would be {format_size(len(data))} after this edit, over the "@@ -193,7 +196,7 @@ class EditTool:)if ctx.cancel.cancelled:return error_result("Operation aborted")- await to_thread_joined(write_bytes, absolute, data)+ await to_thread_joined(write_bytes, absolute, data, identity)except _TooLarge as exc:# The whole file and several copies would sit in the process every Session shares.return error_result(@@ -202,6 +205,11 @@ class EditTool:)except EditError as exc:return error_result(str(exc))+ except FileChanged:+ # Another writer (bash, an editor) changed it after it was read: the edit would overwrite that.+ return error_result(+ f"Could not edit file: {path}. It changed while the edit was being applied; read it again."+ )except NotRegularFile as exc:detail = "Error code: EISDIR." if exc.kind == "directory" else "It is not a regular file."return error_result(f"Could not edit file: {path}. {detail}")diff --git a/core/agent_core/tools/job_wrapper.py b/core/agent_core/tools/job_wrapper.pyindex bf7e0eec3..3f1d18b48 100644--- a/core/agent_core/tools/job_wrapper.py+++ b/core/agent_core/tools/job_wrapper.py@@ -143,9 +143,11 @@ def _run(job_dir: str, proc: subprocess.Popen, log: _BoundedLog, deadline: Optio_write_atomic(os.path.join(job_dir, "exit"), b"%d\n" % (code if code >= 0 else 128 - code))def enforce_deadline() -> None:- # J3: the deadline holds even when no host is there to enforce it.- if not exit_written and deadline is not None and time.time() >= deadline:- _stop_group(job_dir, "timeout", proc)+ # J3: the deadline holds even when no host is there to enforce it. The wrapper alone decides+ # timeout versus exit, and it looks at the shell first: one that has exited is never a timeout.+ if exit_written or deadline is None or time.time() < deadline or proc.poll() is not None:+ return+ _stop_group(job_dir, "timeout", proc)while not eof:enforce_deadline()diff --git a/core/agent_core/tools/jobs.py b/core/agent_core/tools/jobs.pyindex 59f2b6ed5..41573daba 100644--- a/core/agent_core/tools/jobs.py+++ b/core/agent_core/tools/jobs.py@@ -87,6 +87,9 @@ STOP_TIMEOUT = "timeout"STOP_ABORTED = "aborted"_WRAPPER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "job_wrapper.py")+#: How long past the deadline the host leaves a live wrapper to decide (its poll interval, its+#: 0.5 s drain, and margin) before stopping the job itself.+_WRAPPER_DECIDES_S = 1.0_JOB_ID = re.compile(r"^job_[a-z0-9]+$")_GO = "go"_ABANDON = "abandon"@@ -416,7 +419,11 @@ class LocalJobHost:if _group_exists(identity.pid):logger.warning("Job %s process group %s cannot be verified; not signaling", job_id, identity.pid)return- self._create_once(job_id, "stopped", reason) # the first stopper's reason wins+ try:+ self._create_once(job_id, "stopped", reason) # the first stopper's reason wins+ except OSError:+ # Recording is best effort at every stopper: the kill matters more than the record.+ logger.warning("Could not record why job %s was stopped", job_id, exc_info=True)if not await asyncio.to_thread(_terminate_group, identity.pid):logger.warning("Job %s process group %s survived termination", job_id, identity.pid)@@ -446,11 +453,17 @@ class LocalJobHost:# --- deadline (J3) and reporting --------------------------------------async def enforce_deadline(self, job_id: str) -> bool:- """Kill the job if its ``deadline_at`` has passed while it runs; ``True`` if it was killed."""+ """Kill the job if its ``deadline_at`` has passed while it runs; ``True`` if it was killed.++ Only the wrapper sees the shell exit, and it publishes the exit after draining the output, so a+ running job may already have ended on time: a live wrapper decides timeout versus exit. The+ host stops the job as the second owner once the wrapper has not, ``_WRAPPER_DECIDES_S`` late.+ """deadline_at = self.meta(job_id).get("deadline_at")- if not deadline_at or datetime.now(timezone.utc) < _parse_iso(deadline_at):+ if not deadline_at:return False- if self.status(job_id).state != "running":+ late = (datetime.now(timezone.utc) - _parse_iso(deadline_at)).total_seconds()+ if late < _WRAPPER_DECIDES_S or self.status(job_id).state != "running":return Falseawait self.kill(job_id, reason=STOP_TIMEOUT)return Truediff --git a/core/agent_core/tools/output.py b/core/agent_core/tools/output.pyindex 199e78c8f..b7f3678c9 100644--- a/core/agent_core/tools/output.py+++ b/core/agent_core/tools/output.py@@ -30,7 +30,8 @@ class OutputAccumulator:self._tail_starts_at_line_boundary = Trueself._total_bytes = 0self._completed_lines = 0- self._current_line_bytes = 0+ # The size of the last line, open or completed: what the partial-line notice names.+ self._last_line_bytes = 0self._has_open_line = Falsedef append(self, text: str) -> None:@@ -43,14 +44,21 @@ class OutputAccumulator:if self._tail_bytes > self._max_rolling * 2:self._trim()newlines = text.count("\n")+ carried = self._last_line_bytes if self._has_open_line else 0if newlines == 0:- self._current_line_bytes += size+ self._last_line_bytes = carried + sizeself._has_open_line = True+ return+ self._completed_lines += newlines+ last = text.rindex("\n")+ rest = text[last + 1 :]+ if rest:+ self._last_line_bytes = utf8_len(rest)else:- self._completed_lines += newlines- rest = text[text.rindex("\n") + 1 :]- self._current_line_bytes = utf8_len(rest)- self._has_open_line = bool(rest)+ # Avibe fix to Pi, whose count drops to 0 here: a completed last line keeps its size.+ previous = text.rfind("\n", 0, last)+ self._last_line_bytes = (carried if previous == -1 else 0) + utf8_len(text[previous + 1 : last])+ self._has_open_line = bool(rest)def snapshot(self, open_line: str = "") -> TruncationResult:"""The tail as the model would see it, with ``open_line`` (not yet final) appended."""@@ -67,7 +75,10 @@ class OutputAccumulator:)def last_line_bytes(self, open_line: str = "") -> int:- return (self._current_line_bytes if self._has_open_line else 0) + utf8_len(open_line)+ """Bytes of the last line: the open one plus ``open_line`` (not yet final), else the last completed one."""+ if open_line:+ return (self._last_line_bytes if self._has_open_line else 0) + utf8_len(open_line)+ return self._last_line_bytesdef _trim(self) -> None:data = self._tail.encode("utf-8", "surrogatepass")diff --git a/core/agent_core/tools/paths.py b/core/agent_core/tools/paths.pyindex 1af590c4b..afb24b64a 100644--- a/core/agent_core/tools/paths.py+++ b/core/agent_core/tools/paths.py@@ -28,6 +28,14 @@ _WINDOWS = os.name == "nt"_ENCODED_SEPARATOR = re.compile("%2f", re.IGNORECASE)_ENCODED_SEPARATOR_WINDOWS = re.compile("%2f|%5c", re.IGNORECASE)_MALFORMED_ESCAPE = re.compile("%(?![0-9a-fA-F]{2})")+_C0_OR_SPACE = "".join(map(chr, range(0x21)))+_TAB_OR_NEWLINE = dict.fromkeys(map(ord, "\t\n\r"))+_QUERY_OR_FRAGMENT = re.compile("[?#]")+_DRIVE = re.compile(r"[A-Za-z][:|]\Z")+_NORMALIZED_DRIVE = re.compile(r"[A-Za-z]:\Z")+_FORBIDDEN_HOST = re.compile(r"[\x00-\x20#%/:<>?@\[\\\]^|\x7f]")+_SINGLE_DOT = {".", "%2e"}+_DOUBLE_DOT = {"..", ".%2e", "%2e.", "%2e%2e"}def expand_path(path: str) -> str:@@ -43,28 +51,77 @@ def expand_path(path: str) -> str:def _file_url_to_path(url: str) -> str:- """Node's ``fileURLToPath``, which Pi uses.-- An empty or ``localhost`` host names this machine. Any other host is a UNC share on Windows and- an error elsewhere, so a URL can never name a local file it did not mean. Encoded separators- are refused, as Node refuses them.+ """Node's ``fileURLToPath``, which Pi uses, after the WHATWG URL parser's steps for a file URL.++ The parser removes C0 controls and spaces at either end and every tab and newline, reads a+ backslash as ``/``, drops the query and fragment, percent-decodes and lowercases the host, takes+ ``file://C:/`` as a path, writes a drive ``C|`` as ``C:``, and resolves ``.`` and ``..`` segments+ (``%2e`` too) without climbing above a drive. An empty or ``localhost`` host names this machine.+ Any other host is a UNC share on Windows and an error elsewhere, so a URL can never name a local+ file it did not mean. Encoded separators are refused, as Node refuses them."""- parsed = urlparse(url)- host = "" if parsed.netloc.lower() == "localhost" else parsed.netloc+ rest = url.strip(_C0_OR_SPACE).translate(_TAB_OR_NEWLINE).replace("\\", "/")[len("file://") :]+ rest = _QUERY_OR_FRAGMENT.split(rest, maxsplit=1)[0]+ authority, slash, path = rest.partition("/")+ if _DRIVE.match(authority):+ authority, path = "", f"{authority}/{path}" if slash else authority+ host = _url_host(authority)+ pathname = _url_pathname(path)if _WINDOWS:- if _ENCODED_SEPARATOR_WINDOWS.search(parsed.path):+ if _ENCODED_SEPARATOR_WINDOWS.search(pathname):raise ToolInputError("Invalid path: a file URL must not include encoded \\ or / characters")- path = _decode_url_path(parsed.path).replace("/", "\\")+ local = _decode_url_path(pathname).replace("/", "\\")if host:- return f"\\\\{host}{path}"- if len(path) >= 3 and path[0] == "\\" and path[1].isascii() and path[1].isalpha() and path[2] == ":":- return path[1:]+ return f"\\\\{host}{local}"+ if len(local) >= 3 and local[1].isascii() and local[1].isalpha() and local[2] == ":":+ return local[1:]raise ToolInputError("Invalid path: a file URL must be absolute")if host:raise ToolInputError("Invalid path: file URL host must be empty or localhost")- if _ENCODED_SEPARATOR.search(parsed.path):+ if _ENCODED_SEPARATOR.search(pathname):raise ToolInputError("Invalid path: a file URL must not include encoded / characters")- return _decode_url_path(parsed.path)+ return _decode_url_path(pathname)+++def _url_host(authority: str) -> str:+ """The WHATWG host of a file URL: percent-decoded, lowercased, and empty for ``localhost``."""+ if not authority:+ return ""+ try:+ host = unquote(authority, errors="strict")+ if host.startswith("[") and host.endswith("]"):+ host = host.lower() # an IPv6 literal+ else:+ if not host.isascii() or "xn--" in host.lower():+ host = host.encode("idna").decode("idna")+ host = host.lower()+ if _FORBIDDEN_HOST.search(host):+ raise ValueError(host)+ except (UnicodeError, ValueError):+ raise ToolInputError("Invalid path: a file URL must have a valid host") from None+ return "" if host == "localhost" else host+++def _url_pathname(path: str) -> str:+ """The WHATWG path of a file URL (still percent-encoded), from the text after the authority's ``/``."""+ segments: list[str] = []+ parts = path.split("/")+ for index, segment in enumerate(parts):+ last = index == len(parts) - 1+ lowered = segment.lower()+ if lowered in _DOUBLE_DOT:+ if segments and not (len(segments) == 1 and _NORMALIZED_DRIVE.match(segments[0])):+ segments.pop()+ if last:+ segments.append("")+ elif lowered in _SINGLE_DOT:+ if last:+ segments.append("")+ else:+ if not segments and _DRIVE.match(segment):+ segment = segment[0] + ":"+ segments.append(segment)+ return "/" + "/".join(segments)def _decode_url_path(path: str) -> str:diff --git a/core/agent_core/tools/write.py b/core/agent_core/tools/write.pyindex 4fcc618e0..057f8228d 100644--- a/core/agent_core/tools/write.py+++ b/core/agent_core/tools/write.py@@ -11,6 +11,7 @@ import contextlibimport osimport secretsimport stat+from dataclasses import dataclassfrom typing import Any, Mapping, Optionalfrom core.agent_core.tools.args import ToolInputError, error_result, str_arg, text_result@@ -103,13 +104,41 @@ def write_text(path: str, content: str) -> None:write_bytes(path, model_text(content).encode("utf-8"))-def write_bytes(path: str, data: bytes) -> None:+class FileChanged(Exception):+ """The file is no longer the one a read-modify-write read; nothing was written."""+++@dataclass(frozen=True)+class FileIdentity:+ """The file a read-modify-write read, so its result is published only over that same file."""++ path: str # the realpath that was read+ dev: int+ ino: int+ size: int+ mtime_ns: int++ @classmethod+ def of(cls, path: str, st: os.stat_result) -> "FileIdentity":+ return cls(path, st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns)+++def _require(expected: Optional[FileIdentity], path: str, st: os.stat_result) -> None:+ if expected is not None and FileIdentity.of(path, st) != expected:+ raise FileChanged()+++def write_bytes(path: str, data: bytes, expected: Optional[FileIdentity] = None) -> None:"""Create or replace ``path`` only once ``data`` is completely on disk.A failed write (a full disk, a quota) leaves the original, or its absence, as it was. The tempfile sits beside the real target (through symlinks) and is private (0600) while it holds the newcontents; once they are fsynced it takes the existing file's mode, or the umask default for a newfile, and replaces the target with ``os.replace``.++ With ``expected``, the file must still be the one that was read: checked once, right before the+ rename, or with ``fstat`` on the descriptor an in-place write goes through. POSIX has no+ compare-and-rename, so a change between that check and the rename is not seen."""target = os.path.realpath(path)try:@@ -124,6 +153,7 @@ def write_bytes(path: str, data: bytes) -> None:raise# An existing, writable file in a directory we cannot add to: only an in-place write is possible.with os.fdopen(open_regular(target, os.O_WRONLY), "wb") as handle:+ _require(expected, target, os.fstat(handle.fileno()))handle.truncate(0)handle.write(data)return@@ -133,6 +163,12 @@ def write_bytes(path: str, data: bytes) -> None:handle.flush()os.fsync(handle.fileno())os.fchmod(handle.fileno(), mode if mode is not None else 0o666 & ~_UMASK)+ if expected is not None:+ current = os.path.realpath(path)+ try:+ _require(expected, current, os.stat(current))+ except FileNotFoundError:+ raise FileChanged() from Noneos.replace(tmp, target)except BaseException:with contextlib.suppress(FileNotFoundError):diff --git a/tests/agent_core/tools/test_bash.py b/tests/agent_core/tools/test_bash.pyindex 1b82d999e..657e1e2fd 100644--- a/tests/agent_core/tools/test_bash.py+++ b/tests/agent_core/tools/test_bash.py@@ -4,7 +4,9 @@ from __future__ import annotationsimport asyncioimport errno+import functoolsimport os+import signalimport timeimport psutil@@ -70,6 +72,18 @@ async def test_a_log_bounded_on_disk_is_not_called_the_full_output(tmp_path, makassert result.details["omitted_bytes"] == len("".join(f"{i}\n" for i in range(1, 100001))) - 3000+async def test_a_completed_overlong_line_reports_its_size(tmp_path, make_ctx):+ """Avibe fix to Pi: the partial-line notice names the size of the last line even once it is complete."""+ command = "head -c 60000 /dev/zero | tr '\\0' x; echo"++ result = await BashTool(_host(tmp_path)).execute({"command": command}, make_ctx())++ path = result.details["output_path"]+ assert result_text(result).endswith(+ f"\n\n[Showing last 50.0KB of line 1 (line is 58.6KB). Output log (middle omitted beyond 3.0MB): {path}]"+ )++async def test_a_non_zero_exit_is_an_error_result(tmp_path, make_ctx):result = await BashTool(_host(tmp_path)).execute({"command": "echo oops >&2; exit 3"}, make_ctx())@@ -201,6 +215,50 @@ async def test_stops_are_reported_through_the_agents_job_host(tmp_path, make_ctxassert (result.is_error, result_text(result)) == (True, expected)[email protected]("caller", ["host", "bash"])+async def test_only_a_live_wrapper_decides_at_the_deadline(tmp_path, make_ctx, monkeypatch, caller):+ """Only the wrapper sees the shell exit; the host and bash leave a live wrapper a grace, then stop the job."""+ monkeypatch.setattr(jobs_module, "_WRAPPER_DECIDES_S", 0.6)+ quick_kill = functools.partial(jobs_module._terminate_group, timeout_s=0.3)+ monkeypatch.setattr(jobs_module, "_terminate_group", quick_kill)+ host = _host(tmp_path)+ command = f"echo $$ > {tmp_path / 'sh.pid'}; sleep 30"+ started = time.monotonic()+ if caller == "bash":+ running = asyncio.ensure_future(BashTool(host).execute({"command": command, "timeout": 1.0}, make_ctx()))+ job_id = None+ while job_id is None:+ await asyncio.sleep(0.01)+ job_id = host.find_job("ses_test", "toolu_1")+ else:+ job_id = await host.start(+ command,+ cwd=str(tmp_path),+ env={"PATH": os.environ["PATH"]},+ timeout_s=1.0,+ session_id="ses_test",+ tool_call_id="toolu_1",+ )+ running = asyncio.ensure_future(host.wait(job_id, deadline_s=None))+ wrapper_pid = os.path.join(host.job_dir(job_id), "pid")+ while not (os.path.exists(wrapper_pid) and (tmp_path / "sh.pid").exists()):+ await asyncio.sleep(0.01)+ os.kill(int(open(wrapper_pid).read()), signal.SIGSTOP) # the wrapper can no longer decide+ shell_pid = int((tmp_path / "sh.pid").read_text())++ await asyncio.sleep(max(0.0, started + 1.3 - time.monotonic())) # past the deadline, inside the grace+ alive_in_grace = psutil.pid_exists(shell_pid) and psutil.Process(shell_pid).status() != psutil.STATUS_ZOMBIE+ outcome = await asyncio.wait_for(running, timeout=10)++ assert alive_in_grace+ assert host.stop_reason(job_id) == "timeout"+ if caller == "bash":+ assert result_text(outcome).endswith("Command timed out after 1 seconds")+ else:+ assert outcome.state == "gone"+ assert _process_gone(shell_pid)++async def test_the_foreground_window_hands_over_and_the_command_runs_once(tmp_path, make_ctx):watches = Watches()host = _host(tmp_path, watches)diff --git a/tests/agent_core/tools/test_jobs.py b/tests/agent_core/tools/test_jobs.pyindex 69fbe9046..579bdfa98 100644--- a/tests/agent_core/tools/test_jobs.py+++ b/tests/agent_core/tools/test_jobs.py@@ -295,6 +295,51 @@ async def test_the_deadline_holds_after_the_command_closes_its_output(tmp_path):assert restarted.stop_reason(job_id) == "timeout"+async def test_a_kill_whose_reason_cannot_be_recorded_still_stops_the_command(tmp_path, monkeypatch):+ """Recording why is best effort at every stopper: a full disk must not leave the command running."""+ host = LocalJobHost(str(tmp_path / "jobs"))+ job_id = await _start(host, tmp_path, f"echo $$ > {tmp_path / 'sh.pid'}; sleep 30")+ assert _wait_until(lambda: (tmp_path / "sh.pid").exists())+ shell_pid = int((tmp_path / "sh.pid").read_text())+ real_create = host._create_once++ def full_disk(job_id, name, value):+ if name == "stopped":+ raise OSError(errno.ENOSPC, "No space left on device")+ return real_create(job_id, name, value)++ monkeypatch.setattr(host, "_create_once", full_disk)+ try:+ await host.kill(job_id, reason="aborted")+ stopped = _wait_until(+ lambda: not psutil.pid_exists(shell_pid) or psutil.Process(shell_pid).status() == psutil.STATUS_ZOMBIE+ )+ finally:+ monkeypatch.undo()+ await host.kill(job_id)++ assert stopped+ assert host.stop_reason(job_id) is None+++def test_a_shell_that_exited_by_the_deadline_check_is_not_a_timeout(tmp_path, monkeypatch):+ """The wrapper alone decides timeout versus exit, and it looks at the shell before the clock."""+ import core.agent_core.tools.job_wrapper as wrapper++ stops = []+ monkeypatch.setattr(wrapper, "_stop_group", lambda job_dir, reason, proc: stops.append(reason))+ proc = subprocess.Popen(["/bin/sh", "-c", "exit 3"], stdout=subprocess.PIPE)+ proc.wait() # it exited before the deadline was checked+ log = wrapper._BoundedLog(str(tmp_path), 1024, 1024)+ try:+ wrapper._run(str(tmp_path), proc, log, time.time() - 1)+ finally:+ proc.stdout.close()++ assert stops == []+ assert (tmp_path / "exit").read_text() == "3\n"++def test_the_wrapper_stops_its_group_even_when_its_diagnostics_fail(tmp_path, monkeypatch):"""The wrapper's own failure handler must stop the command even if writing the traceback fails (ENOSPC)."""import core.agent_core.tools.job_wrapper as wrapperdiff --git a/tests/agent_core/tools/test_write_edit.py b/tests/agent_core/tools/test_write_edit.pyindex fdc2a84f5..197e11f5a 100644--- a/tests/agent_core/tools/test_write_edit.py+++ b/tests/agent_core/tools/test_write_edit.py@@ -233,6 +233,44 @@ async def test_a_cancelled_write_lands_before_the_next_writer_takes_the_lock(assert (tmp_path / "f.txt").read_text() == "second\n"[email protected]("change", ["replaced", "retargeted", "rewritten", "rewritten-in-place"])+async def test_an_edit_publishes_only_over_the_file_it_read(tmp_path, make_ctx, monkeypatch, change):+ """Another writer (bash, an editor) changed the file after edit read it: nothing is written over it."""+ (tmp_path / "d").mkdir()+ real, other, link = tmp_path / "d" / "a.txt", tmp_path / "d" / "b.txt", tmp_path / "d" / "f.txt"+ real.write_text("alpha\n")+ other.write_text("other\n")+ link.symlink_to(real)+ real_plan = edit_module._plan_edits++ def plan_then_change(*args):+ planned = real_plan(*args)+ if change == "replaced":+ (tmp_path / "d" / "new").write_text("unrelated text\n")+ os.replace(tmp_path / "d" / "new", real)+ elif change == "retargeted":+ link.unlink()+ link.symlink_to(other)+ else:+ real.write_text("unrelated text\n")+ return planned++ monkeypatch.setattr(edit_module, "_plan_edits", plan_then_change)+ if change == "rewritten-in-place":+ (tmp_path / "d").chmod(0o555) # no temp file can be created beside it+ try:+ result = await _edit(make_ctx, "d/f.txt", {"oldText": "alpha", "newText": "beta"})+ finally:+ (tmp_path / "d").chmod(0o755)++ assert (result.is_error, result_text(result)) == (+ True,+ "Could not edit file: d/f.txt. It changed while the edit was being applied; read it again.",+ )+ expected = {"retargeted": ("alpha\n", "other\n")}.get(change, ("unrelated text\n", "other\n"))+ assert (real.read_text(), other.read_text()) == expected++async def test_new_files_keep_the_umask_default(tmp_path, make_ctx):umask = os.umask(0)os.umask(umask)@@ -559,10 +597,20 @@ async def test_a_path_no_file_can_have_is_an_error_result(make_ctx, tool, argumeassert result_text(result) == f"Invalid path: {arguments['path']!r} contains a NUL byte"+# Expected values are Node's fileURLToPath (WHATWG URL parsing), which Pi uses.@pytest.mark.parametrize(("windows", "url", "expected"),[(False, "file:///tmp/a%20b.txt", "/tmp/a b.txt"),+ # The WHATWG URL parser's steps: a backslash is a separator, C0 controls and spaces at the ends go.+ (False, "file:///tmp\\x", "/tmp/x"),+ (False, "file:///tmp/a ", "/tmp/a"),+ (False, "file:///tmp/a\x1f \x00", "/tmp/a"),+ (False, "file:///tmp/a%20", "/tmp/a "),+ (True, "file:///C:\\tmp\\x", "C:\\tmp\\x"),+ (True, "file://localhost\\C:\\x", "C:\\x"),+ # Pi's gate is case-sensitive: this is a relative path in Pi too.+ (False, "FILE:///tmp/a", "FILE:///tmp/a"),(False, "file://localhost/tmp/x", "/tmp/x"),(False, "file://server/tmp/x", ToolInputError("Invalid path: file URL host must be empty or localhost")),(False, "file:///tmp/a%2Fb", ToolInputError("Invalid path: a file URL must not include encoded / characters")),