Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(agent-core): recorded stop reasons, Node file URLs, edit size limit

cyhccfe76d29c0b
diff --git a/core/agent_core/tools/bash.py b/core/agent_core/tools/bash.py
index 10246c8eb..258e98089 100644
--- a/core/agent_core/tools/bash.py
+++ b/core/agent_core/tools/bash.py
@@ -27,7 +27,7 @@ from core.agent_core.tools.args import (
text_result,
)
from core.agent_core.tools.base import MAX_BYTES, MAX_LINES, JobHost, JobStatus, ToolContext, ToolResult, ToolSpec
-from core.agent_core.tools.jobs import STOP_TIMEOUT, JobStartError, LocalJobHost
+from core.agent_core.tools.jobs import STOP_ABORTED, STOP_TIMEOUT, JobStartError, LocalJobHost
from core.agent_core.tools.output import JobOutput
logger = logging.getLogger(__name__)
@@ -35,8 +35,6 @@ logger = logging.getLogger(__name__)
DEFAULT_FOREGROUND_WINDOW_S = 120.0
_MAX_TIMEOUT_S = 2_147_483.647
_PROGRESS_INTERVAL_S = 0.1 # Pi's BASH_UPDATE_THROTTLE_MS
-# A job found gone this close to its timeout was killed for it, by this tool or by the job host.
-_DEADLINE_SLACK_S = 1.0
_WATCH_GRACE_S = 0.5
BASH_SCHEMA: Mapping[str, Any] = {
@@ -106,6 +104,15 @@ def _timed_out_line(timeout_s: float) -> str:
return f"Command timed out after {format_number(timeout_s)} seconds"
+def _stopped_line(reason: Optional[str], timeout_s: Optional[float]) -> Optional[str]:
+ """Pi's status line for a job someone stopped, from the reason recorded when it was stopped."""
+ if reason == STOP_TIMEOUT and timeout_s is not None:
+ return _timed_out_line(timeout_s)
+ if reason == STOP_ABORTED:
+ return "Command aborted"
+ return None
+
+
def handover_result(output: JobOutput, watch_id: str) -> ToolResult:
"""Avibe: the command keeps running as a Watch; the model sees the output so far and how to manage it."""
output.poll()
@@ -126,10 +133,10 @@ def handover_result(output: JobOutput, watch_id: str) -> ToolResult:
async def settle_bash_call(jobs: LocalJobHost, session_id: str, tool_call_id: str) -> Optional[ToolResult]:
"""The durable result for a ``bash`` call left open by a crash (``recovery.md``).
- A finished job gets its final output, a job killed at its deadline gets the
- timeout result, and a running one is handed to Watch. ``None`` means the job
- is gone, never ran, or does not exist: the caller commits the synthetic
- interrupted result.
+ A finished job gets its final output, a job stopped at its deadline or by an
+ abort gets that result, and a running one is handed to Watch. ``None`` means
+ the job is gone for another reason, never ran, or does not exist: the caller
+ commits the synthetic interrupted result.
"""
job_id = jobs.find_job(session_id, tool_call_id)
if job_id is None:
@@ -140,10 +147,8 @@ async def settle_bash_call(jobs: LocalJobHost, session_id: str, tool_call_id: st
return handover_result(JobOutput(jobs, job_id), await jobs.hand_over(job_id))
if status.state == "exited":
return final_result(JobOutput(jobs, job_id), status)
- timeout_s = jobs.meta(job_id).get("timeout_s")
- if jobs.stop_reason(job_id) == STOP_TIMEOUT and timeout_s is not None:
- return stopped_result(JobOutput(jobs, job_id), _timed_out_line(timeout_s))
- return None
+ line = _stopped_line(jobs.stop_reason(job_id), jobs.meta(job_id).get("timeout_s"))
+ return stopped_result(JobOutput(jobs, job_id), line) if line else None
class BashTool:
@@ -206,20 +211,21 @@ class BashTool:
slice_s = min(slice_s, max(0.0, handover_at - elapsed))
status = await self._wait_or_cancel(job_id, slice_s, ctx.cancel)
- if status is not None and status.state == "gone" and timeout is not None:
- # Whoever holds the job enforces its deadline; the host may have killed it first.
- if time.monotonic() - started >= timeout - _DEADLINE_SLACK_S:
- return stopped_result(output, _timed_out_line(timeout))
+ if status is not None and status.state == "gone":
+ # Whoever stopped the job recorded why; the job host or its wrapper may have stopped it first.
+ line = _stopped_line(self._jobs.stop_reason(job_id), timeout)
+ if line:
+ return stopped_result(output, line)
if status is not None and status.state != "running":
note = None
if watch and handover_error is not None:
note = f"[Watch unavailable ({handover_error}); the command ran in the foreground.]"
return final_result(output, status, note=note)
if ctx.cancel.cancelled:
- await self._jobs.kill(job_id)
+ 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)
+ await self._jobs.kill(job_id, reason=STOP_TIMEOUT)
return stopped_result(output, _timed_out_line(timeout))
if hand_over:
try:
diff --git a/core/agent_core/tools/edit.py b/core/agent_core/tools/edit.py
index c74245df6..adbed37de 100644
--- a/core/agent_core/tools/edit.py
+++ b/core/agent_core/tools/edit.py
@@ -19,9 +19,13 @@ from core.agent_core.tools.args import ToolInputError, error_result, os_error_te
from core.agent_core.tools.base import ToolContext, ToolResult, ToolSpec
from core.agent_core.tools.edit_diff import Edit, EditError, apply_edits, generate_diff_string, generate_unified_patch
from core.agent_core.tools.paths import file_mutation_lock, resolve_to_cwd
+from core.agent_core.tools.truncate import format_size
from core.agent_core.tools.write import write_bytes
_SURROGATE = re.compile("[\ud800-\udfff]")
+#: Avibe: larger files are refused rather than loaded whole; the display diff stops at a smaller size.
+MAX_EDIT_BYTES = 10 * 1024 * 1024
+MAX_DIFF_BYTES = 1024 * 1024
EDIT_DESCRIPTION = (
"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping "
@@ -149,6 +153,13 @@ class EditTool:
code = errno.errorcode.get(errno.ENOENT if not os.path.exists(absolute) else errno.EACCES, "EACCES")
return error_result(f"Could not edit file: {path}. Error code: {code}.")
try:
+ size = os.path.getsize(absolute)
+ if size > MAX_EDIT_BYTES:
+ # The whole file and several copies would sit in the process every Session shares.
+ return error_result(
+ f"File {path} is {format_size(size)}, over the {format_size(MAX_EDIT_BYTES)} edit limit. "
+ "Use bash (for example sed or a short script) to change files this large."
+ )
data, base, new_content = await asyncio.to_thread(_plan_edits, absolute, edits, path)
if ctx.cancel.cancelled:
return error_result("Operation aborted")
@@ -158,12 +169,10 @@ class EditTool:
except OSError as exc:
return error_result(os_error_text(exc))
- diff, first_changed_line = generate_diff_string(base, new_content)
- return text_result(
- f"Successfully replaced {len(edits)} block(s) in {path}.",
- details={
- "diff": diff,
- "patch": generate_unified_patch(path, base, new_content),
- "first_changed_line": first_changed_line,
- },
- )
+ result = f"Successfully replaced {len(edits)} block(s) in {path}."
+ if size > MAX_DIFF_BYTES:
+ # The diff is for display only, and difflib is superlinear on large inputs.
+ return text_result(result, details={"diff_skipped": True})
+ diff, first_changed_line = await asyncio.to_thread(generate_diff_string, base, new_content)
+ patch = await asyncio.to_thread(generate_unified_patch, path, base, new_content)
+ return text_result(result, details={"diff": diff, "patch": patch, "first_changed_line": first_changed_line})
diff --git a/core/agent_core/tools/jobs.py b/core/agent_core/tools/jobs.py
index 75bad0bae..0b37aa486 100644
--- a/core/agent_core/tools/jobs.py
+++ b/core/agent_core/tools/jobs.py
@@ -82,6 +82,7 @@ OUTPUT_CHUNK_BYTES = 1024 * 1024
FINISHED_JOB_RETENTION_S = 7 * 24 * 3600
STOP_TIMEOUT = "timeout"
+STOP_ABORTED = "aborted"
_WRAPPER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "job_wrapper.py")
_JOB_ID = re.compile(r"^job_[a-z0-9]+$")
@@ -301,7 +302,7 @@ class LocalJobHost:
finally:
os.close(diagnostics)
self._children[job_id] = proc
- threading.Thread(target=proc.wait, name=f"avibe-{job_id}-reaper", daemon=True).start()
+ threading.Thread(target=self._reap, args=(job_id, proc), name=f"avibe-{job_id}-reaper", daemon=True).start()
identity = await self._await_pid(job_id, proc, marker)
if identity is not None:
@@ -334,7 +335,6 @@ class LocalJobHost:
def status(self, job_id: str) -> JobStatus:
exit_code = self._exit_code(job_id)
if exit_code is not None:
- self._reap(job_id)
return JobStatus("exited", exit_code)
if self._decision(job_id) != _GO:
return JobStatus("gone")
@@ -342,7 +342,6 @@ class LocalJobHost:
return JobStatus("running")
# The wrapper writes `exit` before it exits, so look once more.
exit_code = self._exit_code(job_id)
- self._reap(job_id)
return JobStatus("exited", exit_code) if exit_code is not None else JobStatus("gone")
async def wait(self, job_id: str, *, deadline_s: Optional[float]) -> JobStatus:
@@ -411,7 +410,6 @@ class LocalJobHost:
_write_atomic(self._path(job_id, "stopped"), f"{reason}\n")
if not await asyncio.to_thread(_terminate_group, identity.pid):
logger.warning("Job %s process group %s survived termination", job_id, identity.pid)
- self._reap(job_id)
async def hand_over(self, job_id: str) -> str:
"""Give the job to its Watch: adopt-or-create through ``on_hand_over``, then record the id (J6)."""
@@ -499,9 +497,10 @@ class LocalJobHost:
def _group_carries_marker(self, identity: PersistedProcessIdentity) -> bool:
return process_group_identity_status(identity.pid, identity, logger, "agent job") == "match"
- def _reap(self, job_id: str) -> None:
- child = self._children.get(job_id)
- if child is not None and child.returncode is not None:
+ def _reap(self, job_id: str, proc: subprocess.Popen) -> None:
+ """The reaper thread: wait for the wrapper, then drop it from the registry."""
+ proc.wait()
+ if self._children.get(job_id) is proc:
del self._children[job_id]
diff --git a/core/agent_core/tools/paths.py b/core/agent_core/tools/paths.py
index bec97fcac..44d5db038 100644
--- a/core/agent_core/tools/paths.py
+++ b/core/agent_core/tools/paths.py
@@ -8,7 +8,6 @@ Mario Zechner).
from __future__ import annotations
import asyncio
-import nturl2path
import os
import re
import unicodedata
@@ -22,6 +21,8 @@ _UNICODE_SPACES = re.compile("[\u00a0\u2000-\u200a\u202f\u205f\u3000]")
_NARROW_NO_BREAK_SPACE = "\u202f"
_AM_PM = re.compile(r" (AM|PM)\.", re.IGNORECASE)
_WINDOWS = os.name == "nt"
+_ENCODED_SEPARATOR = re.compile("%2f", re.IGNORECASE)
+_ENCODED_SEPARATOR_WINDOWS = re.compile("%2f|%5c", re.IGNORECASE)
def expand_path(path: str) -> str:
@@ -37,14 +38,28 @@ def expand_path(path: str) -> str:
def _file_url_to_path(url: str) -> str:
- """Like Node's ``fileURLToPath``: drive letters and UNC hosts on Windows, the path elsewhere."""
+ """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.
+ """
parsed = urlparse(url)
- if not _WINDOWS:
- return unquote(parsed.path)
- path = nturl2path.url2pathname(parsed.path)
- if parsed.netloc and parsed.netloc.lower() != "localhost":
- return f"\\\\{parsed.netloc}{path}"
- return path
+ host = "" if parsed.netloc.lower() == "localhost" else parsed.netloc
+ if _WINDOWS:
+ if _ENCODED_SEPARATOR_WINDOWS.search(parsed.path):
+ raise ToolInputError("Invalid path: a file URL must not include encoded \\ or / characters")
+ path = unquote(parsed.path).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:]
+ 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):
+ raise ToolInputError("Invalid path: a file URL must not include encoded / characters")
+ return unquote(parsed.path)
def resolve_to_cwd(path: str, cwd: str) -> str:
diff --git a/tests/agent_core/tools/test_bash.py b/tests/agent_core/tools/test_bash.py
index b5db2f3c3..f6f2a68e3 100644
--- a/tests/agent_core/tools/test_bash.py
+++ b/tests/agent_core/tools/test_bash.py
@@ -85,6 +85,28 @@ async def test_a_nul_byte_in_the_command_is_an_error_result(tmp_path, make_ctx):
assert result_text(result) == "Invalid command: contains a NUL byte"
+async def test_only_the_recorded_reason_makes_a_gone_job_a_timeout(tmp_path, make_ctx, monkeypatch):
+ """A wrapper failure inside a short timeout is reported as what it was, not as the timeout."""
+ monkeypatch.setattr(jobs_module, "OUTPUT_HEAD_BYTES", 10)
+ host = _host(tmp_path)
+ running = asyncio.ensure_future(
+ BashTool(host).execute({"command": "sleep 0.3; seq 1 1000; sleep 30", "timeout": 1.0}, make_ctx())
+ )
+ job_id = None
+ while job_id is None or not os.path.exists(os.path.join(host.job_dir(job_id), "pid")):
+ await asyncio.sleep(0.01)
+ job_id = job_id or host.find_job("ses_test", "toolu_1")
+ # The wrapper cannot write its tail snapshot once the head is full, as on a full disk.
+ wrapper_pid = open(os.path.join(host.job_dir(job_id), "pid")).read().strip()
+ os.mkdir(os.path.join(host.job_dir(job_id), f"tail.log.{wrapper_pid}.tmp"))
+
+ result = await asyncio.wait_for(running, timeout=10)
+
+ assert host.stop_reason(job_id) == "wrapper_error"
+ assert result.is_error
+ assert result_text(result).endswith("Command terminated without an exit code")
+
+
async def test_stdin_is_closed(tmp_path, make_ctx):
started = time.monotonic()
result = await BashTool(_host(tmp_path)).execute({"command": 'read x; echo "rc=$?"'}, make_ctx())
diff --git a/tests/agent_core/tools/test_jobs.py b/tests/agent_core/tools/test_jobs.py
index 27ed52edf..48d3f9ba8 100644
--- a/tests/agent_core/tools/test_jobs.py
+++ b/tests/agent_core/tools/test_jobs.py
@@ -235,6 +235,16 @@ async def test_a_wrapper_that_cannot_keep_the_log_stops_its_command(tmp_path, mo
)
+async def test_a_finished_wrapper_leaves_the_registry(tmp_path):
+ """The reaper drops the wrapper even when no status call comes after it exits."""
+ host = LocalJobHost(str(tmp_path / "jobs"))
+ # The shell exits at once; a background child keeps the pipe, so the wrapper outlives the exit.
+ job_id = await _start(host, tmp_path, "sleep 0.5 &")
+ assert (await host.wait(job_id, deadline_s=5)).state == "exited"
+
+ assert _wait_until(lambda: job_id not in host._children, timeout_s=5)
+
+
async def test_job_files_stay_until_the_call_is_settled(tmp_path):
"""J5."""
host = LocalJobHost(str(tmp_path / "jobs"))
diff --git a/tests/agent_core/tools/test_write_edit.py b/tests/agent_core/tools/test_write_edit.py
index ec898254c..5e39e0365 100644
--- a/tests/agent_core/tools/test_write_edit.py
+++ b/tests/agent_core/tools/test_write_edit.py
@@ -12,6 +12,8 @@ import pytest
import core.agent_core.tools.paths as paths_module
import core.agent_core.tools.write as write_module
+import core.agent_core.tools.edit as edit_module
+from core.agent_core.tools.args import ToolInputError
from core.agent_core.tools.edit import EditTool
from core.agent_core.tools.read import ReadTool
from core.agent_core.tools.write import WriteTool
@@ -98,6 +100,27 @@ async def test_replace_all_replaces_every_occurrence(tmp_path, make_ctx):
assert (tmp_path / "f.txt").read_text() == "baz(1)\nqux\nbaz(2)\nbaz(3)\n"
+async def test_files_over_the_edit_limit_are_refused_and_large_diffs_skipped(tmp_path, make_ctx, monkeypatch):
+ (tmp_path / "big.log").write_text("line\n" * 100)
+ monkeypatch.setattr(edit_module, "MAX_EDIT_BYTES", 400)
+
+ refused = await _edit(make_ctx, "big.log", {"oldText": "line", "newText": "x", "replaceAll": True})
+
+ assert refused.is_error
+ assert result_text(refused) == (
+ "File big.log is 500B, over the 400B edit limit. "
+ "Use bash (for example sed or a short script) to change files this large."
+ )
+ assert (tmp_path / "big.log").read_text() == "line\n" * 100
+
+ monkeypatch.setattr(edit_module, "MAX_EDIT_BYTES", 10_000)
+ monkeypatch.setattr(edit_module, "MAX_DIFF_BYTES", 400)
+ edited = await _edit(make_ctx, "big.log", {"oldText": "line", "newText": "x", "replaceAll": True})
+
+ assert not edited.is_error, result_text(edited)
+ assert edited.details == {"diff_skipped": True}
+
+
@pytest.mark.parametrize("ending", ["\r\n", "\r"])
async def test_bom_and_line_endings_are_preserved(tmp_path, make_ctx, ending):
(tmp_path / "f.txt").write_bytes(f"\ufeffone{ending}two{ending}three{ending}".encode())
@@ -285,10 +308,29 @@ async def test_a_path_no_file_can_have_is_an_error_result(make_ctx, tool, argume
@pytest.mark.parametrize(
- ("url", "path"),
- [("file:///C:/tmp/a%20b.txt", "C:\\tmp\\a b.txt"), ("file://server/share/x.txt", "\\\\server\\share\\x.txt")],
+ ("windows", "url", "expected"),
+ [
+ (False, "file:///tmp/a%20b.txt", "/tmp/a b.txt"),
+ (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")),
+ (True, "file:///C:/tmp/a%20b.txt", "C:\\tmp\\a b.txt"),
+ (True, "file://localhost/C:/x", "C:\\x"),
+ (True, "file://server/share/x.txt", "\\\\server\\share\\x.txt"),
+ (True, "file:///tmp/x", ToolInputError("Invalid path: a file URL must be absolute")),
+ (
+ True,
+ "file:///C:/a%5Cb",
+ ToolInputError("Invalid path: a file URL must not include encoded \\ or / characters"),
+ ),
+ ],
)
-def test_windows_file_urls_keep_drive_and_share(monkeypatch, url, path):
- monkeypatch.setattr(paths_module, "_WINDOWS", True)
-
- assert paths_module.expand_path(url) == path
+def test_file_urls_follow_node_file_url_to_path(monkeypatch, windows, url, expected):
+ monkeypatch.setattr(paths_module, "_WINDOWS", windows)
+
+ if isinstance(expected, ToolInputError):
+ with pytest.raises(ToolInputError) as raised:
+ paths_module.expand_path(url)
+ assert str(raised.value) == str(expected)
+ else:
+ assert paths_module.expand_path(url) == expected