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.

Vibey: register each generated image its row commits, and sweep the media files no row registers (#2596)

Call White030c87901eff
diff --git a/docs/plans/vibey-hosted-tools.md b/docs/plans/vibey-hosted-tools.md
index 33ed420d4..6a05af182 100644
--- a/docs/plans/vibey-hosted-tools.md
+++ b/docs/plans/vibey-hosted-tools.md
@@ -605,10 +605,18 @@ Each has a **Re-verify** action with its cost. Unknown shows nothing.
still over the cap gets a record saying it is too large to view inline.
- Known limitation: no transparent backgrounds in Phase 1. A later per-call format choice (an
`output_format`/`background` argument on the tool) restores them.
- - Known limitation (orchestrator decision, 2026-10-14): a file is saved before the row that names it commits. A
- cancel, crash or kill in between leaves a file no row references. Such files are content-addressed, so they never
- duplicate, and the per-response image budget bounds them. A startup sweep of the agent media root removes them
- (#2588, before the 3.2.1 RC).
+ - A file is saved before the row that names it commits, and a cancel, crash or kill in between leaves a file no
+ row references (orchestrator decision, 2026-10-14). One owner covers every such window (#2588):
+ - the committed row registers each image it names in `media_objects`, in its own transaction, as an input
+ snapshot is registered;
+ - once per process, off the loop, Vibey's first recovery pass sweeps the agent media root;
+ - the sweep removes a content-addressed file that no row registers, and a leftover temporary file, once either is
+ older than 24 hours, longer than any Turn holds an uncommitted save;
+ - each file costs one indexed lookup, and links and foreign names are never touched;
+ - a save that reuses an old file makes it new again, so the sweep never takes a file a save is about to register.
+
+ Generated images that pre-release builds committed without registering them are not kept (owner directive: no
+ compatibility for pre-release states).
- Avibe-authored failure reasons in a record's `error` are English model-facing text. Each carries a stable
`error_code` (C-1 `HostedRecord.error_code`, one of `HOSTED_ERROR_CODES`), by which the display boundary localizes
it; a provider's own reason carries none and shows as it is (#2589).
diff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.py
index ce1b57ca0..fe8820161 100644
--- a/modules/agents/vibey/agent.py
+++ b/modules/agents/vibey/agent.py
@@ -262,6 +262,7 @@ class VibeyAgent(BaseAgent):
# J5 while the service runs: when the jobs directory was last pruned, and the pass in flight.
self._pruned_at: Optional[float] = None
self._prune_task: Optional[asyncio.Task] = None
+ self._media_sweep: Optional[asyncio.Task] = None
# --- BaseAgent -----------------------------------------------------------
@@ -418,8 +419,11 @@ class VibeyAgent(BaseAgent):
Sessions with accepted inputs no run consumed. Each runs the same resume a Turn
runs (T2 and T3, no model call). A Session a run holds is skipped: its own resume
settles it. J5 pruning follows a pass that settled everything. Never reports
- success over a failure; ``VibeyRecovery`` owns the retries.
+ success over a failure; ``VibeyRecovery`` owns the retries. The first pass of the
+ process also starts the media sweep.
"""
+ if self._media_sweep is None:
+ self._media_sweep = asyncio.create_task(self._sweep_media(), name="vibey-agent-media-sweep")
candidates = await asyncio.to_thread(self._recovery_candidates)
unsettled: list[str] = []
for session_id in candidates:
@@ -464,6 +468,16 @@ class VibeyAgent(BaseAgent):
except Exception:
logger.exception("Vibey job pruning failed")
+ async def _sweep_media(self) -> None:
+ """Remove the media files no row registers, once per process, off the loop (``MediaSnapshots.sweep``)."""
+ try:
+ removed, freed = await asyncio.to_thread(self.media.sweep)
+ except Exception:
+ logger.exception("Vibey media sweep failed")
+ return
+ if removed:
+ logger.info("Vibey removed %d unregistered media file(s), %d bytes", removed, freed)
+
def _job_call_settled(self, meta: Any) -> bool:
"""Whether the job's call instance has a durable ``tool_result`` row (the adapter's half of J5).
diff --git a/modules/agents/vibey/media.py b/modules/agents/vibey/media.py
index 120a6b5e5..622d7fa55 100644
--- a/modules/agents/vibey/media.py
+++ b/modules/agents/vibey/media.py
@@ -6,6 +6,12 @@ context - an input attachment or a file ``read`` attaches - is first copied to a
content-addressed file ``<state>/agent_core/media/<sha256>.<ext>`` and registered
there, so a later edit or deletion of the original file cannot change what a
transcript replays. Loading re-checks the digest.
+
+A generated image is saved to the same root before the row that names it
+commits, and that row registers it (``storage.agent_transcript``). A file no row
+registers is left by an interruption in between; ``sweep`` removes it once it is
+older than any Turn holds a save it has not committed (``vibey-hosted-tools.md``
+§7.3).
"""
from __future__ import annotations
@@ -15,8 +21,11 @@ import base64
import binascii
import hashlib
import os
+import re
import secrets
import stat
+import threading
+import time
from pathlib import Path
from typing import Optional
@@ -28,8 +37,15 @@ from core.agent_core.tools.read import detect_supported_image_mime_type
from storage import media_service
from storage.models import agent_sessions
-MEDIA_SOURCE = "agent_context"
_EXTENSIONS = {"image/png": "png", "image/jpeg": "jpg", "image/gif": "gif", "image/webp": "webp"}
+#: How old a file no row registers must be before ``sweep`` removes it: longer than any Turn holds a save it has not
+#: committed. A file in use is kept younger than half of it (``_store``).
+SWEEP_GRACE_S = 24 * 3600.0
+_STORED_NAME = re.compile(r"[0-9a-f]{64}\.(?:png|jpg|gif|webp)")
+_TEMP_NAME = re.compile(r"\.[0-9a-f]{64}\.[0-9a-f]{8}\.tmp")
+#: Orders a save's reuse of a file against the sweep's last look at it and its removal, in this process, the only one
+#: that writes the root.
+_ROOT_LOCK = threading.Lock()
class MediaUnavailable(RuntimeError):
@@ -104,11 +120,20 @@ class MediaSnapshots:
"""The content-addressed file holding ``data``. An entry already at that name is reused only while it is a
regular file that still holds those bytes: history reads these paths directly, and their owner can change
them. Anything else is replaced by one atomic rename, which never follows the entry it replaces, so nothing is
- repaired in place and a link's target is never touched."""
+ repaired in place and a link's target is never touched. A reused file older than half the sweep's grace is
+ made new again, under the lock the sweep removes a file under, so ``sweep`` never takes a file a save is about
+ to register."""
+ with _ROOT_LOCK:
+ return self._store_locked(data, mime_type)
+
+ def _store_locked(self, data: bytes, mime_type: str) -> Path:
digest = hashlib.sha256(data).hexdigest()
path = self._root / f"{digest}.{_EXTENSIONS[mime_type]}"
try:
- if stat.S_ISREG(os.lstat(path).st_mode) and hashlib.sha256(path.read_bytes()).hexdigest() == digest:
+ info = os.lstat(path)
+ if stat.S_ISREG(info.st_mode) and hashlib.sha256(path.read_bytes()).hexdigest() == digest:
+ if info.st_mtime < time.time() - SWEEP_GRACE_S / 2:
+ os.utime(path, follow_symlinks=False)
return path
except OSError:
pass # missing or unreadable: written below
@@ -122,6 +147,56 @@ class MediaSnapshots:
raise
return path
+ # --- sweep -----------------------------------------------------------------
+
+ def sweep(self, grace_s: float = SWEEP_GRACE_S) -> tuple[int, int]:
+ """Remove each file of the root that no ``media_objects`` row registers and that is older than ``grace_s``,
+ and each leftover temporary file that old; return how many files and bytes went (#2588). Run off the loop.
+
+ Only the root's own names are considered, and only regular files: a link, a directory, or a file someone else
+ put there is never touched. Each file is checked with one indexed lookup, under both its path and its resolved
+ path, the two forms a row registers.
+ """
+
+ cutoff = time.time() - grace_s
+ removed = freed = 0
+ try:
+ entries = list(os.scandir(self._root))
+ except FileNotFoundError:
+ return 0, 0
+ with self._engine.connect() as conn:
+ for entry in entries:
+ temporary = _TEMP_NAME.fullmatch(entry.name) is not None
+ if not temporary and not _STORED_NAME.fullmatch(entry.name):
+ continue
+ path = Path(entry.path)
+ if self._stale(path, cutoff) is None:
+ continue
+ if not temporary and media_service.is_registered_path(conn, {str(path), str(path.resolve())}):
+ continue
+ # Looked at again as it goes, under the lock a save reuses a file under: one that reused it since has
+ # made it new (``_store``).
+ with _ROOT_LOCK:
+ size = self._stale(path, cutoff)
+ if size is None:
+ continue
+ try:
+ path.unlink()
+ except FileNotFoundError:
+ continue
+ removed, freed = removed + 1, freed + size
+ return removed, freed
+
+ @staticmethod
+ def _stale(path: Path, cutoff: float) -> Optional[int]:
+ """The size of ``path`` when it is a regular file last written before ``cutoff``, else None."""
+
+ try:
+ info = os.lstat(path)
+ except OSError:
+ return None
+ return info.st_size if stat.S_ISREG(info.st_mode) and info.st_mtime < cutoff else None
+
def _snapshot(self, data: bytes, mime_type: str, session_id: str, name: Optional[str]) -> str:
if mime_type not in IMAGE_MIME_TYPES:
raise ValueError(f"unsupported image type: {mime_type}")
@@ -135,7 +210,7 @@ class MediaSnapshots:
scope_id=scope_id,
session_id=session_id,
kind="image",
- source=MEDIA_SOURCE,
+ source=media_service.AGENT_CONTEXT_SOURCE,
local_path=str(path),
file_name=name or path.name,
content_type=mime_type,
diff --git a/storage/agent_transcript.py b/storage/agent_transcript.py
index 6a5cb7722..ccd05b4df 100644
--- a/storage/agent_transcript.py
+++ b/storage/agent_transcript.py
@@ -50,6 +50,11 @@ it, exactly as for the other backends' rows (``persist_agent_message`` with
changes after commit. A final whose ``final_outcome`` failed commits as
``error``.
+Generated images. A committed row that names a generated image (a hosted
+record's ``images``) registers each file in ``media_objects`` in its own
+transaction, as an input snapshot is registered: the media sweep keeps exactly
+the files some row registers (``vibey-hosted-tools.md`` §7.3).
+
Cancellation. A worker thread cannot be interrupted, so a cancelled write keeps
the Session's lock until its transaction settles and only then raises: when a
write call returns or raises, the rows already show whether it committed.
@@ -71,6 +76,7 @@ from core.agent_core.harness.projection import open_tool_calls
from core.agent_core.harness.store import ContextEntry, EntryKind
from core.agent_core.messages import (
AssistantMessage,
+ HostedToolBlock,
TextBlock,
ToolResultMessage,
has_reply,
@@ -79,7 +85,7 @@ from core.agent_core.messages import (
message_to_dict,
require_json_value,
)
-from storage import agent_events_service, messages_service
+from storage import agent_events_service, media_service, messages_service
from storage.agent_session_rows import reserve_write_lock
from storage.message_deliveries import TURN_OWNER_STATES
from storage.models import agent_events, agent_sessions, message_deliveries, messages, scopes, session_turns
@@ -249,6 +255,7 @@ class SQLiteTranscriptStore:
content={"model": model},
)
conn.execute(messages.update().where(messages.c.id == row["id"]).values(context_seq=seq))
+ _register_images(conn, origin.scope_id, session_id, message)
return ContextEntry(
session_id, seq, "response", row["id"], message=message, payload=model, created_at=_epoch(row["created_at"])
)
@@ -370,6 +377,8 @@ class SQLiteTranscriptStore:
source="agent",
context_seq=seq,
)
+ if message is not None:
+ _register_images(conn, origin.scope_id, session_id, message)
return ContextEntry(
session_id, seq, kind, row["id"], message=message, payload=payload, created_at=_epoch(row["created_at"])
)
@@ -397,6 +406,27 @@ async def _settle(task: asyncio.Future[Any]) -> None:
# --- allocation and attribution ----------------------------------------------
+def _register_images(
+ conn: Connection, scope_id: Optional[str], session_id: str, message: AssistantMessage | ToolResultMessage
+) -> None:
+ """Register each generated image ``message`` names, in its row's transaction (module docstring)."""
+
+ if isinstance(message, AssistantMessage):
+ records = [block.record for block in message.content if isinstance(block, HostedToolBlock)]
+ else:
+ records = [message.hosted.record] if message.hosted is not None else []
+ for image in (image for record in records for image in record.images or ()):
+ media_service.register(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ kind="image",
+ source=media_service.AGENT_CONTEXT_SOURCE,
+ local_path=image.path,
+ content_type=image.mime,
+ )
+
+
def _own_bound(conn: Connection, session_id: str) -> Optional[int]:
values = [
conn.execute(
diff --git a/storage/media_service.py b/storage/media_service.py
index f4b686a64..95ce3d59b 100644
--- a/storage/media_service.py
+++ b/storage/media_service.py
@@ -14,7 +14,7 @@ import mimetypes
import secrets
from datetime import datetime, timezone
from pathlib import Path
-from typing import Any, Optional
+from typing import Any, Iterable, Optional
from sqlalchemy import select
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
@@ -25,6 +25,10 @@ from storage.models import media_object_references, media_objects
logger = logging.getLogger(__name__)
+#: The ``source`` of a file in the agent's context: an input snapshot, or a generated image a committed transcript row
+#: names. The agent media sweep keeps exactly the files some row registers.
+AGENT_CONTEXT_SOURCE = "agent_context"
+
def _utc_now_iso() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
@@ -182,6 +186,16 @@ def register(
return token
+def is_registered_path(conn: Connection, local_paths: Iterable[str]) -> bool:
+ """Whether any row, live or revoked, registers one of ``local_paths``: one lookup on the ``local_path`` prefix of
+ ``ix_media_objects_dedup``."""
+
+ paths = list(local_paths)
+ return bool(paths) and conn.execute(
+ select(media_objects.c.token).where(media_objects.c.local_path.in_(paths)).limit(1)
+ ).first() is not None
+
+
def get_by_token(conn: Connection, token: str) -> Optional[dict[str, Any]]:
"""Return the media row for *token* as a plain dict, or ``None``."""
if not token:
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index c2d280b3c..9da724c14 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -375,6 +375,7 @@ scenarios:
- tests/agent_core/ai/test_hosted_images.py::test_a_response_that_streams_images_past_its_budget_ends_as_an_error
- tests/test_vibey_agent.py::test_a_generated_image_is_kept_as_an_immutable_file_its_bytes_name_and_type
- tests/test_vibey_agent.py::test_a_proxied_image_that_was_not_saved_is_a_failed_call_with_its_code
+ - tests/test_agent_transcript.py::test_the_media_sweep_keeps_every_file_a_row_registers_and_takes_only_stale_orphans
- id: MH-VIBEY-007
name: Vibey starts once with the user's Sources and built-in Agent models, seeded when its first Source exists
status: covered
diff --git a/tests/test_agent_transcript.py b/tests/test_agent_transcript.py
index 0b6a123ee..d638ebc78 100644
--- a/tests/test_agent_transcript.py
+++ b/tests/test_agent_transcript.py
@@ -489,3 +489,87 @@ async def test_a_call_instance_is_settled_once_whoever_writes(engine) -> None:
await store.append_response("ses_main", _assistant("again", call_id="call_1"), final=False)
later = await store.append_tool_result("ses_main", _tool_result("call_1", "second call"), details={})
assert later.row_id != first.row_id
+
+
+async def test_the_media_sweep_keeps_every_file_a_row_registers_and_takes_only_stale_orphans(engine, tmp_path) -> None:
+ """MH-HOSTED-VIBEY-007, #2588 (``vibey-hosted-tools.md`` §7.3): a generated image is saved before the row that
+ names it commits, so an interruption in between leaves a file no row names. A committed row registers each image
+ it names, native or proxied, as an input snapshot is registered; the sweep removes only a file nothing registers
+ that is older than any Turn holds an uncommitted save, and never a link or a name of someone else's."""
+ import base64
+ import os
+ import time
+ from pathlib import Path
+
+ from core.agent_core.messages import (
+ HostedAction,
+ HostedNative,
+ HostedRecord,
+ HostedResult,
+ HostedSummary,
+ HostedToolBlock,
+ ProxyExecution,
+ )
+ from modules.agents.vibey.media import SWEEP_GRACE_S, MediaSnapshots
+
+ with engine.begin() as conn:
+ home = _scope(conn, "C-home")
+ _session(conn, "ses_main", home)
+ first = _accepted_turn(conn, "ses_main", home, "paint two lighthouses", "turn_main")
+ store = SQLiteTranscriptStore(engine)
+ root = tmp_path / "media"
+ media = MediaSnapshots(engine, root)
+
+ def jpeg(n: int) -> str:
+ return base64.b64encode(b"\xff\xd8\xff\xe0" + bytes([n]) * 512).decode()
+
+ await store.consume_input("ses_main", first, _user("paint two lighthouses"))
+ await media.snapshot(b"\x89PNG\r\n\x1a\n" + bytes(64), "image/png", session_id="ses_main")
+ native, proxied = await media.save_image(jpeg(1)), await media.save_image(jpeg(2))
+ call = HostedToolBlock(
+ id="ig_1",
+ tool="image_generation",
+ action=HostedAction("generate", prompt="a lighthouse"),
+ record=HostedRecord(status="completed", images=(native,)),
+ native=HostedNative(source_id="src_served00001", payload=({"type": "image_generation_call", "result": native.path},)),
+ )
+ summary = HostedSummary(counts={}, cited_sources=())
+ await store.append_response(
+ "ses_main", AssistantMessage((call,), ORIGIN, "stop", hosted_summary=summary), final=False
+ )
+ execution = ProxyExecution(executor_origin=ORIGIN, executor_source_id="src_executor01", executor_billing="metered")
+ await store.append_tool_result(
+ "ses_main",
+ ToolResultMessage(
+ tool_call_id="call_2",
+ tool_name="image_generation",
+ content=(text("[image saved]"),),
+ hosted=HostedResult(record=HostedRecord(status="completed", images=(proxied,)), execution=execution),
+ ),
+ details={},
+ )
+ fresh, stale, reused = [await media.save_image(jpeg(n)) for n in (3, 4, 5)]
+ temporary = root / f".{'a' * 64}.0123abcd.tmp"
+ temporary.write_bytes(b"half written")
+ foreign = root / "notes.txt"
+ foreign.write_text("not the sweep's")
+ secret = tmp_path / "secret.key"
+ secret.write_bytes(b"key")
+ link = root / f"{'b' * 64}.png"
+ link.symlink_to(secret)
+ old = time.time() - SWEEP_GRACE_S - 60
+ for entry in root.iterdir():
+ if entry.name != Path(fresh.path).name:
+ os.utime(entry, (old, old), follow_symlinks=False)
+ # A save that reuses an old file makes it new again, so the sweep never takes it before its row commits.
+ assert await media.save_image(jpeg(5)) == reused
+
+ gone = Path(stale.path).stat().st_size + temporary.stat().st_size
+
+ assert media.sweep() == (2, gone)
+ kept = {entry.name for entry in root.iterdir()}
+ assert Path(stale.path).name not in kept and temporary.name not in kept
+ assert {Path(image.path).name for image in (native, proxied, fresh, reused)} <= kept
+ assert {foreign.name, link.name} <= kept and secret.read_bytes() == b"key"
+ assert len([name for name in kept if name.endswith(".png")]) == 2 # the input snapshot and the link
+