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.

feat(agent-core): keep the exact bytes of failed Vibey model requests (#3103)

Call White0e813520dc1a
diff --git a/config/paths.py b/config/paths.py
index d16b62702..f76fe0ddf 100644
--- a/config/paths.py
+++ b/config/paths.py
@@ -130,6 +130,12 @@ def get_state_dir() -> Path:
return get_vibe_remote_dir() / "state"
+def get_model_request_artifacts_dir() -> Path:
+ """Where Vibey keeps the exact bytes of model requests that did not succeed (``request_artifacts``)."""
+
+ return get_state_dir() / "agent_core" / "model-requests"
+
+
def get_logs_dir() -> Path:
return get_vibe_remote_dir() / "logs"
diff --git a/core/agent_core/ai/_common.py b/core/agent_core/ai/_common.py
index c5e4b48c8..d787ab4e5 100644
--- a/core/agent_core/ai/_common.py
+++ b/core/agent_core/ai/_common.py
@@ -27,6 +27,13 @@ from core.agent_core.ai.errors import (
)
from core.agent_core.ai.hosted import MAX_HOSTED_COUNTERS
from core.agent_core.ai.image_limits import LoadedImage, fit_image
+from core.agent_core.ai.request_artifacts import (
+ ARTIFACT_WAIT_S,
+ RequestAttempt,
+ ResponseCapture,
+ begin_attempt,
+ note_slow_artifact_write,
+)
from core.agent_core.ai.sse import SSEEvent, SSEParseError, SSEParser
from core.agent_core.cancel import CancelToken
from core.agent_core.messages import (
@@ -1818,8 +1825,11 @@ def _header_value(value: str) -> bool:
async def iter_sse_events(
response: httpx.Response,
cancel: CancelToken,
+ *,
+ capture: ResponseCapture | None = None,
) -> AsyncIterator[SSEEvent]:
- """Yield SSE events while allowing a CancelToken to interrupt a stalled read."""
+ """Yield SSE events while allowing a CancelToken to interrupt a stalled read. ``capture`` receives the raw bytes
+ as they are read."""
parser = SSEParser()
iterator = response.aiter_bytes().__aiter__()
@@ -1833,9 +1843,13 @@ async def iter_sse_events(
timeout_s=PROVIDER_SILENCE_TIMEOUT_S,
)
except StopAsyncIteration:
+ if capture is not None:
+ capture.finish()
break
if chunk is None:
return
+ if capture is not None:
+ capture.feed(chunk)
for event in parser.feed(chunk):
yield event
for event in parser.finish():
@@ -1872,12 +1886,12 @@ async def drive_sse_stream(
opening: asyncio.Task[httpx.Response] | None = None
candidate: Done | ProviderError | None = None
sent_at: float | None = None
+ # The request's bytes, kept until it succeeds (``request_artifacts``), when a capture scope is active.
+ attempt: RequestAttempt | None = None
assembler.begin_driver()
try:
try:
- if cancel.cancelled:
- candidate = assembler.aborted(cancel.reason)
- else:
+ if not cancel.cancelled:
# The transport bounds only connecting; the wait for response
# headers is the provider's silence, bounded below, or the
# gateway's to bound (``PROVIDER_SILENCE_TIMEOUT_S``).
@@ -1888,6 +1902,25 @@ async def drive_sse_stream(
headers=headers,
timeout=httpx.Timeout(None, connect=CONNECT_TIMEOUT_S),
)
+ # Durable before it is sent: a crash mid-request leaves it pending, never a success. A Stop ends
+ # the wait at once and nothing is sent; a write that stalls past its bound is not waited for.
+ pending = begin_attempt(request, endpoint=endpoint, protocol=assembler.protocol)
+ if pending is not None:
+ try:
+ await _await_artifact(pending.written, cancel)
+ except asyncio.CancelledError:
+ pending.give_up(sent=False)
+ raise
+ attempt = pending.attempt()
+ if attempt is None:
+ pending.give_up(sent=not cancel.cancelled)
+ if cancel.cancelled:
+ # Stopped before the send, possibly while the pending write ran: nothing goes out.
+ if attempt is not None:
+ attempt.not_sent()
+ candidate = assembler.aborted(cancel.reason)
+ else:
+ capture = attempt.capture if attempt is not None else None
# Retain the opening task even if cancellation wins the await:
# its successful result still belongs to this driver's finally.
sent_at = time.monotonic()
@@ -1897,16 +1930,20 @@ async def drive_sse_stream(
cancel,
timeout_s=None if gateway else PROVIDER_SILENCE_TIMEOUT_S,
)
+ if response is not None and capture is not None:
+ capture.response(response.status_code, response.headers)
if response is None:
candidate = assembler.aborted(cancel.reason)
elif not 200 <= response.status_code < 300:
# HTTP errors already identify their outcome. Resolving a
# served hop first could mask auth/rate limits (or stall).
try:
- body = await read_response_body(response, cancel)
+ body = await read_response_body(response, cancel, capture=capture)
except (GeneratorExit, asyncio.CancelledError):
raise
except Exception as exc:
+ if attempt is not None:
+ attempt.exception_type = type(exc).__name__
candidate = assembler.exception(
exc,
status=response.status_code,
@@ -1923,6 +1960,10 @@ async def drive_sse_stream(
):
# The pinned Source cannot serve this content; nothing reached a model. The adapter
# decides what follows (§3.5, §4.3), so no terminal is committed here.
+ if attempt is not None:
+ await _await_artifact(
+ attempt.failed(kind="pin_unavailable", status=response.status_code), cancel
+ )
yield handed_back
return
else:
@@ -1932,6 +1973,10 @@ async def drive_sse_stream(
headers=response.headers,
)
if refused is not None and refused(candidate):
+ if attempt is not None:
+ await _await_artifact(
+ attempt.failed(kind="http_error", error_kind=candidate.kind), cancel
+ )
yield REFUSED
return
refused_payloads = opaque_refusal(body or "") if response.status_code == 400 else ()
@@ -1964,10 +2009,13 @@ async def drive_sse_stream(
resolved_origin.source_id,
resolved_origin.source_identity,
)
- async for item in translate(iter_sse_events(response, cancel)):
+ async for item in translate(iter_sse_events(response, cancel, capture=capture)):
if isinstance(item, (Done, ProviderError)):
candidate = item
break
+ if item is PAUSE_TURN and attempt is not None:
+ # A paused response's request ended normally; its continuation is another request.
+ await _await_artifact(attempt.succeeded(), cancel)
yield item
if isinstance(item, HandOff):
return
@@ -1980,8 +2028,12 @@ async def drive_sse_stream(
except (GeneratorExit, asyncio.CancelledError):
raise
except (OutputBudgetExceeded, SSEParseError, ToolIdentityError) as exc:
+ if attempt is not None:
+ attempt.exception_type = type(exc).__name__
candidate = assembler.error(str(exc), kind="invalid_request")
except Exception as exc:
+ if attempt is not None:
+ attempt.exception_type = type(exc).__name__
candidate = assembler.exception(exc)
if candidate is not None:
@@ -1996,6 +2048,18 @@ async def drive_sse_stream(
# long again, so the failure ends the turn: neither replayed nor
# continued.
candidate = replace(candidate, retryable=False, continuable=False)
+ # Decided before the artifact's write is awaited: diagnostic storage never counts as provider silence.
+ if attempt is not None:
+ await _await_artifact(
+ attempt.succeeded()
+ if isinstance(candidate, Done)
+ else attempt.failed(
+ kind=_attempt_failure_kind(candidate, response),
+ error_kind=candidate.kind,
+ status=response.status_code if response is not None else None,
+ ),
+ cancel,
+ )
# Translator terminals are candidates, not public errors. Commit
# and sanitize exactly once at the shared driver boundary.
assembler.end_driver()
@@ -2004,6 +2068,10 @@ async def drive_sse_stream(
yield terminal
finally:
assembler.end_driver()
+ if attempt is not None:
+ # Ended without a terminal (its consumer closed it, or its task was cancelled): out of the active set
+ # and its ``unknown`` state queued, synchronously. Nothing here waits for diagnostics.
+ attempt.abandon()
async def close_opened_response() -> None:
if opening is None:
return
@@ -2039,6 +2107,35 @@ async def drive_sse_stream(
opening.add_done_callback(close_late_response)
+async def _await_artifact(written: asyncio.Future[Any] | None, cancel: CancelToken) -> None:
+ """Wait for an artifact write: at most ``ARTIFACT_WAIT_S``, and never past a Stop (the CancelToken, or this
+ task's cancellation). The write itself always runs to its end on the artifact worker, which retrieves its
+ outcome; diagnostics never hold up a request, its terminal, or a Stop."""
+
+ if written is None:
+ return
+ try:
+ await _await_network(asyncio.shield(written), cancel, timeout_s=ARTIFACT_WAIT_S)
+ except ProviderStalled:
+ note_slow_artifact_write()
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ pass # logged by the write's done-callback
+
+
+def _attempt_failure_kind(error: ProviderError, response: httpx.Response | None) -> str:
+ """How a kept request ended, as a closed token: never the error's message, which can echo the request."""
+
+ if error.kind == "aborted":
+ return "cancelled"
+ if response is None:
+ return "network_error"
+ if not 200 <= response.status_code < 300:
+ return "http_error"
+ return "stream_error"
+
+
async def _await_network(
awaitable: Awaitable[_T],
cancel: CancelToken,
@@ -2126,8 +2223,13 @@ async def read_response_body(
cancel: CancelToken,
*,
max_bytes: int = 64 * 1024,
+ capture: ResponseCapture | None = None,
) -> str | None:
- """Read an error body through the shared cancellation owner with a byte cap."""
+ """Read an error body through the shared cancellation owner with a byte cap.
+
+ ``capture`` sees every chunk this read takes, and nothing more: it never reads on its own, so the text, the
+ error's classification, and the time it takes are what they are without capture.
+ """
iterator = response.aiter_bytes().__aiter__()
chunks: list[bytes] = []
@@ -2140,11 +2242,15 @@ async def read_response_body(
timeout_s=PROVIDER_SILENCE_TIMEOUT_S,
)
except StopAsyncIteration:
+ if capture is not None:
+ capture.finish()
break
if chunk is None:
return None
if not chunk:
continue
+ if capture is not None:
+ capture.feed(chunk)
remaining = max_bytes - size
piece = bytes(chunk[:remaining])
chunks.append(piece)
diff --git a/core/agent_core/ai/request_artifacts.py b/core/agent_core/ai/request_artifacts.py
new file mode 100644
index 000000000..da5858aa6
--- /dev/null
+++ b/core/agent_core/ai/request_artifacts.py
@@ -0,0 +1,753 @@
+"""Failed model request artifacts: the exact bytes a model request sent, kept when it did not succeed.
+
+``drive_sse_stream`` records every model request it sends while a capture scope is active
+(``capture_model_requests``); outside one it records nothing, so the library stays hermetic by default.
+
+Each attempt is one directory under the store root:
+
+- ``request.bin``: ``httpx.Request.content`` exactly as sent, never re-serialized.
+- ``meta.json``: typed facts only. These are the hop (protocol, provider, model, Source), the URL without its query
+ or userinfo, allowlisted headers, the body's size and sha256, the Session and Turn, the state and outcome, the
+ HTTP status, and the error kind. Never a credential, never an error message: a provider's message can echo the
+ request.
+- ``response.bin``: the raw response bytes the transport read anyway, never a read of its own. An HTTP error body
+ is what classification read (its first 64 KiB); a stream keeps its first ``STREAM_HEAD_BYTES`` and last
+ ``STREAM_TAIL_BYTES``, so a terminal error event survives. ``meta.json`` says whether the body was read to its
+ end and what was cut.
+
+Lifecycle. ``_ACTIVE`` holds the attempts this process may still send or stream; retention never removes one.
+- ``begin`` writes the pending attempt (and adds it to ``_ACTIVE``) before the request is sent. The send waits for
+ that write at most ``ARTIFACT_WAIT_S`` and never past a Stop: a Stop sends nothing (``cancelled`` / ``not_sent``),
+ and a stalled write is given up and the request sent untracked (``unknown`` / ``untracked``), settled when the
+ write lands.
+- Every ending goes through one path, ``RequestAttempt._queue``: in one synchronous step the attempt leaves
+ ``_ACTIVE`` and the write of its final state is queued on the worker, so no later cancellation can skip it. The
+ write runs to its end whoever waits for it, its outcome retrieved by a done-callback. The driver waits for a
+ terminal's write at most ``ARTIFACT_WAIT_S`` and never past a Stop; on a closed or cancelled stream it does not
+ wait at all. Endings:
+ - a semantically successful request is deleted: a ``Done``, or an Anthropic ``pause_turn`` sub-request that
+ ended normally;
+ - one that ended in an error is kept as ``failed``, or ``cancelled`` when the turn was stopped;
+ - one stopped before it was sent is kept as ``cancelled`` with outcome ``not_sent``;
+ - one whose consumer closed it, or whose task was cancelled, before any ending is ``unknown``.
+- An attempt whose final state was never written (the process died first) stays ``pending`` on disk. It reads
+ ``unknown`` once its owner process is gone, or, in the owner, once it is no
+ longer active. It is never treated as a success.
+
+The store root and every export directory are made owner-private by ``core.private_fs`` (on Windows, a protected
+DACL inherited by everything created inside). Files are created with ``O_EXCL | O_NOFOLLOW``. All filesystem work
+runs on one private worker thread, never on the event loop. A failure to record never changes the request's
+outcome; it is logged without payload.
+
+Retention defaults to 7 days and 256 MiB. It runs at the store's own writes, never on a timer: after every kept
+ending, and at any other write once ``MAINTENANCE_INTERVAL_S`` has passed. Each run removes expired attempts, then
+the oldest finished ones while over the quota (strictly: one larger than the quota goes too). An active attempt is
+never removed.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import functools
+import hashlib
+import json
+import logging
+import os
+import re
+import secrets
+import shutil
+import stat
+import threading
+import time
+from time import monotonic as _monotonic
+from collections import deque
+from collections.abc import Iterator, Mapping
+from concurrent.futures import ThreadPoolExecutor
+from contextlib import contextmanager
+from contextvars import ContextVar
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Callable, TypeVar
+from urllib.parse import urlsplit, urlunsplit
+
+import psutil
+
+from core.private_fs import ensure_private_directory
+
+logger = logging.getLogger(__name__)
+
+SCHEMA_VERSION = 1
+DEFAULT_RETENTION_S = 7 * 24 * 60 * 60
+DEFAULT_QUOTA_BYTES = 256 * 1024 * 1024
+#: An HTTP error body is kept as far as it was read, up to this size; anything after it is cut and the cut stated.
+ERROR_BODY_LIMIT = 1024 * 1024
+#: A stream (HTTP 2xx) keeps its start and its end; the middle of a long one is dropped and the drop stated.
+STREAM_HEAD_BYTES = 64 * 1024
+STREAM_TAIL_BYTES = 1024 * 1024
+#: An interrupted write leaves a ``.partial`` directory; one this old belongs to no live write.
+_PARTIAL_GRACE_S = 60 * 60
+#: Retention runs at the store's own writes, never on a timer: after every kept ending, and at any other write once
+#: this long has passed since the last run. An attempt that expires is removed at the first write after that.
+MAINTENANCE_INTERVAL_S = 10 * 60
+#: The longest a request, its terminal, or its cleanup waits for an artifact write. A write still running then goes
+#: on in the worker (its outcome still retrieved); the request does not wait for diagnostics any longer.
+ARTIFACT_WAIT_S = 10.0
+
+REQUEST_FILE = "request.bin"
+RESPONSE_FILE = "response.bin"
+META_FILE = "meta.json"
+_FILES = (REQUEST_FILE, RESPONSE_FILE, META_FILE)
+
+ARTIFACT_ID = re.compile(r"^mr_[0-9]{8}T[0-9]{6}Z_[0-9a-f]{12}$")
+
+#: Headers that name the request's shape and route, never a credential.
+_REQUEST_HEADERS = frozenset({
+ "accept",
+ "anthropic-beta",
+ "anthropic-version",
+ "content-length",
+ "content-type",
+ "user-agent",
+ "x-avibe-pin-model",
+ "x-avibe-pin-source",
+})
+#: Headers that correlate a response across hops or describe its body.
+_RESPONSE_HEADERS = frozenset({
+ "content-type",
+ "request-id",
+ "retry-after",
+ "x-avibe-served-hop",
+ "x-request-id",
+ "x-should-retry",
+})
+
+PENDING = "pending"
+FAILED = "failed"
+CANCELLED = "cancelled"
+UNKNOWN = "unknown"
+
+_T = TypeVar("_T")
+
+#: Attempts this process has sent and not yet ended, across every store object. Only these of its own pending
+#: attempts are active; retention never removes an active attempt.
+_ACTIVE: set[str] = set()
+_ACTIVE_LOCK = threading.Lock()
+
+
+class ArtifactStoreError(RuntimeError):
+ """The store cannot be used safely: a path that is not a private directory, or an unknown artifact."""
+
+
+@dataclass(frozen=True)
+class CaptureScope:
+ """Where the requests sent in this context are recorded, and the Session and Turn they belong to."""
+
+ store: "RequestArtifactStore"
+ session_id: str | None = None
+ turn_id: str | None = None
+ version: str | None = None
+
+
+_SCOPE: ContextVar[CaptureScope | None] = ContextVar("avibe_model_request_capture", default=None)
+
+
+@contextmanager
+def capture_model_requests(
+ store: "RequestArtifactStore",
+ *,
+ session_id: str | None = None,
+ turn_id: str | None = None,
+ version: str | None = None,
+) -> Iterator[None]:
+ """Record every model request sent in this context, and in the tasks it starts, to ``store``."""
+
+ token = _SCOPE.set(CaptureScope(store, session_id, turn_id, version))
+ try:
+ yield
+ finally:
+ _SCOPE.reset(token)
+
+
+def _now() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _new_id() -> str:
+ return f"mr_{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}_{secrets.token_hex(6)}"
+
+
+def safe_url(url: str) -> str:
+ """The URL without userinfo, query, or fragment: a key some providers take as a query parameter stays out."""
+
+ parts = urlsplit(url)
+ host = parts.hostname or ""
+ if parts.port is not None:
+ host = f"{host}:{parts.port}"
+ return urlunsplit((parts.scheme, host, parts.path, "", ""))
+
+
+def allowed_headers(headers: Mapping[str, str], allowed: frozenset[str]) -> dict[str, str]:
+ return {name.lower(): value for name, value in headers.items() if name.lower() in allowed}
+
+
+def _process_start(pid: int) -> float | None:
+ try:
+ return float(psutil.Process(pid).create_time())
+ except (psutil.Error, OSError, ValueError):
+ return None
+
+
+def _owner_alive(owner: Any) -> bool:
+ if not isinstance(owner, Mapping):
+ return False
+ pid, started = owner.get("pid"), owner.get("started")
+ if not isinstance(pid, int) or pid <= 0:
+ return False
+ current = _process_start(pid)
+ if current is None:
+ return False
+ # A reused pid belongs to a process started later; the clock's precision differs by platform.
+ return not isinstance(started, (int, float)) or abs(current - float(started)) < 1.0
+
+
+class ResponseCapture:
+ """The raw response bytes as read, bounded: a whole error body up to its limit, or a stream's head and tail."""
+
+ def __init__(self) -> None:
+ self.status: int | None = None
+ self.headers: dict[str, str] = {}
+ self.total = 0
+ self.read_to_end = False
+ self._head = bytearray()
+ self._tail: deque[bytes] = deque()
+ self._tail_size = 0
+ self._streaming = False
+
+ def response(self, status: int, headers: Mapping[str, str]) -> None:
+ self.status = status
+ self.headers = allowed_headers(headers, _RESPONSE_HEADERS)
+ self._streaming = 200 <= status < 300
+
+ @property
+ def head_limit(self) -> int:
+ return STREAM_HEAD_BYTES if self._streaming else ERROR_BODY_LIMIT
+
+ def feed(self, chunk: bytes) -> None:
+ if not chunk:
+ return
+ self.total += len(chunk)
+ room = self.head_limit - len(self._head)
+ if room > 0:
+ self._head += chunk[:room]
+ chunk = chunk[room:]
+ if chunk and self._streaming:
+ if len(chunk) >= STREAM_TAIL_BYTES:
+ # One chunk fills the tail alone: only its end is kept, never the chunk itself.
+ self._tail.clear()
+ self._tail.append(bytes(chunk[-STREAM_TAIL_BYTES:]))
+ self._tail_size = STREAM_TAIL_BYTES
+ return
+ self._tail.append(bytes(chunk))
+ self._tail_size += len(chunk)
+ # Held strictly within the bound: whole chunks drop first, then the start of the oldest one left.
+ while self._tail_size > STREAM_TAIL_BYTES:
+ excess = self._tail_size - STREAM_TAIL_BYTES
+ first = self._tail[0]
+ if len(first) <= excess:
+ self._tail.popleft()
+ self._tail_size -= len(first)
+ else:
+ self._tail[0] = first[excess:]
+ self._tail_size -= excess
+
+ def finish(self) -> None:
+ self.read_to_end = True
+
+
+ def _tail_bytes(self) -> bytes:
+ return b"".join(self._tail)
+
+ def body(self) -> bytes:
+ return bytes(self._head) + self._tail_bytes()
+
+ def summary(self) -> dict[str, Any]:
+ tail = self._tail_size
+ captured = len(self._head) + tail
+ omitted = self.total - captured
+ summary: dict[str, Any] = {
+ "status": self.status,
+ "headers": dict(self.headers),
+ "read_bytes": self.total,
+ "read_to_end": self.read_to_end,
+ "captured_bytes": captured,
+ "truncated": omitted > 0,
+ }
+ if omitted > 0:
+ # A stream drops its middle; an error body drops its end (and was not read past its limit).
+ summary["truncation"] = "middle" if tail else "end"
+ summary["omitted_bytes"] = omitted
+ summary["head_bytes"] = len(self._head)
+ return summary
+
+
+class RequestArtifactStore:
+ """The private directory of request artifacts. Every method is blocking: callers run them off the event loop."""
+
+ def __init__(
+ self,
+ root: Path,
+ *,
+ retention_s: float = DEFAULT_RETENTION_S,
+ quota_bytes: int = DEFAULT_QUOTA_BYTES,
+ ) -> None:
+ self.root = Path(root)
+ self.retention_s = retention_s
+ self.quota_bytes = quota_bytes
+ self._ready = False
+ self._retained_at: float | None = None
+
+ # -- paths -------------------------------------------------------------------------------------------------
+
+ def _ensure_root(self) -> Path:
+ """The root, owner-private (``core.private_fs``): created so, or repaired, once per store object. A link or
+ a non-directory in its place is refused."""
+
+ if not self._ready:
+ ensure_private_directory(self.root)
+ if self.root.is_symlink():
+ raise ArtifactStoreError(f"{self.root} is not a private directory")
+ self._ready = True
+ # What earlier processes left behind is pruned before this one adds to it.
+ self._retain(force=True)
+ return self.root
+
+ def _retain(self, *, force: bool) -> None:
+ """Apply retention at a write: always after a kept ending, otherwise once per ``MAINTENANCE_INTERVAL_S``."""
+
+ now = _monotonic()
+ if not force and self._retained_at is not None and now - self._retained_at < MAINTENANCE_INTERVAL_S:
+ return
+ self._retained_at = now
+ self.prune()
+
+ def path(self, artifact_id: str) -> Path:
+ if not ARTIFACT_ID.match(artifact_id):
+ raise ArtifactStoreError(f"invalid artifact id: {artifact_id!r}")
+ directory = self.root / artifact_id
+ try:
+ info = os.lstat(directory)
+ except FileNotFoundError:
+ raise ArtifactStoreError(f"artifact {artifact_id} not found") from None
+ if stat.S_ISLNK(info.st_mode) or not stat.S_ISDIR(info.st_mode):
+ raise ArtifactStoreError(f"artifact {artifact_id} is not a private directory")
+ return directory
+
+ # -- writes ------------------------------------------------------------------------------------------------
+
+ def begin(self, meta: dict[str, Any], body: bytes) -> str:
+ """Write a pending attempt and return its id; it is active in this process until ``end`` or ``abandon``."""
+
+ root = self._ensure_root()
+ self._retain(force=False)
+ artifact_id = _new_id()
+ partial = root / f".{artifact_id}.partial"
+ os.mkdir(partial, 0o700)
+ _write_private(partial / REQUEST_FILE, body)
+ _write_private(partial / META_FILE, _encode({**meta, "id": artifact_id}))
+ os.rename(partial, root / artifact_id)
+ with _ACTIVE_LOCK:
+ _ACTIVE.add(artifact_id)
+ return artifact_id
+
+ def succeed(self, artifact_id: str) -> None:
+ """A semantically successful attempt is not kept."""
+
+ self._remove(self.path(artifact_id))
+ self._retain(force=False)
+
+ def fail(self, artifact_id: str, outcome: Mapping[str, Any], capture: ResponseCapture | None) -> None:
+ """Keep the attempt with its outcome and the response read, then apply retention."""
+
+ directory = self.path(artifact_id)
+ meta = self.meta(artifact_id)
+ if capture is not None and capture.total:
+ _write_private(directory / RESPONSE_FILE, capture.body())
+ meta.update(outcome)
+ meta["finished_at"] = _now()
+ if capture is not None:
+ meta["response"] = capture.summary()
+ _replace_private(directory / META_FILE, _encode(meta))
+ self._retain(force=True)
+
+ def close(self, artifact_id: str, *, state: str, kind: str) -> None:
+ """An attempt that ended with no response to keep: stopped before it was sent (``cancelled``,
+ ``not_sent``), or closed with no known outcome (``unknown``). Every reader, in any process, sees it."""
+
+ directory = self.path(artifact_id)
+ meta = self.meta(artifact_id)
+ meta["state"] = state
+ meta["outcome"] = {"kind": kind, "error_kind": None, "http_status": None, "exception_type": None}
+ meta["finished_at"] = _now()
+ _replace_private(directory / META_FILE, _encode(meta))
+ self._retain(force=True)
+
+ # -- reads -------------------------------------------------------------------------------------------------
+
+ def meta(self, artifact_id: str) -> dict[str, Any]:
+ path = self.path(artifact_id) / META_FILE
+ data = json.loads(_read_private(path).decode("utf-8"))
+ if not isinstance(data, dict):
+ raise ArtifactStoreError(f"artifact {artifact_id} has no readable metadata")
+ return data
+
+ def state(self, meta: Mapping[str, Any]) -> str:
+ """The attempt's state as a reader should see it: a pending one nobody is still sending is ``unknown``."""
+
+ state = meta.get("state")
+ if state != PENDING:
+ return str(state)
+ return PENDING if self._is_active(meta) else UNKNOWN
+
+ def _is_active(self, meta: Mapping[str, Any]) -> bool:
+ owner = meta.get("owner")
+ if isinstance(owner, Mapping) and owner.get("pid") == os.getpid():
+ with _ACTIVE_LOCK:
+ return meta.get("id") in _ACTIVE
+ return _owner_alive(owner)
+
+ def entries(self) -> list[dict[str, Any]]:
+ """Every readable attempt, newest first, with its effective state and size on disk."""
+
+ try:
+ root_info = os.lstat(self.root)
+ except FileNotFoundError:
+ return []
+ if stat.S_ISLNK(root_info.st_mode) or not stat.S_ISDIR(root_info.st_mode):
+ raise ArtifactStoreError(f"{self.root} is not a private directory")
+ found: list[dict[str, Any]] = []
+ with os.scandir(self.root) as listing:
+ for entry in listing:
+ if not ARTIFACT_ID.match(entry.name) or not entry.is_dir(follow_symlinks=False):
+ continue
+ try:
+ meta = self.meta(entry.name)
+ except (OSError, ValueError, ArtifactStoreError):
+ continue
+ meta["state"] = self.state(meta)
+ meta["size_bytes"] = _size(Path(entry.path))
+ found.append(meta)
+ found.sort(key=lambda meta: str(meta.get("created_at") or ""), reverse=True)
+ return found
+
+ # -- retention ---------------------------------------------------------------------------------------------
+
+ def prune(self) -> None:
+ if not self.root.is_dir() or self.root.is_symlink():
+ return
+ now = time.time()
+ with os.scandir(self.root) as listing:
+ for entry in listing:
+ if entry.name.endswith(".partial") and entry.is_dir(follow_symlinks=False):
+ try:
+ if now - entry.stat(follow_symlinks=False).st_mtime > _PARTIAL_GRACE_S:
+ self._remove(Path(entry.path))
+ except OSError:
+ continue
+ entries = self.entries()
+ cutoff = now - self.retention_s
+ kept: list[dict[str, Any]] = []
+ for meta in entries:
+ if meta["state"] != PENDING and _timestamp(meta.get("created_at")) < cutoff:
+ self._remove_quietly(meta)
+ else:
+ kept.append(meta)
+ total = sum(int(meta["size_bytes"]) for meta in kept)
+ for meta in reversed(kept): # oldest first
+ if total <= self.quota_bytes:
+ break
+ if meta["state"] == PENDING:
+ continue
+ self._remove_quietly(meta)
+ total -= int(meta["size_bytes"])
+
+ def _remove_quietly(self, meta: Mapping[str, Any]) -> None:
+ try:
+ self._remove(self.path(str(meta.get("id"))))
+ except (OSError, ArtifactStoreError):
+ pass
+
+ @staticmethod
+ def _remove(directory: Path) -> None:
+ info = os.lstat(directory)
+ if stat.S_ISLNK(info.st_mode) or not stat.S_ISDIR(info.st_mode):
+ raise ArtifactStoreError(f"{directory} is not a private directory")
+ shutil.rmtree(directory)
+
+ # -- export ------------------------------------------------------------------------------------------------
+
+ def export(self, artifact_id: str, destination: Path) -> Path:
+ """Copy one attempt's files into ``destination/<id>/``: a new private directory under a directory the
+ caller chose. Only this store's files are read; an existing or linked target is refused."""
+
+ source = self.path(artifact_id)
+ destination = Path(destination).expanduser()
+ if destination.is_symlink():
+ raise ArtifactStoreError(f"{destination} is a symbolic link")
+ destination.mkdir(parents=True, exist_ok=True)
+ if destination.is_symlink() or not destination.is_dir():
+ raise ArtifactStoreError(f"{destination} is not a directory")
+ target = destination / artifact_id
+ if os.path.lexists(target):
+ raise FileExistsError(f"{target} already exists")
+ # Owner-private from its creation (on Windows a protected, inherited DACL): the files below start private.
+ ensure_private_directory(target)
+ if target.is_symlink() or any(target.iterdir()):
+ raise ArtifactStoreError(f"{target} is not a new private directory")
+ for name in _FILES:
+ path = source / name
+ try:
+ data = _read_private(path)
+ except FileNotFoundError:
+ continue
+ _write_private(target / name, data)
+ return target
+
+
+def _encode(meta: Mapping[str, Any]) -> bytes:
+ return (json.dumps(meta, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode("utf-8")
+
+
+def _timestamp(value: Any) -> float:
+ try:
+ return datetime.fromisoformat(str(value)).timestamp()
+ except (TypeError, ValueError):
+ return 0.0
+
+
+def _size(directory: Path) -> int:
+ total = 0
+ for name in _FILES:
+ try:
+ total += os.lstat(directory / name).st_size
+ except OSError:
+ continue
+ return total
+
+
+_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)
+_CLOEXEC = getattr(os, "O_CLOEXEC", 0)
+_BINARY = getattr(os, "O_BINARY", 0)
+
+
+def _write_private(path: Path, data: bytes) -> None:
+ descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | _NOFOLLOW | _CLOEXEC | _BINARY, 0o600)
+ with os.fdopen(descriptor, "wb") as handle:
+ handle.write(data)
+
+
+def _replace_private(path: Path, data: bytes) -> None:
+ temporary = path.with_name(f".{path.name}.{secrets.token_hex(4)}.tmp")
+ _write_private(temporary, data)
+ os.replace(temporary, path)
+
+
+def _read_private(path: Path) -> bytes:
+ descriptor = os.open(path, os.O_RDONLY | _NOFOLLOW | _CLOEXEC | _BINARY)
+ with os.fdopen(descriptor, "rb") as handle:
+ return handle.read()
+
+
+# -- the attempt the transport drives ---------------------------------------------------------------------------
+
+_executor: ThreadPoolExecutor | None = None
+_executor_lock = threading.Lock()
+
+
+def _worker() -> ThreadPoolExecutor:
+ """One private thread: artifact writes keep their order and never run on the event loop."""
+
+ global _executor
+ with _executor_lock:
+ if _executor is None:
+ _executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="avibe-request-artifacts")
+ return _executor
+
+
+def _submit(function: Callable[..., _T], *args: Any) -> asyncio.Future[_T]:
+ """Queue ``function`` on the artifact worker; the caller owns the returned future."""
+
+ return asyncio.get_running_loop().run_in_executor(_worker(), functools.partial(function, *args))
+
+
+class RequestAttempt:
+ """One sent request's artifact, driven by ``drive_sse_stream``. Every ending is queued synchronously and returns
+ the write's future; how long the request waits for it (never past a Stop) is the driver's decision. Every step
+ is best effort: a failure to record is logged without payload and never reaches the request's outcome."""
+
+ def __init__(self, store: RequestArtifactStore, artifact_id: str) -> None:
+ self.store = store
+ self.id = artifact_id
+ self.capture = ResponseCapture()
+ self.exception_type: str | None = None
+ self.ended = False
+
+ def succeeded(self) -> asyncio.Future[Any] | None:
+ return self._queue("remove a successful request", self.store.succeed, self.id)
+
+ def failed(
+ self, *, kind: str, error_kind: str | None = None, status: int | None = None
+ ) -> asyncio.Future[Any] | None:
+ outcome: dict[str, Any] = {
+ "state": CANCELLED if kind == "cancelled" else FAILED,
+ "outcome": {
+ "kind": kind,
+ "error_kind": error_kind,
+ "http_status": status if status is not None else self.capture.status,
+ "exception_type": self.exception_type,
+ },
+ }
+ return self._queue("keep a failed request", self.store.fail, self.id, outcome, self.capture)
+
+ def not_sent(self) -> asyncio.Future[Any] | None:
+ """Stopped before it was sent: the request never went out."""
+
+ return self._queue(
+ "keep an unsent request", functools.partial(self.store.close, state=CANCELLED, kind="not_sent"), self.id
+ )
+
+ def abandon(self) -> asyncio.Future[Any] | None:
+ """Closed with no known outcome: its consumer stopped reading, or its task was cancelled."""
+
+ return self._queue(
+ "mark an interrupted request", functools.partial(self.store.close, state=UNKNOWN, kind=UNKNOWN), self.id
+ )
+
+ def _queue(self, action: str, write: Callable[..., Any], *args: Any) -> asyncio.Future[Any] | None:
+ """The one way an attempt ends: out of ``_ACTIVE`` and its final state queued on the worker, in one
+ synchronous step, so no later cancellation can skip it. The write runs to its end whoever waits for it; its
+ outcome is retrieved by a done-callback and a failure logged, never raised into the request."""
+
+ if self.ended:
+ return None
+ self.ended = True
+ _release(self.id)
+ written = _submit(write, *args)
+ written.add_done_callback(functools.partial(_log_write_failure, action))
+ return written
+
+
+class PendingBegin:
+ """A pending write queued before a send. The driver waits for it (never past a Stop or ``ARTIFACT_WAIT_S``),
+ then takes the attempt it wrote, or gives it up: cancelled before the send (``cancelled`` / ``not_sent``), or
+ sent without it because it stalled (``unknown`` / ``untracked``)."""
+
+ def __init__(self, store: RequestArtifactStore, ticket: "_PendingWrite", written: asyncio.Future[str]) -> None:
+ self.store = store
+ self.written = written
+ self._ticket = ticket
+
+ def attempt(self) -> RequestAttempt | None:
+ written = self.written
+ if not written.done() or written.cancelled() or written.exception() is not None:
+ return None
+ return RequestAttempt(self.store, written.result())
+
+ def give_up(self, *, sent: bool) -> None:
+ if sent:
+ self._ticket.give_up(self.store, state=UNKNOWN, kind="untracked")
+ else:
+ self._ticket.give_up(self.store, state=CANCELLED, kind="not_sent")
+
+
+def begin_attempt(request: Any, *, endpoint: Any, protocol: str) -> PendingBegin | None:
+ """Queue ``request`` (an ``httpx.Request``) as a pending attempt, when a capture scope is active. The caller
+ waits for ``PendingBegin.written`` before it sends."""
+
+ scope = _SCOPE.get()
+ if scope is None:
+ return None
+ try:
+ body = bytes(request.content)
+ meta: dict[str, Any] = {
+ "schema_version": SCHEMA_VERSION,
+ "state": PENDING,
+ "created_at": _now(),
+ "owner": {"pid": os.getpid(), "started": _process_start(os.getpid())},
+ "session_id": scope.session_id,
+ "turn_id": scope.turn_id,
+ "avibe_version": scope.version,
+ "request": {
+ "method": request.method,
+ "url": safe_url(str(request.url)),
+ "protocol": protocol,
+ "provider": getattr(endpoint, "provider", None),
+ "model": getattr(endpoint, "model_id", None),
+ "source_id": getattr(endpoint, "source_id", None),
+ "headers": allowed_headers(request.headers, _REQUEST_HEADERS),
+ "body_bytes": len(body),
+ "body_sha256": hashlib.sha256(body).hexdigest(),
+ },
+ }
+ except Exception as exc:
+ _record_failure("record a pending request", exc)
+ return None
+ ticket = _PendingWrite()
+ written = _submit(ticket.write, scope.store, meta, body)
+ written.add_done_callback(functools.partial(_log_write_failure, "record a pending request"))
+ return PendingBegin(scope.store, ticket, written)
+
+
+class _PendingWrite:
+ """A pending write that its request may give up: whichever comes second, the write landing or the giving up,
+ settles it on the worker and takes it out of ``_ACTIVE``."""
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._given_up: tuple[str, str] | None = None
+ self._artifact_id: str | None = None
+
+ def write(self, store: RequestArtifactStore, meta: dict[str, Any], body: bytes) -> str:
+ artifact_id = store.begin(meta, body)
+ with self._lock:
+ self._artifact_id = artifact_id
+ given_up = self._given_up
+ if given_up is not None:
+ _release(artifact_id)
+ store.close(artifact_id, state=given_up[0], kind=given_up[1])
+ return artifact_id
+
+ def give_up(self, store: RequestArtifactStore, *, state: str, kind: str) -> None:
+ with self._lock:
+ if self._given_up is not None:
+ return
+ self._given_up = (state, kind)
+ landed = self._artifact_id
+ if landed is None:
+ return # the write settles it when it lands
+ _release(landed)
+ settled = _submit(functools.partial(store.close, state=state, kind=kind), landed)
+ settled.add_done_callback(functools.partial(_log_write_failure, "settle a pending request"))
+
+
+def _release(artifact_id: str) -> None:
+ with _ACTIVE_LOCK:
+ _ACTIVE.discard(artifact_id)
+
+
+def _log_write_failure(action: str, written: Any) -> None:
+ """Retrieve a worker write's outcome, so none goes unobserved, and log a failure without payload."""
+
+ if written.cancelled():
+ return
+ exc = written.exception()
+ if exc is not None:
+ _record_failure(action, exc)
+
+
+def note_slow_artifact_write() -> None:
+ logger.warning("An artifact write is still running after %ss; not waiting for it", ARTIFACT_WAIT_S)
+
+
+def _record_failure(action: str, exc: BaseException) -> None:
+ logger.warning("Could not %s artifact: %s", action, type(exc).__name__)
diff --git a/docs/CLI.md b/docs/CLI.md
index b680b9e43..3557b2fee 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -600,6 +600,24 @@ message sent mid-turn, is `other_outputs`; delivery bookkeeping, turn and
process ids, and copies of other fields are not printed. `--brief` prints the
same compact row as `vibe runs list`, for status checks.
+### `vibe model-requests`
+
+Inspect the model requests Vibey kept because they did not succeed: the exact
+bytes sent, with the outcome and the raw response read.
+
+```bash
+vibe model-requests list # newest first; --session-id and --state narrow it, --page and --limit page it
+vibe model-requests show mr_20261031T140102Z_0a1b2c3d4e5f
+vibe model-requests export mr_20261031T140102Z_0a1b2c3d4e5f --to ~/private/requests
+```
+
+`list` and `show` print metadata only, never a request or response body.
+`export` copies one request's files into a new private directory `<dir>/<id>/`.
+The files can hold prompts and tool output. See
+[Model request artifacts](model-request-artifacts.md) for what is kept, for how
+long, and why these are the bytes sent to the local Model Hub rather than the
+provider's.
+
### `vibe task`
Create, inspect, update, run, pause, resume, or remove scheduled tasks.
@@ -982,6 +1000,7 @@ The web UI (`http://127.0.0.1:5123`) provides the same controls:
| `~/.vibe_remote/state/task_requests/` | Legacy queued task/hook requests imported into SQLite on startup |
| `~/.vibe_remote/state/user_preferences.md` | Shared long-term user preference notes |
| `~/.vibe_remote/state/backups/` | Automatic state backups taken before migrations |
+| `~/.vibe_remote/state/agent_core/model-requests/` | Private copies of Vibey model requests that did not succeed (`vibe model-requests`); kept 7 days, 256 MiB at most |
| `~/.vibe_remote/runtime/remote-access-cloudflared.pid` | cloudflared tunnel PID for Avibe Cloud remote access |
| `~/.vibe_remote/screenshots/` | Default output directory for `vibe screenshot` |
| `~/.vibe_remote/logs/vibe_remote.log` | Application logs |
diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.md
index 761cea523..d66cf2e4a 100644
--- a/docs/CLI_ZH.md
+++ b/docs/CLI_ZH.md
@@ -476,6 +476,21 @@ vibe runs show # 在 Avibe Agent shell 内查看调用
`other_outputs`;投递记账、turn 与进程 id,以及其他字段的副本都不输出。`--brief`
只输出与 `vibe runs list` 相同的精简行,用于查看状态。
+### `vibe model-requests`
+
+查看 Vibey 因请求未成功而保留下来的模型请求:发送时的原始字节、结果,以及读到的原始响应。
+
+```bash
+vibe model-requests list # 最新的在前;--session-id、--state 缩小范围,--page、--limit 分页
+vibe model-requests show mr_20261031T140102Z_0a1b2c3d4e5f
+vibe model-requests export mr_20261031T140102Z_0a1b2c3d4e5f --to ~/private/requests
+```
+
+`list` 和 `show` 只输出元数据,不输出请求或响应正文。`export` 把一条请求的文件复制到新建的私有目录
+`<dir>/<id>/`。这些文件可能包含提示词和工具输出。保留哪些内容、保留多久,以及为什么这是发给本机
+Model Hub 的字节而不是 provider 收到的字节,见
+[Model request artifacts](model-request-artifacts.md)。
+
### `vibe task`
创建、查看、更新、立即执行、暂停、恢复或删除定时任务。
diff --git a/docs/model-request-artifacts.md b/docs/model-request-artifacts.md
new file mode 100644
index 000000000..9b773eb75
--- /dev/null
+++ b/docs/model-request-artifacts.md
@@ -0,0 +1,160 @@
+# Model request artifacts
+
+When a Vibey model request does not succeed, Avibe keeps the exact bytes it sent, so the failure can be studied
+later: for example, a provider 400 whose cause depends on the request's shape. Requests that succeed leave nothing
+behind.
+
+Source: `core/agent_core/ai/request_artifacts.py`. It is wired into the shared transport (`drive_sse_stream` in
+`core/agent_core/ai/_common.py`) and into Vibey Turns (`modules/agents/vibey/agent.py`).
+
+## What is kept, and when
+
+Every model request a Vibey Turn sends goes through the shared transport. This covers all four protocols:
+Anthropic Messages, OpenAI Responses, OpenAI Chat Completions, and Google.
+
+1. **Before the request is sent**, its pending artifact is written: `request.bin` (the `httpx.Request.content` that
+ is then sent, byte for byte) and `meta.json`. The send waits for that write at most 10 s, and never past a Stop.
+ - A Stop during the write sends nothing, and the attempt is kept as `cancelled` with outcome `not_sent`.
+ - A write that stalls longer is not waited for: the request goes out untracked, and the write is settled as
+ `unknown` with outcome `untracked` when it lands.
+2. **When it ends**, it is resolved in one of these ways:
+ - A semantically successful request is deleted. That means one that produced a complete response (`Done`), or an
+ Anthropic `pause_turn` sub-request that ended normally. Its continuation is a separate request with its own
+ artifact.
+ - One that ended in an error is kept as `failed`: an HTTP error (including the gateway's `pin_unavailable` 409
+ and an HTTP 400 that leads to a resend), a stream that returned HTTP 200 but ended with an error or a stall,
+ or a network failure. HTTP 200 alone is not success. A turn stopped mid-request is `cancelled`.
+ - One stopped before it was sent is `cancelled` with outcome `not_sent`, so it never caused provider work.
+ - One closed with no known outcome is `unknown`: its consumer stopped reading, or its task was cancelled before
+ a terminal.
+3. **Every ending goes through one path.** The attempt leaves this process's active set and the write of its final
+ state is queued on the worker in the same synchronous step, so no later cancellation can skip it. The write
+ always runs to its end on the worker, which retrieves its outcome and logs a failure, never raising it into the
+ request.
+ - Before yielding a terminal, the driver waits for that write at most 10 s, and never past a Stop.
+ - A stream that is closed or cancelled does not wait at all: its `unknown` write is only queued.
+ - Whichever comes second, a pending write landing or the request giving it up, settles the attempt.
+4. **An attempt whose final state was never written** stays `pending` on disk: the process died first.
+ `vibe model-requests` shows it as `unknown` once its owner process is gone (pid and process start time). It is
+ never treated as a success.
+
+Outside a Vibey Turn nothing is captured: the library default is off, so tests and other callers stay hermetic.
+
+### Scope: client-to-Model-Hub bytes
+
+Vibey sends its requests to the local Model Hub gateway. These are the bytes Vibey sent to the gateway. They are
+**not** the bytes the gateway, a relay, or the provider finally received, because the Model Hub engine may rewrite
+a request before forwarding it. To correlate one with the upstream hop, use its `x-request-id` / `request-id`
+response header (kept in `meta.json`) and the Model Hub provenance of the same Turn.
+
+## Layout
+
+```
+~/.avibe/state/agent_core/model-requests/
+ mr_20261031T140102Z_0a1b2c3d4e5f/
+ request.bin # the request body exactly as sent
+ response.bin # the raw response bytes read, when there were any
+ meta.json # typed facts only
+```
+
+- **`meta.json`** holds:
+ - the Session and Turn, and the Avibe version;
+ - the hop: protocol, provider, model, Source, and the URL without its query or userinfo;
+ - allowlisted request headers (`content-type`, `anthropic-version`, `anthropic-beta`, the Model Hub pin headers,
+ and the like);
+ - the body's size and sha256;
+ - `outcome`: `kind`, `error_kind`, `http_status`, and `exception_type`;
+ - for the response: its status, allowlisted headers (`content-type`, `request-id`, `x-request-id`, `retry-after`,
+ `x-should-retry`, `x-avibe-served-hop`), and the bytes read and kept.
+
+ It never holds a credential or any other header, and never an error message: a provider's message can echo the
+ prompt, tools, or a credential. The response body is in `response.bin`.
+- **`response.bin`**:
+ The capture only sees bytes the transport reads anyway. It never reads on its own, so the error's classification
+ and timing are what they are without it.
+ - An HTTP error body is kept as far as it is read to classify the error: its first 64 KiB, plus the rest of the
+ last chunk read, up to 1 MiB. A larger body is **expected to be incomplete**, with `read_to_end: false`.
+ - A stream (HTTP 2xx) keeps its first 64 KiB and its last 1 MiB, so the terminal error event of a long response
+ survives.
+ - `meta.json` states completeness and any cut: `read_to_end`, `truncated`, `truncation`, `omitted_bytes`. The
+ request body, by contrast, is always complete.
+
+The files can contain prompts, tool output, and attachments. The store root and every export directory are made
+owner-private by `core.private_fs`:
+- on POSIX, `0700` directories and `0600` files;
+- on Windows, a protected DACL that grants only this user and SYSTEM, set when the directory is created and
+ inherited by everything created inside.
+
+Files are created with `O_EXCL | O_NOFOLLOW`, and a store or export path that is a symbolic link is refused. The
+Windows path is exercised by `core.private_fs`'s own Windows tests; this feature's tests check the same
+`private_fs.is_private` contract on the platform they run on.
+
+## Retention
+
+The defaults are 7 days and 256 MiB. Retention runs at the store's own writes, never on a timer:
+
+- after every attempt that is kept, whether `failed`, `cancelled`, or `unknown`;
+- when a process first records a request;
+- at any other write (a new request, or the removal of a successful one) once 10 minutes have passed since the last
+ run.
+
+An attempt that expires is therefore removed at the first write after it does. A process that sends nothing
+removes nothing; the next one to write does.
+
+Each run removes expired attempts, and then, while the store is over its quota, the oldest finished or unknown
+attempts. The quota is strict for those: a single kept attempt larger than the quota is removed as soon as it is
+kept. An attempt still being sent by a live process is never removed (liveness is the owner's pid together with its
+process start time, so a reused pid does not count). While requests are in flight, the store can therefore exceed
+the quota by their size.
+
+Trade-offs:
+- A week covers the time between noticing a failure and studying it.
+- 256 MiB holds dozens of the largest real requests (several MiB each with long contexts or images) without
+ growing without bound.
+- Retention is part of the write it runs in, on the artifact worker. A run scans the store, which the quota keeps
+ small, so it can add a few milliseconds to that write. It never changes a request's outcome.
+
+## Runtime cost and failure isolation
+
+All filesystem work runs on one private worker thread, never on the controller's event loop. Waits on that worker
+are bounded:
+- before the send, a request waits for its pending write, for at most 10 s;
+- before its terminal, for its own removal or finalization, for at most 10 s;
+- a Stop (the CancelToken, or the reading task's cancellation through the Agent loop's `RunScope`) ends either wait
+ at once;
+- a closed or cancelled stream's cleanup never waits.
+
+Diagnostics can therefore delay a request by at most that bound, and a Stop not at all.
+
+If the store cannot be written (full disk, a non-directory in its place), the request proceeds exactly as it would
+without capture. A warning names only the failed step and the exception type.
+
+## CLI
+
+```bash
+vibe model-requests list [--session-id ID] [--state failed|cancelled|unknown|pending] [--page N] [--limit N]
+vibe model-requests show <id>
+vibe model-requests export <id> --to <dir>
+```
+
+- The commands run at the Owner role floor, since the attempts hold every Session's prompts.
+- `list` and `show` print the JSON envelope with metadata only, never a body.
+- `export` reads only from the store, by a validated id. It copies the attempt's files into a new private
+ directory `<dir>/<id>/`, and refuses a symbolic-link destination or an existing export.
+- Share exports with care: they hold the conversation.
+
+## Testing
+
+`tests/agent_core/ai/test_request_artifacts.py` drives the real adapters over `httpx.MockTransport`. It covers:
+
+- exact bytes on HTTP 400 and 503 for all four protocols, and on a network error;
+- a stream that returns HTTP 200 and then ends in an error;
+- error-body truncation;
+- success, and a successful `pause_turn` sub-request;
+- cancellation, and a consumer that closes early;
+- off-loop execution and failure isolation;
+- retention around active and orphaned attempts;
+- export safety, and concurrent requests.
+
+`tests/test_vibey_agent.py::test_a_turns_failed_model_request_is_kept_with_its_session_and_turn` covers the Vibey
+wiring, and `tests/test_cli_model_requests.py` covers the CLI. Every test writes under its own temporary home.
diff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.py
index f0b9e56e2..994f0c854 100644
--- a/modules/agents/vibey/agent.py
+++ b/modules/agents/vibey/agent.py
@@ -62,6 +62,7 @@ from core.agent_core.agent.recovery import settle_open_calls
from core.agent_core.harness.context import ContextConfig
from core.agent_core.harness.projection import open_tool_calls
from core.agent_core.hosted_continuations import pending_hosted
+from core.agent_core.ai.request_artifacts import RequestArtifactStore, capture_model_requests
from core.agent_core.ai.transform import in_flight_position
from core.agent_core.tools.base import CallInstance
from core.agent_core.tools.jobs import call_instance
@@ -267,6 +268,11 @@ class VibeyAgent(BaseAgent):
state = Path(state_dir) if state_dir is not None else paths.get_state_dir() / "agent_core"
self._state_dir = state
self.media = MediaSnapshots(self._engine, state / "media")
+ # The exact bytes of every model request a Turn sends, kept when it does not succeed (``request_artifacts``).
+ self.request_artifacts = RequestArtifactStore(state / "model-requests")
+ from vibe import __version__
+
+ self._version = __version__
self.store = AdapterTranscriptStore(
SQLiteTranscriptStore(self._engine, render=self._display_source),
self._engine,
@@ -318,7 +324,10 @@ class VibeyAgent(BaseAgent):
turn = _Run(request, session_id, turn_id, self._instance)
async with self._held(session_id, run=turn) as runtime:
try:
- await self._run_turn(runtime, turn, input_id)
+ with capture_model_requests(
+ self.request_artifacts, session_id=session_id, turn_id=turn_id, version=self._version
+ ):
+ await self._run_turn(runtime, turn, input_id)
except Exception as error:
if turn.settled:
# Raised during or after settlement (its emits, or a failure notice): the
diff --git a/tests/agent_core/ai/test_request_artifacts.py b/tests/agent_core/ai/test_request_artifacts.py
new file mode 100644
index 000000000..63b50d625
--- /dev/null
+++ b/tests/agent_core/ai/test_request_artifacts.py
@@ -0,0 +1,828 @@
+"""Failed model request artifacts (``core/agent_core/ai/request_artifacts.py``).
+
+Inside a capture scope every model request ``drive_sse_stream`` sends is written before it goes out, as the exact
+``httpx.Request.content``. A semantically successful one is removed; every other ending is kept with typed facts
+and the raw response read. Outside a scope nothing is written.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import subprocess
+import sys
+import threading
+from contextlib import aclosing
+from dataclasses import replace
+from pathlib import Path
+from typing import Any, Callable
+
+import httpx
+import pytest
+
+from core.agent_core.ai import request_artifacts
+from core.agent_core.ai.provider import Done, ModelEndpoint, ModelRequest, ProviderError
+from core.agent_core.ai.registry import create_adapter
+from core.agent_core.ai.request_artifacts import (
+ META_FILE,
+ REQUEST_FILE,
+ RESPONSE_FILE,
+ STREAM_HEAD_BYTES,
+ STREAM_TAIL_BYTES,
+ RequestArtifactStore,
+ capture_model_requests,
+)
+from core import private_fs
+from core.agent_core.cancel import CancelToken
+from core.agent_core.messages import TextBlock, UserMessage
+from tests.agent_core.ai.test_hosted_pause_turn import _request as _anthropic_hub_request
+from tests.agent_core.ai.test_hosted_pause_turn import _response, _served, _text
+from tests.fake_pid_helpers import fake_pid
+
+SECRET = "sk-test-credential-never-stored"
+PROMPT = "private prompt text"
+ENDPOINTS = {
+ "anthropic": ("https://api.anthropic.invalid/v1", "claude-opus-5-5", "anthropic"),
+ "openai_responses": ("https://api.openai.invalid/v1", "gpt-5.6", "openai"),
+ "openai_chat": ("https://chat.invalid/v1", "chat-model", "openai"),
+ "google": ("https://gemini.invalid/v1beta?key=" + SECRET, "gemini-4-argon", "google"),
+}
+REFUSAL = {"type": "error", "error": {"type": "invalid_request_error", "message": f"refused: {PROMPT}"}}
+
+
+def _direct_request(protocol: str) -> ModelRequest:
+ base_url, model, provider = ENDPOINTS[protocol]
+ return ModelRequest(
+ endpoint=ModelEndpoint(protocol, base_url, model, SECRET, provider=provider, source_id="src_direct0001"), # type: ignore[arg-type]
+ system="system",
+ messages=(UserMessage((TextBlock(PROMPT),)),),
+ tools=(),
+ max_tokens=64,
+ cache="none",
+ )
+
+
+async def _run(
+ request: ModelRequest,
+ answer: Callable[[httpx.Request], httpx.Response],
+ store: RequestArtifactStore | None,
+ *,
+ gateway: bool = False,
+ cancel: CancelToken | None = None,
+ consume: Callable[[Any], Any] | None = None,
+) -> tuple[list[httpx.Request], list[Any]]:
+ sent: list[httpx.Request] = []
+
+ def transport(wire: httpx.Request) -> httpx.Response:
+ sent.append(wire)
+ return answer(wire)
+
+ async def stream() -> list[Any]:
+ async with httpx.AsyncClient(transport=httpx.MockTransport(transport)) as client:
+ adapter = create_adapter(request.endpoint.protocol, client=client, gateway=gateway)
+ events = []
+ async with aclosing(adapter.stream(request, cancel or CancelToken())) as stream:
+ async for event in stream:
+ events.append(event)
+ if consume is not None and consume(event):
+ break
+ return events
+
+ if store is None:
+ return sent, await stream()
+ with capture_model_requests(store, session_id="ses_artifacts", turn_id="trn_artifacts", version="9.9.9"):
+ events = await stream()
+ # A Stop or a closed stream does not wait for its artifact's write; it lands once the worker gets to it.
+ await _drain_worker()
+ return sent, events
+
+
+def _kept(store: RequestArtifactStore) -> list[dict[str, Any]]:
+ return store.entries()
+
+
+def store(tmp_path: Path) -> RequestArtifactStore:
+ return RequestArtifactStore(tmp_path / "state" / "model-requests")
+
+
[email protected]("protocol", sorted(ENDPOINTS))
[email protected]("status", [400, 503])
+async def test_a_refused_request_keeps_the_exact_bytes_sent_with_typed_facts_only(store, protocol, status):
+ """Every adapter goes through the shared driver: the kept body is the transport's own bytes, and the metadata
+ names the hop without its credential, the URL's query, or the provider's message."""
+
+ sent, events = await _run(_direct_request(protocol), lambda _: httpx.Response(status, json=REFUSAL), store)
+
+ assert isinstance(events[-1], ProviderError)
+ (meta,) = _kept(store)
+ directory = store.path(meta["id"])
+ assert (directory / REQUEST_FILE).read_bytes() == sent[0].content
+ assert json.loads((directory / RESPONSE_FILE).read_bytes()) == REFUSAL
+ assert meta["state"] == "failed"
+ assert meta["outcome"] == {
+ "kind": "http_error", "error_kind": events[-1].kind, "http_status": status, "exception_type": None,
+ }
+ assert meta["session_id"] == "ses_artifacts" and meta["turn_id"] == "trn_artifacts"
+ assert meta["avibe_version"] == "9.9.9"
+ assert meta["request"]["protocol"] == protocol and meta["request"]["model"] == ENDPOINTS[protocol][1]
+ assert meta["request"]["body_bytes"] == len(sent[0].content)
+ assert meta["response"]["read_to_end"] and not meta["response"]["truncated"]
+ text = (directory / META_FILE).read_text()
+ assert SECRET not in text and PROMPT not in text and "?" not in meta["request"]["url"]
+ for path in (store.root, directory, *(directory / name for name in (REQUEST_FILE, RESPONSE_FILE, META_FILE))):
+ assert private_fs.is_private(path, os.lstat(path).st_mode), path
+
+
+async def test_a_request_that_never_got_a_response_is_kept_as_a_network_error(store):
+ def answer(_: httpx.Request) -> httpx.Response:
+ raise httpx.ConnectError("connection refused")
+
+ sent, events = await _run(_direct_request("anthropic"), answer, store)
+
+ assert isinstance(events[-1], ProviderError)
+ (meta,) = _kept(store)
+ assert (store.path(meta["id"]) / REQUEST_FILE).read_bytes() == sent[0].content
+ assert not (store.path(meta["id"]) / RESPONSE_FILE).exists()
+ assert meta["outcome"]["kind"] == "network_error" and meta["outcome"]["exception_type"] == "ConnectError"
+
+
+async def test_a_stream_that_ends_in_an_error_after_http_200_is_kept_with_its_end(store):
+ """HTTP 200 alone is not success: a stream whose terminal is an error keeps the request and the stream's head and
+ tail, so the error event at its end survives a long response."""
+
+ filler = "x" * (STREAM_HEAD_BYTES + STREAM_TAIL_BYTES)
+ events = [
+ {"type": "message_start", "message": {"usage": {"input_tokens": 3}}},
+ {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},
+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": filler}},
+ {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}},
+ ]
+ body = "".join(f"data: {json.dumps(event)}\n\n" for event in events)
+
+ sent, result = await _run(
+ _anthropic_hub_request(), lambda _: httpx.Response(200, headers=_served(), text=body), store, gateway=True
+ )
+
+ assert isinstance(result[-1], ProviderError)
+ (meta,) = _kept(store)
+ kept = (store.path(meta["id"]) / RESPONSE_FILE).read_bytes()
+ assert meta["outcome"]["kind"] == "stream_error" and meta["outcome"]["http_status"] == 200
+ assert meta["response"]["truncated"] and meta["response"]["truncation"] == "middle"
+ assert meta["response"]["omitted_bytes"] == len(body.encode()) - len(kept)
+ assert kept.startswith(b'data: {"type": "message_start"')
+ assert kept.endswith(body.encode()[-200:]) and b"overloaded_error" in kept
+ assert meta["response"]["headers"]["x-avibe-served-hop"]
+ assert (store.path(meta["id"]) / REQUEST_FILE).read_bytes() == sent[0].content
+
+
+async def test_an_error_body_is_kept_whole_up_to_its_limit_and_the_cut_is_stated(store, monkeypatch):
+ monkeypatch.setattr(request_artifacts, "ERROR_BODY_LIMIT", 1024)
+ body = b"e" * 5000
+
+ await _run(_direct_request("openai_chat"), lambda _: httpx.Response(500, content=body), store)
+
+ (meta,) = _kept(store)
+ kept = (store.path(meta["id"]) / RESPONSE_FILE).read_bytes()
+ assert kept == body[:1024]
+ assert meta["response"]["truncated"] and meta["response"]["truncation"] == "end"
+ assert meta["response"]["read_bytes"] == 5000 and meta["response"]["omitted_bytes"] == 5000 - 1024
+
+
+async def test_a_successful_request_and_a_paused_sub_request_are_not_kept(store):
+ """A ``Done`` removes its request; so does an Anthropic ``pause_turn`` sub-request that ended normally, while a
+ continuation that then fails is kept on its own."""
+
+ def answer(number: int) -> httpx.Response:
+ if number == 1:
+ body = _response(_text("part 1"), stop_reason="pause_turn", input_tokens=10, output_tokens=1)
+ elif number == 2:
+ body = _response(_text("done"), stop_reason="end_turn", input_tokens=10, output_tokens=1)
+ else:
+ return httpx.Response(500, json={"type": "error", "error": {"type": "api_error", "message": "boom"}})
+ return httpx.Response(200, headers=_served(), text=body)
+
+ calls = iter(range(1, 10))
+ sent, events = await _run(_anthropic_hub_request(), lambda _: answer(next(calls)), store, gateway=True)
+
+ assert len(sent) == 2 and isinstance(events[-1], Done)
+ assert _kept(store) == []
+
+ calls = iter((1, 3))
+ sent, events = await _run(_anthropic_hub_request(), lambda _: answer(next(calls)), store, gateway=True)
+
+ assert len(sent) == 2 and isinstance(events[-1], ProviderError)
+ (meta,) = _kept(store)
+ assert (store.path(meta["id"]) / REQUEST_FILE).read_bytes() == sent[1].content
+
+
+async def test_a_cancelled_request_is_kept_as_cancelled(store):
+ cancel = CancelToken()
+
+ def answer(_: httpx.Request) -> httpx.Response:
+ cancel.cancel("stop")
+ return httpx.Response(200, headers=_served(), text=_response(_text("x"), stop_reason="end_turn", input_tokens=1, output_tokens=1))
+
+ _, events = await _run(_anthropic_hub_request(), answer, store, gateway=True, cancel=cancel)
+
+ assert isinstance(events[-1], ProviderError) and events[-1].kind == "aborted"
+ (meta,) = _kept(store)
+ assert meta["state"] == "cancelled" and meta["outcome"]["kind"] == "cancelled"
+
+
+async def test_a_request_whose_consumer_stopped_reading_is_unknown_to_every_reader(store, tmp_path):
+ """No outcome is known, and never a success: the entry is marked ``unknown`` on disk, so another process (the
+ CLI) sees the same state while the owner still runs, not ``pending``."""
+
+ body = _response(_text("partial"), stop_reason="end_turn", input_tokens=1, output_tokens=1)
+ sent, _ = await _run(
+ _anthropic_hub_request(),
+ lambda _: httpx.Response(200, headers=_served(), text=body),
+ store,
+ gateway=True,
+ consume=lambda event: not isinstance(event, (Done, ProviderError)),
+ )
+
+ (meta,) = _kept(store)
+ on_disk = json.loads((store.path(meta["id"]) / META_FILE).read_text())
+ assert on_disk["state"] == "unknown" and on_disk["outcome"]["kind"] == "unknown"
+ assert (store.path(meta["id"]) / REQUEST_FILE).read_bytes() == sent[0].content
+
+
+async def test_a_request_still_streaming_is_pending_to_every_reader(store):
+ """The other side of the same rule: while the stream is open the entry is active and reads ``pending``."""
+
+ body = _response(_text("partial"), stop_reason="end_turn", input_tokens=1, output_tokens=1)
+ seen: list[tuple[str, str, bool]] = []
+
+ def look(event: Any) -> bool:
+ if not seen:
+ (meta,) = _kept(store)
+ on_disk = json.loads((store.path(meta["id"]) / META_FILE).read_text())
+ # This process reads its active set; another process reads the disk and whether the owner lives.
+ seen.append((meta["state"], on_disk["state"], request_artifacts._owner_alive(on_disk["owner"])))
+ return False
+
+ await _run(
+ _anthropic_hub_request(), lambda _: httpx.Response(200, headers=_served(), text=body), store, gateway=True,
+ consume=look,
+ )
+
+ assert seen == [("pending", "pending", True)]
+ assert _kept(store) == []
+
+
+def _blocked_begin(monkeypatch) -> tuple[threading.Event, threading.Event]:
+ entered, release = threading.Event(), threading.Event()
+ begin = RequestArtifactStore.begin
+
+ def slow(self, meta, body):
+ entered.set()
+ release.wait(5)
+ return begin(self, meta, body)
+
+ monkeypatch.setattr(RequestArtifactStore, "begin", slow)
+ return entered, release
+
+
+async def _drain_worker() -> None:
+ await asyncio.get_running_loop().run_in_executor(request_artifacts._worker(), lambda: None)
+
+
[email protected]("landed_first", [False, True], ids=["cancelled-before-write-lands", "write-lands-first"])
+async def test_a_task_cancelled_while_its_pending_write_runs_sends_nothing_and_settles_it(store, monkeypatch, landed_first):
+ """Whichever comes second, the write landing or the cancellation, settles the attempt: never sent, never active,
+ and ``cancelled`` / ``not_sent`` for every reader."""
+
+ loop = asyncio.get_running_loop()
+ entered, release = threading.Event(), threading.Event()
+ tasks: list[asyncio.Task] = []
+ begin = RequestArtifactStore.begin
+
+ def slow(self, meta, body):
+ entered.set()
+ release.wait(5)
+ artifact_id = begin(self, meta, body)
+ if landed_first:
+ # Queued on the loop before the write's own result: the task sees the cancellation after it landed.
+ loop.call_soon_threadsafe(tasks[0].cancel)
+ return artifact_id
+
+ monkeypatch.setattr(RequestArtifactStore, "begin", slow)
+ sent: list[httpx.Request] = []
+ tasks.append(asyncio.create_task(
+ _run(_direct_request("anthropic"), lambda wire: sent.append(wire) or httpx.Response(400), store)
+ ))
+ await asyncio.to_thread(entered.wait, 5)
+ if not landed_first:
+ tasks[0].cancel()
+ await asyncio.sleep(0)
+ release.set()
+ with pytest.raises(asyncio.CancelledError):
+ await tasks[0]
+ await _drain_worker()
+
+ assert sent == []
+ (meta,) = _kept(store)
+ assert meta["state"] == "cancelled" and meta["outcome"]["kind"] == "not_sent"
+ assert meta["id"] not in request_artifacts._ACTIVE
+
+
+async def test_a_turn_stopped_while_its_pending_write_runs_sends_nothing(store, monkeypatch):
+ """A Stop (the CancelToken) that arrives during the pending write is seen before the send: no provider work."""
+
+ entered, release = _blocked_begin(monkeypatch)
+ cancel = CancelToken()
+ sent: list[httpx.Request] = []
+
+ async def stop() -> None:
+ await asyncio.to_thread(entered.wait, 5)
+ cancel.cancel("stop")
+ release.set()
+
+ stopping = asyncio.create_task(stop())
+ _, events = await _run(
+ _direct_request("anthropic"), lambda wire: sent.append(wire) or httpx.Response(400), store, cancel=cancel
+ )
+ await stopping
+
+ assert sent == [] and isinstance(events[-1], ProviderError) and events[-1].kind == "aborted"
+ (meta,) = _kept(store)
+ assert meta["state"] == "cancelled" and meta["outcome"]["kind"] == "not_sent"
+ assert meta["id"] not in request_artifacts._ACTIVE
+
+
+async def test_a_final_write_queued_behind_other_work_survives_its_tasks_cancellation(store):
+ """Cancelling the task that awaits an ending does not cancel the queued write: it still runs, and the attempt
+ is out of ``_ACTIVE`` from the moment it ended."""
+
+ gate = threading.Event()
+ blocker: list[Any] = []
+
+ def answer(_: httpx.Request) -> httpx.Response:
+ # Occupy the single worker so the ending's write has to queue behind it.
+ blocker.append(request_artifacts._worker().submit(gate.wait, 5))
+ return httpx.Response(400, json=REFUSAL)
+
+ task = asyncio.create_task(_run(_direct_request("anthropic"), answer, store))
+ while not blocker or request_artifacts._worker()._work_queue.qsize() == 0:
+ await asyncio.sleep(0.005)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ (pending,) = _kept(store)
+ assert pending["id"] not in request_artifacts._ACTIVE
+ gate.set()
+ await _drain_worker()
+
+ (meta,) = _kept(store)
+ assert meta["state"] == "failed" and meta["outcome"]["http_status"] == 400
+
+
+class _PrefixThenReset(httpx.AsyncByteStream):
+ def __init__(self, prefix: bytes) -> None:
+ self.prefix = prefix
+
+ async def __aiter__(self):
+ yield self.prefix
+ raise httpx.ReadError("connection reset")
+
+
+async def test_an_error_body_is_kept_as_far_as_classification_read_it_and_no_further(store):
+ """Capture only sees the reads the transport makes anyway: past the 64 KiB the error is classified by, nothing
+ more is read, so a body that would fail later changes neither the error nor its timing, and the artifact says
+ the body was not read to its end."""
+
+ message = "prompt is too long: 250000 tokens > 200000 maximum"
+ prefix = json.dumps({"type": "error", "error": {"type": "invalid_request_error", "message": message}}).encode()
+ prefix += b" " * (64 * 1024)
+
+ def answer(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(400, headers={"content-type": "application/json"}, stream=_PrefixThenReset(prefix))
+
+ _, plain = await _run(_direct_request("anthropic"), answer, None)
+ _, captured = await _run(_direct_request("anthropic"), answer, store)
+
+ assert isinstance(plain[-1], ProviderError)
+ assert (captured[-1].kind, captured[-1].message, captured[-1].status) == (
+ plain[-1].kind, plain[-1].message, plain[-1].status,
+ )
+ (meta,) = _kept(store)
+ assert meta["outcome"]["kind"] == "http_error" and meta["outcome"]["exception_type"] is None
+ assert not meta["response"]["read_to_end"] and not meta["response"]["truncated"]
+ assert (store.path(meta["id"]) / RESPONSE_FILE).read_bytes() == prefix
+
+
+async def test_nothing_is_written_outside_a_capture_scope(tmp_path):
+ await _run(_direct_request("anthropic"), lambda _: httpx.Response(400, json=REFUSAL), None)
+
+ assert not any(tmp_path.rglob("request.bin"))
+
+
+async def test_the_store_works_off_the_event_loop_and_its_failure_changes_no_outcome(tmp_path, monkeypatch, caplog):
+ """Artifact work runs on its own thread; a store that cannot be written leaves the request's events exactly as
+ they are without capture, and logs no payload."""
+
+ threads: list[str] = []
+ begin = RequestArtifactStore.begin
+
+ def record(self, meta, body):
+ threads.append(threading.current_thread().name)
+ return begin(self, meta, body)
+
+ monkeypatch.setattr(RequestArtifactStore, "begin", record)
+ working = RequestArtifactStore(tmp_path / "ok")
+ await _run(_direct_request("anthropic"), lambda _: httpx.Response(400, json=REFUSAL), working)
+ assert threads and all(name.startswith("avibe-request-artifacts") for name in threads)
+ assert threading.current_thread().name not in threads
+
+ (tmp_path / "blocked").write_text("not a directory")
+ broken = RequestArtifactStore(tmp_path / "blocked")
+ body = _response(_text("ok"), stop_reason="end_turn", input_tokens=1, output_tokens=1)
+ answer = lambda _: httpx.Response(200, headers=_served(), text=body) # noqa: E731
+ _, plain = await _run(_anthropic_hub_request(), answer, None, gateway=True)
+ with caplog.at_level("WARNING", logger="core.agent_core.ai.request_artifacts"):
+ _, captured = await _run(_anthropic_hub_request(), answer, broken, gateway=True)
+
+ assert [type(event) for event in captured] == [type(event) for event in plain]
+ assert captured[-1].message.content == plain[-1].message.content
+ assert any("record a pending request" in record.getMessage() for record in caplog.records)
+ assert all(PROMPT not in record.getMessage() for record in caplog.records)
+
+
+def _write(store: RequestArtifactStore, *, created_at: str, size: int = 10, owner: dict | None = None,
+ state: str = "failed") -> str:
+ meta = {"state": state, "created_at": created_at, "owner": owner or {"pid": 0, "started": None}}
+ artifact_id = store.begin(meta, b"x" * size)
+ # Written as found on disk: not this process's active attempt, whatever its recorded state and owner.
+ request_artifacts._ACTIVE.discard(artifact_id)
+ return artifact_id
+
+
+def other_process():
+ process = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
+ try:
+ yield process.pid
+ finally:
+ process.kill()
+ process.wait()
+
+
+def test_retention_drops_expired_and_oldest_attempts_but_never_an_active_one(tmp_path, other_process):
+ store = RequestArtifactStore(tmp_path / "requests", retention_s=3600)
+ from datetime import datetime, timedelta, timezone
+
+ now = datetime.now(timezone.utc)
+ expired = _write(store, created_at=(now - timedelta(hours=2)).isoformat())
+ old = _write(store, created_at=(now - timedelta(minutes=30)).isoformat(), size=900)
+ new = _write(store, created_at=(now - timedelta(minutes=10)).isoformat(), size=900)
+ # Pending and owned by another live process: active, never removed, however old or over quota.
+ live = {"pid": other_process, "started": request_artifacts._process_start(other_process)}
+ active = _write(store, created_at=(now - timedelta(hours=5)).isoformat(), size=900, owner=live, state="pending")
+ # Pending but its owner is gone: unknown, never a success, and removable like any finished attempt.
+ orphan = _write(
+ store, created_at=(now - timedelta(minutes=20)).isoformat(), owner={"pid": fake_pid(), "started": 1.0},
+ state="pending",
+ )
+ # This process's own pending attempt that it no longer sends (``abandon``): unknown as well.
+ own = _write(
+ store, created_at=(now - timedelta(minutes=5)).isoformat(),
+ owner={"pid": os.getpid(), "started": request_artifacts._process_start(os.getpid())}, state="pending",
+ )
+
+ entries = {meta["id"]: meta for meta in store.entries()}
+ assert entries[active]["state"] == "pending"
+ assert entries[orphan]["state"] == "unknown" and entries[own]["state"] == "unknown"
+ # Room for exactly the newest finished attempts and the active one.
+ store.quota_bytes = sum(entries[key]["size_bytes"] for key in (active, new, own))
+
+ store.prune()
+
+ remaining = {meta["id"] for meta in store.entries()}
+ # Past retention it goes; over quota, the oldest finished ones go first; the active one stays though oldest.
+ assert remaining == {active, new, own}
+ assert expired not in remaining and old not in remaining and orphan not in remaining
+
+
+def test_an_attempt_is_read_only_from_the_store_and_exported_into_a_new_private_directory(tmp_path):
+ store = RequestArtifactStore(tmp_path / "requests")
+ artifact_id = _write(store, created_at=_meta_now()["created_at"])
+ destination = tmp_path / "export"
+
+ target = store.export(artifact_id, destination)
+
+ assert target == destination / artifact_id
+ assert (target / REQUEST_FILE).read_bytes() == b"x" * 10
+ for path in (target, *target.iterdir()):
+ assert private_fs.is_private(path, os.lstat(path).st_mode), path
+ with pytest.raises(FileExistsError):
+ store.export(artifact_id, destination)
+ link = tmp_path / "link"
+ link.symlink_to(tmp_path / "elsewhere", target_is_directory=True)
+ with pytest.raises(request_artifacts.ArtifactStoreError):
+ store.export(artifact_id, link)
+ for bad in ("../requests", "mr_x", f"{artifact_id}/../.."):
+ with pytest.raises(request_artifacts.ArtifactStoreError):
+ store.path(bad)
+
+
+async def test_concurrent_requests_each_keep_their_own_bytes(store):
+ async def one(protocol: str) -> tuple[list[httpx.Request], list[Any]]:
+ request = _direct_request(protocol)
+ request = replace(request, messages=(UserMessage((TextBlock(f"{PROMPT} {protocol}"),)),))
+ return await _run(request, lambda _: httpx.Response(400, json=REFUSAL), store)
+
+ results = await asyncio.gather(*(one(protocol) for protocol in sorted(ENDPOINTS)))
+
+ kept = {store.path(meta["id"]).joinpath(REQUEST_FILE).read_bytes() for meta in _kept(store)}
+ assert kept == {sent[0].content for sent, _ in results}
+
+
+def _meta_now(state: str = "pending") -> dict[str, Any]:
+ from datetime import datetime, timezone
+
+ return {"state": state, "created_at": datetime.now(timezone.utc).isoformat(),
+ "owner": {"pid": os.getpid(), "started": request_artifacts._process_start(os.getpid())}}
+
+
[email protected]("ending", ["failed", "not_sent", "unknown"])
+def test_every_kept_ending_applies_retention_and_never_removes_an_active_attempt(tmp_path, ending):
+ """With a quota smaller than any attempt, each kept ending removes what it can: older finished attempts and
+ itself, but never an attempt this process is still sending."""
+
+ store = RequestArtifactStore(tmp_path / "requests", quota_bytes=1)
+ _write(store, created_at=_meta_now()["created_at"])
+ active = store.begin(_meta_now(), b"in flight")
+ ending_id = store.begin(_meta_now(), b"ending")
+ try:
+ request_artifacts._release(ending_id) # as ``RequestAttempt._queue`` does before the write
+ if ending == "failed":
+ store.fail(ending_id, {"state": "failed", "outcome": {"kind": "http_error"}}, None)
+ else:
+ state = "cancelled" if ending == "not_sent" else "unknown"
+ store.close(ending_id, state=state, kind=ending)
+
+ assert {meta["id"] for meta in store.entries()} == {active}
+ finally:
+ request_artifacts._release(active)
+
+
+def test_a_process_with_only_successes_still_expires_old_attempts_at_its_writes(tmp_path, monkeypatch):
+ """No timer: retention runs at the store's writes, and at the first one after the maintenance interval a
+ successful request's removal also removes what has expired."""
+
+ clock = [1000.0]
+ monkeypatch.setattr(request_artifacts, "_monotonic", lambda: clock[0])
+ store = RequestArtifactStore(tmp_path / "requests", retention_s=3600)
+ expired = _write(store, created_at="2026-01-01T00:00:00+00:00")
+ first = store.begin(_meta_now(), b"ok")
+ store.succeed(first)
+ # Within the interval since the last run (the first write's): kept for now.
+ assert expired in {meta["id"] for meta in store.entries()}
+
+ clock[0] += request_artifacts.MAINTENANCE_INTERVAL_S
+ second = store.begin(_meta_now(), b"ok")
+ store.succeed(second)
+
+ assert store.entries() == []
+
+
+async def test_waiting_for_the_artifact_write_never_counts_as_provider_silence(tmp_path, monkeypatch):
+ """The silence policy is decided before the artifact's final write is awaited: an error just inside the silence
+ bound keeps its recovery permissions even when the write takes longer than what is left of the bound."""
+
+ from core.agent_core.ai import _common
+
+ clock = [5000.0]
+
+ class Clock:
+ def __getattr__(self, name: str) -> Any:
+ import time
+
+ return getattr(time, name)
+
+ @staticmethod
+ def monotonic() -> float:
+ return clock[0]
+
+ monkeypatch.setattr(_common, "time", Clock())
+ fail = RequestArtifactStore.fail
+
+ def slow_fail(self, *args, **kwargs):
+ clock[0] += 10 # the worker's write, past the rest of the bound
+ return fail(self, *args, **kwargs)
+
+ monkeypatch.setattr(RequestArtifactStore, "fail", slow_fail)
+
+ def answer(_: httpx.Request) -> httpx.Response:
+ clock[0] += _common.PROVIDER_SILENCE_TIMEOUT_S - 1
+ return httpx.Response(503, json={"type": "error", "error": {"type": "overloaded_error", "message": "busy"}})
+
+ _, plain = await _run(_direct_request("anthropic"), answer, None)
+ _, captured = await _run(_direct_request("anthropic"), answer, RequestArtifactStore(tmp_path / "requests"))
+
+ assert plain[-1].retryable or plain[-1].continuable
+ assert (captured[-1].retryable, captured[-1].continuable) == (plain[-1].retryable, plain[-1].continuable)
+
+
[email protected]("chunks", [[3 * STREAM_TAIL_BYTES], [STREAM_TAIL_BYTES // 3 + 7] * 7, [10, 3 * STREAM_TAIL_BYTES, 5]],
+ ids=["one-large-chunk", "many-chunks", "large-between-small"])
+def test_a_streams_kept_end_stays_within_its_bound_whatever_the_chunking(chunks):
+ capture = request_artifacts.ResponseCapture()
+ capture.response(200, {})
+ stream = bytes(index % 251 for index in range(STREAM_HEAD_BYTES + sum(chunks)))
+ capture.feed(stream[:STREAM_HEAD_BYTES])
+ offset = STREAM_HEAD_BYTES
+ for size in chunks:
+ capture.feed(stream[offset:offset + size])
+ offset += size
+ assert capture._tail_size <= STREAM_TAIL_BYTES and sum(map(len, capture._tail)) == capture._tail_size
+
+ kept = capture.body()
+ assert kept == stream[:STREAM_HEAD_BYTES] + stream[-STREAM_TAIL_BYTES:]
+ summary = capture.summary()
+ assert summary["captured_bytes"] == len(kept)
+ assert summary["omitted_bytes"] == len(stream) - len(kept) and summary["truncation"] == "middle"
+
+
+
+# -- Stop through the Agent loop's real owner (``RunScope.call``) while the artifact worker is held ------------------
+
+
+class _Held:
+ """The artifact worker held by a gate, as a stalled filesystem would hold it."""
+
+ def __init__(self) -> None:
+ self.gate = threading.Event()
+ self.blocker: Any = None
+
+ def hold(self) -> None:
+ self.blocker = request_artifacts._worker().submit(self.gate.wait, 30)
+
+ async def release(self) -> None:
+ self.gate.set()
+ await _drain_worker()
+
+
+async def _drive_in_run_scope(request: ModelRequest, answer, store, *, cancel: CancelToken, stop, ready):
+ """Read the adapter stream the way the Agent loop does, each step owned by ``RunScope.call``; ``stop`` is called
+ once ``ready()`` says the driver waits on the held worker."""
+
+ from core.agent_core.agent.lifecycle import RunAborted, RunScope
+
+ scope = RunScope(cancel)
+ events: list[Any] = []
+ async with httpx.AsyncClient(transport=httpx.MockTransport(answer)) as client:
+ adapter = create_adapter(request.endpoint.protocol, client=client, gateway=False)
+ with capture_model_requests(store, session_id="ses_artifacts", turn_id="trn_artifacts"):
+ stream = adapter.stream(request, cancel)
+ iterator = stream.__aiter__()
+
+ async def read() -> None:
+ while True:
+ try:
+ events.append(await scope.call(iterator.__anext__))
+ except StopAsyncIteration:
+ return
+
+ reading = asyncio.create_task(read())
+ while not ready() and not reading.done():
+ await asyncio.sleep(0.005)
+ assert not reading.done()
+ started = asyncio.get_running_loop().time()
+ await stop(reading)
+ try:
+ await asyncio.wait_for(reading, timeout=2)
+ except (asyncio.CancelledError, RunAborted):
+ pass
+ elapsed = asyncio.get_running_loop().time() - started
+ return events, elapsed
+
+
+class _Hanging(httpx.AsyncByteStream):
+ """A stream that sends its start and then nothing, as a slow model does."""
+
+ def __init__(self, first: bytes, started: threading.Event) -> None:
+ self.first = first
+ self.started = started
+
+ async def __aiter__(self):
+ yield self.first
+ self.started.set()
+ await asyncio.Event().wait()
+
+
[email protected]("stop_kind", ["cancel_token", "task_cancel"])
[email protected]("phase", ["pending_write", "streaming", "final_write"])
+async def test_a_stop_ends_at_once_while_the_artifact_worker_is_held(store, monkeypatch, stop_kind, phase):
+ """With the worker held (a stalled filesystem), a Stop through the loop's owner ends the read at once, in every
+ phase: a held pending write sends nothing; a stream cut mid-way only queues its ``unknown`` write; a held final
+ write is left to run. Once the worker is free, every write lands and nothing stays active."""
+
+ held = _Held()
+ sent: list[httpx.Request] = []
+ entered = threading.Event()
+ if phase == "pending_write":
+ begin = RequestArtifactStore.begin
+
+ def gated(self, meta, body):
+ entered.set()
+ held.gate.wait(30)
+ return begin(self, meta, body)
+
+ monkeypatch.setattr(RequestArtifactStore, "begin", gated)
+ ready = entered.is_set
+ else:
+ # The failure's write is queued behind the held worker.
+ ready = lambda: request_artifacts._worker()._work_queue.qsize() > 0 # noqa: E731
+
+ started = threading.Event()
+ if phase == "streaming":
+ ready = lambda: started.is_set() and held.blocker is not None # noqa: E731
+
+ def answer(wire: httpx.Request) -> httpx.Response:
+ sent.append(wire)
+ held.hold() # every later write queues behind this
+ if phase == "streaming":
+ first = b'data: {"type": "message_start", "message": {"usage": {"input_tokens": 1}}}\n\n'
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=_Hanging(first, started))
+ return httpx.Response(400, json=REFUSAL)
+
+ cancel = CancelToken()
+
+ async def stop(reading: asyncio.Task) -> None:
+ if stop_kind == "cancel_token":
+ cancel.cancel("stop")
+ else:
+ reading.cancel()
+
+ _, elapsed = await _drive_in_run_scope(
+ _direct_request("anthropic"), answer, store, cancel=cancel, stop=stop, ready=ready
+ )
+
+ assert elapsed < 1.5
+ await held.release()
+ (meta,) = _kept(store)
+ assert meta["id"] not in request_artifacts._ACTIVE
+ if phase == "pending_write":
+ assert sent == [] and meta["state"] == "cancelled" and meta["outcome"]["kind"] == "not_sent"
+ elif phase == "streaming":
+ # Cut by the task (``unknown``), or by the driver's own CancelToken check first (``cancelled``).
+ assert len(sent) == 1 and meta["state"] in {"unknown", "cancelled"}
+ else:
+ assert len(sent) == 1 and meta["state"] == "failed" and meta["outcome"]["http_status"] == 400
+
+
+async def test_a_consumer_that_closes_the_stream_never_waits_for_the_held_worker(store):
+ """A consumer's ``aclose`` queues the ``unknown`` write and returns: nothing in the driver's cleanup waits for
+ diagnostics. The write lands once the worker is free."""
+
+ held = _Held()
+ body = _response(_text("partial"), stop_reason="end_turn", input_tokens=1, output_tokens=1)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(
+ lambda _: httpx.Response(200, headers=_served(), text=body)
+ )) as client:
+ adapter = create_adapter("anthropic", client=client, gateway=True)
+ with capture_model_requests(store, session_id="ses_artifacts", turn_id="trn_artifacts"):
+ stream = adapter.stream(_anthropic_hub_request(), CancelToken())
+ await stream.__anext__()
+ held.hold()
+ await asyncio.wait_for(stream.aclose(), timeout=1)
+
+ await held.release()
+ (meta,) = _kept(store)
+ assert meta["state"] == "unknown" and meta["id"] not in request_artifacts._ACTIVE
+
+
+async def test_a_pending_write_that_stalls_past_its_bound_lets_the_request_go_untracked(store, monkeypatch):
+ """Diagnostics never hold a request back for long: past ``ARTIFACT_WAIT_S`` the request is sent without
+ waiting, its outcome is the same, and the late write lands as ``unknown`` / ``untracked``, never active."""
+
+ monkeypatch.setattr(request_artifacts, "ARTIFACT_WAIT_S", 0.05)
+ from core.agent_core.ai import _common
+
+ monkeypatch.setattr(_common, "ARTIFACT_WAIT_S", 0.05)
+ gate = threading.Event()
+ begin = RequestArtifactStore.begin
+
+ def stalled(self, meta, body):
+ gate.wait(30)
+ return begin(self, meta, body)
+
+ monkeypatch.setattr(RequestArtifactStore, "begin", stalled)
+
+ def answer(_: httpx.Request) -> httpx.Response:
+ # Sent while the write still stalls; it lands only now.
+ assert not gate.is_set()
+ gate.set()
+ return httpx.Response(400, json=REFUSAL)
+
+ sent, events = await _run(_direct_request("anthropic"), answer, store)
+
+ assert len(sent) == 1 and isinstance(events[-1], ProviderError) and events[-1].status == 400
+ (meta,) = _kept(store)
+ assert meta["state"] == "unknown" and meta["outcome"]["kind"] == "untracked"
+ assert meta["id"] not in request_artifacts._ACTIVE
diff --git a/tests/test_cli_model_requests.py b/tests/test_cli_model_requests.py
new file mode 100644
index 000000000..43fef8747
--- /dev/null
+++ b/tests/test_cli_model_requests.py
@@ -0,0 +1,90 @@
+"""``vibe model-requests``: list, show, and export the model requests Vibey kept (``request_artifacts``).
+
+The JSON on stdout names each request by its typed facts and never carries a request or response body; export
+copies one into a new private directory under the directory the caller names.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import stat
+import sys
+from datetime import datetime, timezone
+
+import pytest
+
+from config import paths
+from core.agent_core.ai.request_artifacts import RESPONSE_FILE, RequestArtifactStore, ResponseCapture
+from vibe import cli
+
+BODY = b'{"messages":[{"role":"user","content":"private prompt text"}]}'
+ERROR = b'{"error":{"message":"refused: private prompt text"}}'
+
+
+def _run(monkeypatch, capsys, *argv: str) -> tuple[int, dict]:
+ monkeypatch.setattr(sys, "argv", ["vibe", *argv])
+ with pytest.raises(SystemExit) as exc:
+ cli.main()
+ captured = capsys.readouterr()
+ assert b"private prompt" not in (captured.out + captured.err).encode()
+ return exc.value.code, json.loads(captured.out or captured.err)
+
+
+def kept() -> str:
+ store = RequestArtifactStore(paths.get_model_request_artifacts_dir())
+ meta = {
+ "state": "pending",
+ "created_at": datetime.now(timezone.utc).isoformat(),
+ "owner": {"pid": os.getpid(), "started": None},
+ "session_id": "ses_one",
+ "turn_id": "trn_one",
+ "request": {"protocol": "anthropic", "provider": "anthropic", "model": "claude-opus-5-5", "body_bytes": len(BODY)},
+ }
+ artifact_id = store.begin(meta, BODY)
+ capture = ResponseCapture()
+ capture.response(400, {"x-request-id": "relay-1", "authorization": "Bearer secret"})
+ capture.feed(ERROR)
+ capture.finish()
+ store.fail(artifact_id, {"state": "failed", "outcome": {"kind": "http_error", "error_kind": "invalid_request",
+ "http_status": 400}}, capture)
+ return artifact_id
+
+
+def test_list_and_show_name_a_kept_request_without_its_bodies(monkeypatch, capsys, kept):
+ code, listed = _run(monkeypatch, capsys, "model-requests", "list")
+
+ assert code == 0 and listed["pagination"]["has_more"] is False
+ (item,) = listed["model_requests"]
+ assert item["id"] == kept and item["state"] == "failed" and item["session_id"] == "ses_one"
+ assert item["outcome"] == "http_error" and item["http_status"] == 400 and item["request_bytes"] == len(BODY)
+
+ code, other = _run(monkeypatch, capsys, "model-requests", "list", "--session-id", "ses_other")
+ assert code == 0 and other["model_requests"] == []
+
+ code, shown = _run(monkeypatch, capsys, "model-requests", "show", kept)
+ assert code == 0
+ assert shown["model_request"]["response"]["headers"] == {"x-request-id": "relay-1"}
+ assert shown["files"]["request.bin"] == len(BODY) and shown["files"][RESPONSE_FILE] == len(ERROR)
+
+
+def test_export_copies_into_a_new_private_directory_and_refuses_to_overwrite(monkeypatch, capsys, kept, tmp_path):
+ destination = tmp_path / "exported"
+
+ code, exported = _run(monkeypatch, capsys, "model-requests", "export", kept, "--to", str(destination))
+
+ assert code == 0 and exported["path"] == str(destination / kept)
+ assert exported["files"] == ["meta.json", "request.bin", "response.bin"]
+ assert (destination / kept / "request.bin").read_bytes() == BODY
+ assert stat.S_IMODE(os.stat(destination / kept).st_mode) == 0o700
+
+ code, error = _run(monkeypatch, capsys, "model-requests", "export", kept, "--to", str(destination))
+ assert code == 1 and error["code"] == "model_request_export_exists"
+
+
[email protected]("artifact_id", ["../../etc", "mr_20261031T000000Z_000000000000"])
+def test_an_unknown_or_invalid_id_reads_nothing(monkeypatch, capsys, artifact_id):
+ code, error = _run(monkeypatch, capsys, "model-requests", "show", artifact_id)
+
+ assert code == 1 and error["code"] == "model_request_unavailable"
diff --git a/tests/test_cli_pagination.py b/tests/test_cli_pagination.py
index 7eee53c2c..02b105947 100644
--- a/tests/test_cli_pagination.py
+++ b/tests/test_cli_pagination.py
@@ -82,6 +82,7 @@ def test_all_collection_commands_share_bounded_pagination_contract() -> None:
("data", "query"),
("task", "list"),
("watch", "list"),
+ ("model-requests", "list"),
}
fixed_page_commands = {("skill", "list")}
parser = cli.build_parser()
diff --git a/tests/test_vibey_agent.py b/tests/test_vibey_agent.py
index 811738ab4..6f0c6cba0 100644
--- a/tests/test_vibey_agent.py
+++ b/tests/test_vibey_agent.py
@@ -5968,3 +5968,37 @@ async def test_a_final_whose_cited_text_is_all_silent_stays_silent(engine, sessi
assert not any(CHANGELOG in item for item in harness.controller.im_client.sent)
assert not any(CHANGELOG in (row["content_text"] or "") for row in harness.rows("result") + harness.rows("assistant"))
+
+
+async def test_a_turns_failed_model_request_is_kept_with_its_session_and_turn(engine, session, tmp_path, published):
+ """Production wiring: every model request a Vibey Turn sends is captured under the agent's state directory and
+ tagged with its Session and Turn; the successful Turn's request is gone, the refused one stays byte-exact."""
+ import httpx
+ from core.agent_core.ai.request_artifacts import REQUEST_FILE
+ from modules.agents.vibey.models import registry_providers
+ from tests.agent_core.ai import test_hosted_replay as replay
+
+ sent: list[bytes] = []
+ headers = {"content-type": "text/event-stream", "x-avibe-served-hop": json.dumps(
+ {"provider": "test-provider", "api": "anthropic", "model": "test-model", "source": replay.SOURCE}
+ )}
+
+ def gateway(request):
+ sent.append(request.content)
+ if len(sent) == 1:
+ return httpx.Response(200, headers=headers, text=replay._sse("anthropic", replay._ANSWERED["anthropic"]))
+ return httpx.Response(400, json={"type": "error", "error": {"type": "invalid_request_error", "message": "no"}})
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:
+ harness = _Harness(engine, tmp_path, "telegram", [], providers=registry_providers(media_loader=None, client=client))
+ await harness.agent.handle_message(harness.request("first"))
+ assert harness.agent.request_artifacts.entries() == []
+ failing = harness.request("second")
+ await harness.agent.handle_message(failing)
+
+ store = harness.agent.request_artifacts
+ assert store.root == tmp_path / "agent_core" / "model-requests"
+ (meta,) = store.entries()
+ assert meta["session_id"] == SESSION and meta["turn_id"] == _turn(failing.context)
+ assert meta["state"] == "failed" and meta["outcome"]["http_status"] == 400
+ assert (store.path(meta["id"]) / REQUEST_FILE).read_bytes() == sent[-1]
diff --git a/vibe/cli.py b/vibe/cli.py
index 507e723d3..719b4a7c5 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -6888,6 +6888,114 @@ def _wait_for_run_result(store: TaskExecutionStore, run_id: str, *, wait_timeout
time.sleep(0.25)
+def _model_request_store():
+ from core.agent_core.ai.request_artifacts import RequestArtifactStore
+
+ return RequestArtifactStore(paths.get_model_request_artifacts_dir())
+
+
+def _model_request_summary(meta: dict) -> dict:
+ """One kept model request, by its typed facts: never a body, header value it did not allow, or error message."""
+
+ request = meta.get("request") if isinstance(meta.get("request"), dict) else {}
+ outcome = meta.get("outcome") if isinstance(meta.get("outcome"), dict) else {}
+ return {
+ "id": meta.get("id"),
+ "state": meta.get("state"),
+ "created_at": meta.get("created_at"),
+ "finished_at": meta.get("finished_at"),
+ "session_id": meta.get("session_id"),
+ "turn_id": meta.get("turn_id"),
+ "protocol": request.get("protocol"),
+ "provider": request.get("provider"),
+ "model": request.get("model"),
+ "source_id": request.get("source_id"),
+ "outcome": outcome.get("kind"),
+ "error_kind": outcome.get("error_kind"),
+ "http_status": outcome.get("http_status"),
+ "request_bytes": request.get("body_bytes"),
+ "size_bytes": meta.get("size_bytes"),
+ }
+
+
+def _model_request_error(exc: Exception, *, help_command: str) -> int:
+ from core.agent_core.ai.request_artifacts import ArtifactStoreError
+
+ if isinstance(exc, ArtifactStoreError):
+ exc = TaskCliError(str(exc), code="model_request_unavailable", help_command=help_command)
+ _print_task_error(exc, help_command=help_command)
+ return 1
+
+
+def cmd_model_requests_list(args):
+ help_command = "vibe model-requests list --help"
+ try:
+ page_request = _page_request_from_args(args, help_command=help_command)
+ store = _model_request_store()
+ entries = store.entries()
+ if getattr(args, "session_id", None):
+ entries = [meta for meta in entries if meta.get("session_id") == args.session_id]
+ if getattr(args, "state", None):
+ entries = [meta for meta in entries if meta.get("state") == args.state]
+ result = page_sequence(entries, page_request)
+ command = ["vibe", "model-requests", "list"]
+ _add_optional_arg(command, "--session-id", getattr(args, "session_id", None))
+ _add_optional_arg(command, "--state", getattr(args, "state", None))
+ _print_cli_payload(
+ "model_requests",
+ directory=str(store.root),
+ model_requests=[_model_request_summary(meta) for meta in result.items],
+ **_paginated_fields(result, command=command),
+ )
+ return 0
+ except Exception as exc:
+ return _model_request_error(exc, help_command=help_command)
+
+
+def cmd_model_requests_show(args):
+ help_command = "vibe model-requests show --help"
+ try:
+ from core.agent_core.ai.request_artifacts import META_FILE, REQUEST_FILE, RESPONSE_FILE
+
+ store = _model_request_store()
+ meta = store.meta(args.request_id)
+ meta["state"] = store.state(meta)
+ directory = store.path(args.request_id)
+ files = {
+ name: (directory / name).stat().st_size
+ for name in (REQUEST_FILE, RESPONSE_FILE, META_FILE)
+ if (directory / name).is_file()
+ }
+ _print_cli_payload("model_request", model_request=meta, directory=str(directory), files=files)
+ return 0
+ except Exception as exc:
+ return _model_request_error(exc, help_command=help_command)
+
+
+def cmd_model_requests_export(args):
+ help_command = "vibe model-requests export --help"
+ try:
+ store = _model_request_store()
+ target = store.export(args.request_id, Path(args.to))
+ _print_cli_payload(
+ "model_request_export",
+ id=args.request_id,
+ path=str(target),
+ files=sorted(path.name for path in target.iterdir()),
+ )
+ return 0
+ except FileExistsError:
+ error = TaskCliError(
+ f"{Path(args.to).expanduser() / args.request_id} already exists",
+ code="model_request_export_exists",
+ hint="Export into another directory, or remove the earlier export first.",
+ help_command=help_command,
+ )
+ return _model_request_error(error, help_command=help_command)
+ except Exception as exc:
+ return _model_request_error(exc, help_command=help_command)
+
+
def cmd_runs_list(args):
try:
scope = _resolve_session_list_scope(args, help_command="vibe runs list --help")
@@ -17512,6 +17620,51 @@ def build_parser():
runs_cancel_parser.add_argument("run_id")
_add_json_noop(runs_cancel_parser)
+ model_requests_parser = subparsers.add_parser(
+ "model-requests",
+ help="Inspect model requests Vibey kept because they did not succeed",
+ description=(
+ "List, inspect, and export the exact bytes of Vibey model requests that failed, were cancelled, or "
+ "ended without a known outcome. Output never includes a request or response body; export copies one "
+ "into a private directory you choose."
+ ),
+ error_help_command="vibe model-requests --help",
+ )
+ model_requests_subparsers = model_requests_parser.add_subparsers(
+ dest="model_requests_command", metavar="{list,show,export}"
+ )
+ model_requests_subparsers.required = True
+ model_requests_list_parser = model_requests_subparsers.add_parser(
+ "list",
+ help="List kept model requests, newest first",
+ error_help_command="vibe model-requests list --help",
+ )
+ model_requests_list_parser.add_argument("--session-id", help="Only requests of this Session")
+ model_requests_list_parser.add_argument(
+ "--state", choices=["failed", "cancelled", "unknown", "pending"], help="Only requests in this state"
+ )
+ _add_pagination_args(model_requests_list_parser, help_command="vibe model-requests list --help")
+ _add_json_noop(model_requests_list_parser)
+ model_requests_show_parser = model_requests_subparsers.add_parser(
+ "show",
+ help="Show one kept model request's metadata",
+ error_help_command="vibe model-requests show --help",
+ )
+ model_requests_show_parser.add_argument("request_id")
+ _add_json_noop(model_requests_show_parser)
+ model_requests_export_parser = model_requests_subparsers.add_parser(
+ "export",
+ help="Copy one kept model request's files into DIR/<id>/",
+ description=(
+ "Copy request.bin, response.bin, and meta.json of one kept model request into a new private "
+ "directory DIR/<id>/. The files may hold prompts and tool output; keep them private."
+ ),
+ error_help_command="vibe model-requests export --help",
+ )
+ model_requests_export_parser.add_argument("request_id")
+ model_requests_export_parser.add_argument("--to", required=True, metavar="DIR", help="Directory to export into")
+ _add_json_noop(model_requests_export_parser)
+
harness_parser = subparsers.add_parser(
"harness",
help="Inspect unified Harness live state and anomalies",
@@ -19008,6 +19161,11 @@ _CLI_COMMAND_FLOORS: dict[tuple[str, ...], Optional[str]] = {
("skill", "load"): "editor",
("data", "query"): "editor",
("data", "skill-usage"): "editor",
+ # Kept model requests hold whole prompts, tool definitions and output of every Session, as raw bytes: Owner
+ # only, listing included.
+ ("model-requests", "list"): "owner",
+ ("model-requests", "show"): "owner",
+ ("model-requests", "export"): "owner",
("data", "retention"): "member",
# ``vibe mcp`` admits itself from raw argv (vibe/mcp_cli.py): discovery and
# calls at Editor like Skills, management Owner-only. This floor is reached
@@ -19249,6 +19407,14 @@ def _dispatch_parsed_command(parser: argparse.ArgumentParser, args) -> None:
if args.runs_command == "cancel":
sys.exit(cmd_runs_cancel(args))
parser.error("runs command is required")
+ if args.command == "model-requests":
+ if args.model_requests_command == "list":
+ sys.exit(cmd_model_requests_list(args))
+ if args.model_requests_command == "show":
+ sys.exit(cmd_model_requests_show(args))
+ if args.model_requests_command == "export":
+ sys.exit(cmd_model_requests_export(args))
+ parser.error("model-requests command is required")
if args.command == "harness":
if args.harness_command == "status":
sys.exit(cmd_harness_status(args))