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(vibey): save generated images, native and proxied, through a media sink, so history holds only their path (#2582)

Call White197a6a4f61d0
diff --git a/core/agent_core/ai/_common.py b/core/agent_core/ai/_common.py
index a8f5019ab..e7e570b3d 100644
--- a/core/agent_core/ai/_common.py
+++ b/core/agent_core/ai/_common.py
@@ -1699,10 +1699,15 @@ def required_only_tool(tools: list[Any]) -> str:
async def iter_sse_events(
response: httpx.Response,
cancel: CancelToken,
+ *,
+ max_line_size: int | 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. ``max_line_size`` overrides the
+ parser's default line cap; a stream allowed lines that long (a generated image's) is parsed off the controller
+ loop, because one event can be many MiB."""
- parser = SSEParser()
+ parser = SSEParser(max_line_size=max_line_size)
+ offload = max_line_size is not None
iterator = response.aiter_bytes().__aiter__()
while True:
if cancel.cancelled:
@@ -1717,9 +1722,9 @@ async def iter_sse_events(
break
if chunk is None:
return
- for event in parser.feed(chunk):
+ for event in await asyncio.to_thread(parser.feed, chunk) if offload else parser.feed(chunk):
yield event
- for event in parser.finish():
+ for event in await asyncio.to_thread(parser.finish) if offload else parser.finish():
yield event
@@ -1736,6 +1741,7 @@ async def drive_sse_stream(
resolver: ServedHopResolver | None,
gateway: bool,
translate: WireTranslator,
+ max_line_size: int | None = None,
) -> AsyncIterator[Any]:
"""Own the complete request/stream/terminal/cleanup lifecycle.
@@ -1812,7 +1818,7 @@ async def drive_sse_stream(
candidate = assembler.aborted(cancel.reason)
else:
assembler.set_origin(resolved_origin.origin, resolved_origin.verified, resolved_origin.source_id)
- async for item in translate(iter_sse_events(response, cancel)):
+ async for item in translate(iter_sse_events(response, cancel, max_line_size=max_line_size)):
if isinstance(item, (Done, ProviderError)):
candidate = item
break
diff --git a/core/agent_core/ai/hosted.py b/core/agent_core/ai/hosted.py
index c8a749f21..99187ee54 100644
--- a/core/agent_core/ai/hosted.py
+++ b/core/agent_core/ai/hosted.py
@@ -23,12 +23,15 @@ from core.agent_core.messages import (
Citation,
HostedAction,
HostedCost,
+ HostedImage,
HostedNative,
HostedRecord,
HostedSource,
HostedToolBlock,
ToolCallBlock,
)
+from core.agent_core.tools.read import MAX_INLINE_IMAGE_BYTES
+from core.agent_core.tools.truncate import format_size
#: xAI reports a response's cost in ticks of 1e-10 USD (``usage.cost_in_usd_ticks``).
_USD_PER_TICK = 1e-10
@@ -75,18 +78,29 @@ def responses_hosted_tool(item: Mapping[str, Any]) -> Optional[str]:
kind = item.get("type")
if kind == "web_search_call":
return "web_search"
+ if kind == "image_generation_call":
+ return "image_generation"
if kind == "custom_tool_call" and str(item.get("name") or "").startswith("x_"):
return "x_search"
return None
def responses_hosted_block(
- item: Mapping[str, Any], *, source_id: str, call_id: str, finished: bool = True
+ item: Mapping[str, Any],
+ *,
+ source_id: str,
+ call_id: str,
+ finished: bool = True,
+ image: HostedImage | None = None,
+ image_error: str | None = None,
) -> HostedToolBlock:
- """One Responses hosted-call item (a ``web_search_call``, or xAI's X-search ``custom_tool_call``) as its block.
+ """One Responses hosted-call item (a ``web_search_call``, an ``image_generation_call``, or xAI's X-search
+ ``custom_tool_call``) as its block.
``call_id`` names the block when the item carries no id of its own. An item that has only been added
- (``finished`` false) holds the call's place in the output order as a pending call.
+ (``finished`` false) holds the call's place in the output order as a pending call. A generated image is the file
+ the adapter saved, ``image``: the item's base64 ``result`` is never kept (§7.3), and a finished call that saved no
+ image failed, for ``image_error`` when the adapter knows why.
"""
tool = responses_hosted_tool(item)
@@ -103,7 +117,17 @@ def responses_hosted_block(
else:
record_status = "pending"
error = _item_error(item, record_status) if record_status in ("failed", "incomplete") else None
- if tool == "web_search":
+ images: tuple[HostedImage, ...] | None = None
+ if tool == "image_generation":
+ if record_status == "completed" and image is None:
+ record_status, error = "failed", bounded_error(image_error or "the provider returned no image")
+ images = (image,) if image is not None and record_status == "completed" else ()
+ action, sources = generate_action(item), ()
+ # The transcript's copy names the saved file in place of the base64 image.
+ item = {key: value for key, value in item.items() if key != "result"}
+ if images:
+ item["result"] = images[0].path
+ elif tool == "web_search":
action, sources = _web_search_action(item)
else:
action, sources = _x_search_action(item), ()
@@ -111,11 +135,33 @@ def responses_hosted_block(
id=_text(item.get("id")) or _text(item.get("call_id")) or call_id,
tool=tool, # type: ignore[arg-type]
action=action,
- record=HostedRecord(status=record_status, error=error, sources=sources), # type: ignore[arg-type]
+ record=HostedRecord(status=record_status, error=error, sources=sources, images=images), # type: ignore[arg-type]
native=HostedNative(source_id=source_id, payload=_payload(item)),
)
+def generate_action(item: Mapping[str, Any]) -> HostedAction:
+ """An image generation as it ran: the prompt the provider rendered (its revision of the model's), and the output's
+ resolved size and quality, which pricing reads (§7.3, item 22). ``item`` is a native ``image_generation_call`` or
+ a proxy executor's ``generation`` facts, which carry the same names."""
+
+ return HostedAction(
+ "generate",
+ prompt=_text(item.get("revised_prompt")),
+ size=_text(item.get("size")),
+ quality=_text(item.get("quality")),
+ )
+
+
+def image_dimensions(size: Any) -> tuple[int | None, int | None]:
+ """An output's ``WIDTHxHEIGHT`` size as two numbers, or nothing for ``auto`` or a size that is not one."""
+
+ width, separator, height = str(size or "").partition("x")
+ if separator and width.isdigit() and height.isdigit() and int(width) > 0 and int(height) > 0:
+ return int(width), int(height)
+ return None, None
+
+
def _web_search_action(item: Mapping[str, Any]) -> tuple[HostedAction, tuple[HostedSource, ...]]:
action = item.get("action")
action = action if isinstance(action, Mapping) else {}
@@ -287,14 +333,32 @@ def record_text(
lines.append("Also searched: " + "; ".join(json.dumps(item, ensure_ascii=False) for item in further_queries))
lines.extend(notes)
lines.extend(_numbered(record.sources))
+ for image in record.images or ():
+ lines.extend(_image_lines(image))
if cited:
lines.append("Posts cited in the answer:")
lines.extend(_numbered(cited))
- if record.status == "completed" and not record.sources and not cited and not notes:
+ if record.status == "completed" and not record.sources and not record.images and not cited and not notes:
lines.append("No results were returned.")
return "\n".join(lines)
+def _image_lines(image: HostedImage) -> list[str]:
+ """A generated image as the model sees it: where it is saved and what it is, never the image itself (§7.3). The
+ model opens the file with ``read`` to look at it, unless it is over ``read``'s inline limit."""
+
+ facts = [f"{image.width}×{image.height}" if image.width and image.height else None, image.mime]
+ if image.bytes is not None:
+ facts.append(format_size(image.bytes))
+ lines = [f"Image saved: {image.path} ({', '.join(fact for fact in facts if fact)})"]
+ if image.bytes is not None and image.bytes > MAX_INLINE_IMAGE_BYTES:
+ lines.append(
+ f" It is over the {format_size(MAX_INLINE_IMAGE_BYTES)} inline image limit, so read cannot show it. "
+ "The user sees it."
+ )
+ return lines
+
+
def _numbered(sources: Sequence[HostedSource]) -> list[str]:
lines: list[str] = []
for number, source in enumerate(sources, 1):
diff --git a/core/agent_core/ai/openai_responses.py b/core/agent_core/ai/openai_responses.py
index c82b1b332..62a573888 100644
--- a/core/agent_core/ai/openai_responses.py
+++ b/core/agent_core/ai/openai_responses.py
@@ -9,15 +9,18 @@ Payload and stream rules are ported from tau's ``tau_ai/openai_compatible.py``
from __future__ import annotations
+import asyncio
import copy
import json
from collections.abc import AsyncIterator, Mapping
+from dataclasses import replace
from typing import Any
import httpx
from core.agent_core.ai.hosted import (
citation,
+ image_dimensions,
reported_cost,
reported_counts,
responses_hosted_block,
@@ -51,15 +54,19 @@ from core.agent_core.ai._common import (
)
from core.agent_core.ai.provider import (
Done,
+ HostedToolRoute,
MediaLoader,
+ MediaSink,
ModelRequest,
ProviderAdapter,
ProviderError,
TextDelta,
)
from core.agent_core.cancel import CancelToken
+from core.agent_core.ai.sse import DEFAULT_MAX_PENDING_EVENT_SIZE
from core.agent_core.messages import (
AssistantMessage,
+ HostedImage,
HostedToolBlock,
TextBlock,
ThinkingBlock,
@@ -68,6 +75,19 @@ from core.agent_core.messages import (
UserMessage,
)
+#: A preview OpenAI streams while an image is drawn (``partial_images``); only the done item's image is kept.
+_PARTIAL_IMAGE_EVENT = "response.image_generation_call.partial_image"
+#: Every image one response streams, previews and finals, decoded (plan item 25). The terminal response repeats every
+#: final image in one event, so the budget is what one event can carry as base64, less a margin for the rest of it.
+IMAGE_BYTES_PER_RESPONSE = (DEFAULT_MAX_PENDING_EVENT_SIZE - 1024 * 1024) * 3 // 4
+#: Image events beyond the declared previews and the final, per image call (plan item 25).
+_IMAGE_EVENT_MARGIN = 2
+#: An event longer than this (a generated image's) is parsed off the controller loop.
+_INLINE_PARSE_CHARS = 1024 * 1024
+#: The line cap of a stream that may carry a generated image: the whole event cap, as one image line can be several
+#: MiB of base64 (§7.5). Other streams keep the default line cap.
+IMAGE_STREAM_LINE_BYTES = DEFAULT_MAX_PENDING_EVENT_SIZE
+
_KNOWN_RESPONSE_EVENTS = frozenset(
{
"response.created",
@@ -287,6 +307,7 @@ class OpenAIResponsesAdapter(ProviderAdapter):
client: httpx.AsyncClient | None = None,
*,
media_loader: MediaLoader | None = None,
+ media_sink: MediaSink | None = None,
served_hop_resolver: ServedHopResolver | None = None,
gateway: bool = False,
) -> None:
@@ -294,6 +315,7 @@ class OpenAIResponsesAdapter(ProviderAdapter):
self._client = client or httpx.AsyncClient(timeout=None, trust_env=not gateway)
self._owns_client = client is None
self._media_loader = media_loader
+ self._media_sink = media_sink
self._served_hop_resolver = served_hop_resolver
self._gateway = gateway
@@ -344,6 +366,7 @@ class OpenAIResponsesAdapter(ProviderAdapter):
refusal = False
# The hosted tools this request declared natively: only their items become hosted calls (§4.2).
hosted = frozenset(native_hosted_tools(request))
+ images = _ImageBudget(native_hosted_tools(request).get("image_generation"))
try:
wire = wire_request(request, transformed_messages, gateway=self._gateway, loaded_images=loaded_images)
@@ -357,7 +380,24 @@ class OpenAIResponsesAdapter(ProviderAdapter):
return
if not event.data or event.data == "[DONE]":
continue
- chunk = json_object(event.data)
+ # A preview of an image still being drawn is never kept: named as one, its base64 is not even
+ # parsed. Named or known by its JSON type, it counts against the response's image budget.
+ named_preview = event.event == _PARTIAL_IMAGE_EVENT
+ if named_preview:
+ chunk = None
+ elif len(event.data) > _INLINE_PARSE_CHARS:
+ # A generated image's event is many MiB: parsed off the controller loop.
+ chunk = await asyncio.to_thread(json_object, event.data)
+ else:
+ chunk = json_object(event.data)
+ if named_preview or (chunk is not None and chunk.get("type") == _PARTIAL_IMAGE_EVENT):
+ exceeded = images.charge(len(event.data))
+ if exceeded is not None:
+ terminal = assembler.terminal(assembler.error(exceeded, kind="invalid_request"))
+ if terminal is not None:
+ yield terminal
+ return
+ continue
if chunk is None:
terminal = assembler.terminal(
assembler.error(
@@ -648,6 +688,8 @@ class OpenAIResponsesAdapter(ProviderAdapter):
assembler.ensure_text_slot(output_index)
else:
# A hosted call takes its place in the output order now; its done item fills it in.
+ if responses_hosted_tool(item) == "image_generation":
+ images.started()
_add_hosted_call(assembler, item, output_index, hosted, finished=False)
elif event_type == "response.reasoning_summary_text.done":
continue
@@ -938,6 +980,22 @@ class OpenAIResponsesAdapter(ProviderAdapter):
end = assembler.block_end(output_index)
if end is not None:
yield end
+ elif (
+ responses_hosted_tool(item) == "image_generation"
+ and "image_generation" in hosted
+ and assembler.source_id is not None
+ ):
+ encoded = item.get("result")
+ exceeded = images.charge(len(encoded) if isinstance(encoded, str) else 0)
+ if exceeded is not None:
+ terminal = assembler.terminal(assembler.error(exceeded, kind="invalid_request"))
+ if terminal is not None:
+ yield terminal
+ return
+ image, failure = await _saved_image(self._media_sink, item)
+ _add_hosted_call(
+ assembler, item, output_index, hosted, image=image, image_error=failure
+ )
else:
_add_hosted_call(assembler, item, output_index, hosted)
elif event_type in {"response.completed", "response.incomplete"}:
@@ -1301,6 +1359,8 @@ class OpenAIResponsesAdapter(ProviderAdapter):
resolver=self._served_hop_resolver,
gateway=self._gateway,
translate=translate,
+ # A generated image arrives as one base64 line of several MiB (§7.5).
+ max_line_size=IMAGE_STREAM_LINE_BYTES if "image_generation" in hosted else None,
)
unavailable = False
try:
@@ -1583,11 +1643,15 @@ def _add_hosted_call(
*,
finished: bool = True,
backfill: bool = False,
+ image: HostedImage | None = None,
+ image_error: str | None = None,
) -> None:
"""An output item of a hosted tool the request declared natively, as its hosted call at its output index (§4.2):
pending when only added, filled in when done. A call the terminal response backfills keeps a block it has.
A response whose served Source is unknown keeps no hosted call: its native payload could never be replayed.
+ A generated image is ``image``, the file its done item was saved to. The terminal response repeats that image,
+ and its copy is never decoded (§7.5), so a call it alone finishes saved none.
"""
tool = responses_hosted_tool(item)
@@ -1596,14 +1660,68 @@ def _add_hosted_call(
current = assembler.hosted_block_at(output_index)
if backfill and current is not None and current.record.status != "pending":
return
+ if backfill and tool == "image_generation":
+ image_error = "the image was not streamed before the response ended"
assembler.hosted_block(
output_index,
responses_hosted_block(
- item, source_id=assembler.source_id, call_id=f"hosted_{output_index}", finished=finished
+ item,
+ source_id=assembler.source_id,
+ call_id=f"hosted_{output_index}",
+ finished=finished,
+ image=image,
+ image_error=image_error,
),
)
+class _ImageBudget:
+ """The image data one response may stream (plan item 25): per image call, the previews its declaration asks for
+ and the final, plus a small margin; and a cumulative decoded size. Exceeding either ends the stream as an error,
+ so a misbehaving provider cannot stream images without bound. The terminal response's duplicate is not counted:
+ it is never decoded."""
+
+ def __init__(self, route: HostedToolRoute | None) -> None:
+ partials = (route.declaration or {}).get("partial_images") if route is not None else None
+ self._per_call = (partials if isinstance(partials, int) and partials > 0 else 0) + 1
+ self._calls = 0
+ self._events = 0
+ self._bytes = 0
+
+ def started(self) -> None:
+ self._calls += 1
+
+ def charge(self, encoded_length: int) -> str | None:
+ """Count one preview or final of ``encoded_length`` base64 characters; why the stream must end, if it must."""
+
+ self._events += 1
+ self._bytes += encoded_length * 3 // 4
+ if self._events > self._per_call * self._calls + _IMAGE_EVENT_MARGIN:
+ return "the provider streamed more images than the response asked for"
+ if self._bytes > IMAGE_BYTES_PER_RESPONSE:
+ return "the provider streamed more image data than one response may carry"
+ return None
+
+
+async def _saved_image(sink: MediaSink | None, item: Mapping[str, Any]) -> tuple[HostedImage | None, str | None]:
+ """The file a done ``image_generation_call`` was saved to, with its output size, or why there is none (§7.3).
+
+ Only a completed call's image is saved: that is the only record that lists one, so no file is written that no
+ record names."""
+
+ encoded = item.get("result")
+ if item.get("status") != "completed" or not isinstance(encoded, str) or not encoded:
+ return None, None
+ if sink is None:
+ return None, "nothing here can keep a generated image"
+ try:
+ image = await sink.save_image(encoded)
+ except (ValueError, OSError) as error:
+ return None, f"the image could not be saved: {error}"
+ width, height = image_dimensions(item.get("size"))
+ return replace(image, width=width, height=height), None
+
+
def _add_message_citations(assembler: StreamAssembler, index: int, item: Mapping[str, Any]) -> None:
"""``url_citation`` annotations on a message's text parts, as citations into the text the parts make together."""
diff --git a/core/agent_core/ai/provider.py b/core/agent_core/ai/provider.py
index 80c053aef..89647e109 100644
--- a/core/agent_core/ai/provider.py
+++ b/core/agent_core/ai/provider.py
@@ -11,7 +11,7 @@ from dataclasses import dataclass, field
from typing import Any, AsyncIterator, Literal, Mapping, Optional, Protocol, Union
from core.agent_core.cancel import CancelToken
-from core.agent_core.messages import AssistantMessage, Message, ProtocolName
+from core.agent_core.messages import AssistantMessage, HostedImage, Message, ProtocolName
from core.agent_core.tools.base import ToolSpec
ErrorKind = Literal[
@@ -118,6 +118,19 @@ class MediaLoader(Protocol):
...
+class MediaSink(Protocol):
+ """Supplied by the adapter layer; keeps a generated image as a local file (``vibey-hosted-tools.md`` §7.3).
+
+ The image never enters a message or the model's context: only its path, in the call's record.
+ """
+
+ async def save_image(self, encoded: str) -> HostedImage:
+ """Decode base64 ``encoded``, store it, and return its record: the file's absolute path, its type as its
+ bytes show it, and its size. Raises ``ValueError`` when ``encoded`` is not a supported image in base64, and
+ ``OSError`` when it cannot be stored."""
+ ...
+
+
@dataclass(frozen=True)
class ModelRequest:
endpoint: ModelEndpoint
diff --git a/core/agent_core/messages.py b/core/agent_core/messages.py
index f2b7fbd0c..e1f966077 100644
--- a/core/agent_core/messages.py
+++ b/core/agent_core/messages.py
@@ -301,19 +301,20 @@ class HostedSource:
@dataclass(frozen=True)
class HostedImage:
- """A generated image saved as a local file; the model sees only this record."""
+ """A generated image saved as a local file; the model sees only this record. ``bytes`` is the file's size."""
path: str
mime: str
width: Optional[int] = None
height: Optional[int] = None
+ bytes: Optional[int] = None
def __post_init__(self) -> None:
_require_text(self.path, "image path")
_require(self.mime, str, "image mime")
if self.mime not in IMAGE_MIME_TYPES:
raise ValueError(f"unsupported image type: {self.mime}")
- for name in ("width", "height"):
+ for name in ("width", "height", "bytes"):
value = getattr(self, name)
_require(value, int, f"image {name}", optional=True)
if value is not None and value < 1:
@@ -466,14 +467,18 @@ class ProxyExecution:
@dataclass(frozen=True)
class HostedResult:
- """``ToolResultMessage.hosted``: the canonical record of a proxied hosted call."""
+ """``ToolResultMessage.hosted``: the canonical record of a proxied hosted call. ``action`` is what the executor
+ reports it did, where that differs from the model's request: for ``image_generation``, the prompt it rendered and
+ the output's resolved size and quality, as a native call's block carries them."""
record: HostedRecord
execution: Optional[ProxyExecution] = None
+ action: Optional[HostedAction] = None
def __post_init__(self) -> None:
_require(self.record, HostedRecord, "hosted record")
_require(self.execution, ProxyExecution, "proxy execution", optional=True)
+ _require(self.action, HostedAction, "hosted result action", optional=True)
if self.execution is None and self.record.status != "failed":
raise ValueError("a hosted result without an execution is a failed record")
@@ -673,6 +678,7 @@ def _record_to_dict(record: HostedRecord) -> dict[str, Any]:
item: dict[str, Any] = {"path": image.path, "mime": image.mime}
_put(item, "width", image.width)
_put(item, "height", image.height)
+ _put(item, "bytes", image.bytes)
images.append(item)
out["images"] = images
return out
@@ -683,7 +689,9 @@ def _record_from_dict(data: Any) -> HostedRecord:
images = None
if "images" in f:
images = tuple(
- HostedImage(**_read(item, "hosted image", {"path": str, "mime": str}, {"width": int, "height": int}))
+ HostedImage(
+ **_read(item, "hosted image", {"path": str, "mime": str}, {"width": int, "height": int, "bytes": int})
+ )
for item in f["images"]
)
return HostedRecord(
@@ -885,6 +893,8 @@ def message_to_dict(message: Message) -> dict[str, Any]:
}
if execution.cost is not None:
hosted_result["execution"]["cost"] = _cost_to_dict(execution.cost)
+ if message.hosted.action is not None:
+ hosted_result["action"] = _action_to_dict(message.hosted.action)
result["hosted"] = hosted_result
return result
raise TypeError(f"not a message: {type(message).__name__}")
@@ -927,7 +937,7 @@ def message_from_dict(data: Mapping[str, Any]) -> Message:
)
hosted_result = None
if "hosted" in f:
- h = _read(f["hosted"], "hosted result", {"record": dict}, {"execution": dict})
+ h = _read(f["hosted"], "hosted result", {"record": dict}, {"execution": dict, "action": dict})
execution = None
if "execution" in h:
e = _read(
@@ -949,7 +959,11 @@ def message_from_dict(data: Mapping[str, Any]) -> Message:
executor_billing=e["executor_billing"],
cost=_cost_from_dict(e["cost"]) if "cost" in e else None,
)
- hosted_result = HostedResult(record=_record_from_dict(h["record"]), execution=execution)
+ hosted_result = HostedResult(
+ record=_record_from_dict(h["record"]),
+ execution=execution,
+ action=_action_from_dict(h["action"]) if "action" in h else None,
+ )
return ToolResultMessage(
tool_call_id=f["tool_call_id"],
tool_name=f["tool_name"],
diff --git a/core/hosted_activity.py b/core/hosted_activity.py
index cae4450b8..18b5539da 100644
--- a/core/hosted_activity.py
+++ b/core/hosted_activity.py
@@ -139,6 +139,8 @@ def _image_payload(image: HostedImage) -> dict[str, Any]:
out["width"] = image.width
if image.height is not None:
out["height"] = image.height
+ if image.bytes is not None:
+ out["bytes"] = image.bytes
return out
@@ -228,6 +230,9 @@ def proxy_activity(
)
size = arguments.get("size") if isinstance(arguments.get("size"), str) else None
execution = result.execution
+ # What the executor reports it did (an image's rendered prompt and resolved size and quality), read as a native
+ # call's block action is.
+ ran = result.action if result.action is not None and result.action.type == "generate" else None
return HostedActivity(
call_id=call.id,
tool=call.name,
@@ -243,9 +248,9 @@ def proxy_activity(
model=execution.executor_origin.model if execution is not None else None,
sources=tuple(result.record.sources),
images=tuple(result.record.images or ()),
- size=size,
- quality=None,
- revised_prompt=None,
+ size=(ran.size if ran is not None and ran.size else size),
+ quality=ran.quality if ran is not None else None,
+ revised_prompt=ran.prompt if ran is not None else None,
cost=execution.cost if execution is not None else None,
cost_calls=1,
duration_ms=duration_ms,
diff --git a/docs/plans/agent-core-contracts/conversion-tables.md b/docs/plans/agent-core-contracts/conversion-tables.md
index 3901adac7..540fcad5b 100644
--- a/docs/plans/agent-core-contracts/conversion-tables.md
+++ b/docs/plans/agent-core-contracts/conversion-tables.md
@@ -649,8 +649,9 @@ far:
- **Requests.** A hosted tool's canonical spec is sent as the native declaration on a hop whose route is native, with
its Responses `include` values and the pin header on that request.
-- **Parsing** for `web_search` and `x_search`: native results become `HostedToolBlock`s, text citations become
- `TextBlock.citations`, and response-level facts go to `hosted_summary`.
+- **Parsing** for `web_search`, `x_search` and `image_generation`: native results become `HostedToolBlock`s, text
+ citations become `TextBlock.citations`, and response-level facts go to `hosted_summary`. A generated image is saved
+ to a file through the adapter's `MediaSink` as its done item is parsed (Images row).
- **Portable history.** A finished response's hosted calls become synthetic same-named calls and results, split around
the assistant message. There is one call per hosted block, and nothing folds. Each result shows its status line
first and then every line attached to it. A response its
@@ -674,9 +675,11 @@ far:
request reaches the loop as usual.
- **Proxy.** A hosted tool that a hop does not run natively is its canonical function, and a call to it runs on the
- gateway's executor bound for the Turn. The result keeps the record on `ToolResultMessage.hosted`.
+ gateway's executor bound for the Turn. The result keeps the record on `ToolResultMessage.hosted`. A proxied image's
+ base64 comes back beside its record and is saved through the same `MediaSink` as a native one; the record lists the
+ file.
-Still to come: `pause_turn` and images.
+Still to come: `pause_turn`.
Until `pause_turn` lands, the Anthropic stop table above still maps it to `stop`. An Anthropic citation covers its
whole text block, so it carries no range.
@@ -688,7 +691,7 @@ whole text block, so it carries no range.
| Response-level facts → `AssistantMessage.hosted_summary` | `usage.server_tool_use` counts | xAI `cost_in_usd_ticks` (reported once per response), `server_side_tool_usage_details` counts, and the X-search `url_citation`s as `cited_sources` | — |
| Citations → `TextBlock.citations` | text-block `citations[]` (`web_search_result_location`: `url`, `title`, `cited_text`) | `output_text.annotations[]` of type `url_citation` (`url`, `title`, `start_index`, `end_index`) | — |
| Same-Source replay (target hop is `native.source_id`, same origin, and `hosted_tools[tool].replay` is true now) | `native.payload` blocks verbatim, in place; citations not sent | `native.payload` items verbatim, in place; annotations not sent; never for `image_generation` | — |
-| Images | — | `image_generation_call` → file; history and model context hold the text path record (path, revised prompt, size, mode, cost); `result` base64 never stored; duplicate `result` in `response.completed` not decoded; the image-declaring stream gets a 32 MiB line cap | — |
+| Images | — | `image_generation_call` → a file saved through the `MediaSink` from its `output_item.done`. The record lists it as a `HostedImage`: absolute path, mime type sniffed from its bytes, the item's size as width and height, and the file's byte count. The action is `generate` with the revised prompt and the resolved size and quality. `native.payload` holds the path in place of `result`, so no base64 is ever stored. `partial_image` previews are skipped before parsing. The duplicate `result` in the terminal response is never decoded, and a call that saved no image is `failed`. The model reads the path record, and a file over `read`'s inline limit says so. A stream that declares `image_generation` gets the 32 MiB event cap as its line cap; others keep 8 MiB. | — |
| Other-origin replay | assistant `tool_use(name=<tool>, input=<per-action arguments>)` + user `tool_result(record as text)`, splitting the assistant message; a `failed`/`incomplete` record sets `is_error: true` | `function_call(name=<tool>, arguments)` + `function_call_output(record as text)`; a failed record's text starts `[<tool> failed: <error>]` | assistant `tool_calls` + `tool` message, failure as in Responses |
| Pinning (any protocol) | a request with a native declaration or a verbatim `native.payload` carries `x-avibe-pin-source: <hop source_id>`. A continuation whose calls go back verbatim also carries `x-avibe-pin-model: <its served model>`, the hop's own model. A `409` `model_hub_pin_unavailable` / `pin_unavailable` answer is not shown: the same request is rendered again in portable form (proxy declarations, synthetic history, in-place text) and sent unpinned, exactly once. | same | — |
| Citations at delivery | `TextBlock.citations` → `core/citations.py` builder → Markdown links + Web sidecar | same | — |
diff --git a/docs/plans/agent-core-contracts/message.schema.json b/docs/plans/agent-core-contracts/message.schema.json
index 780c8a852..8a8645773 100644
--- a/docs/plans/agent-core-contracts/message.schema.json
+++ b/docs/plans/agent-core-contracts/message.schema.json
@@ -430,13 +430,16 @@
"record"
],
"additionalProperties": false,
- "description": "Set only on the result of a proxied hosted call. `execution` is present exactly when an executor ran; without it the record failed.",
+ "description": "Set only on the result of a proxied hosted call. `execution` is present exactly when an executor ran; without it the record failed. `action` is what the executor reports it did, such as a generated image's rendered prompt and resolved size and quality.",
"properties": {
"record": {
"$ref": "#/definitions/HostedRecord"
},
"execution": {
"$ref": "#/definitions/ProxyExecution"
+ },
+ "action": {
+ "$ref": "#/definitions/HostedAction"
}
},
"if": {
@@ -846,7 +849,7 @@
"mime"
],
"additionalProperties": false,
- "description": "A generated image saved as a local file. Image bytes are never stored in a message.",
+ "description": "A generated image saved as a local file. Image bytes are never stored in a message; `bytes` is the file's size.",
"properties": {
"path": {
"type": "string",
@@ -867,6 +870,10 @@
"height": {
"type": "integer",
"minimum": 1
+ },
+ "bytes": {
+ "type": "integer",
+ "minimum": 1
}
}
},
diff --git a/docs/plans/agent-core-contracts/provider.md b/docs/plans/agent-core-contracts/provider.md
index feaffd545..86b7af516 100644
--- a/docs/plans/agent-core-contracts/provider.md
+++ b/docs/plans/agent-core-contracts/provider.md
@@ -40,6 +40,10 @@ class MediaLoader(Protocol): # supplied by the adapter; reads media_objects
async def load(self, media_token: str) -> tuple[bytes, str]: ... # bytes, mime type
+class MediaSink(Protocol): # supplied by the adapter; keeps a generated image as a local file
+ async def save_image(self, encoded: str) -> HostedImage: ... # base64 in; path, sniffed mime, size out
+
+
@dataclass(frozen=True)
class ModelRequest:
endpoint: ModelEndpoint
@@ -82,7 +86,9 @@ defined effect, including when it is unknown:
| `supports_images` | images sent | placeholders | placeholders |
| `supports_reasoning` | `reasoning_effort` sent if it is one of `reasoning_efforts` | `reasoning_effort = None` | `reasoning_effort = None` | Adapters are constructed with a
`MediaLoader` and resolve each `ImageBlock`'s bytes at request time; the canonical message never carries bytes. The
-token names an immutable snapshot (`message.schema.json`), so the bytes never change for a committed block.
+token names an immutable snapshot (`message.schema.json`), so the bytes never change for a committed block. The
+Responses adapter also takes a `MediaSink`. It saves each image a native `image_generation` call returns as it parses
+the call's done item, and the call's record names the file (`vibey-hosted-tools.md` §7.3).
`stream` yields `ProviderEvent`s (`provider-event.schema.json`) and always ends with exactly one `done` or one
`error`. `done.message` is the complete canonical `AssistantMessage`; its `origin` comes from the served-hop report
diff --git a/docs/plans/vibey-hosted-tools.md b/docs/plans/vibey-hosted-tools.md
index 5e29417b6..8df682a78 100644
--- a/docs/plans/vibey-hosted-tools.md
+++ b/docs/plans/vibey-hosted-tools.md
@@ -581,6 +581,12 @@ Each has a **Re-verify** action with its cost. Unknown shows nothing.
still over the cap gets a record saying it is too large to view inline.
- Known limitation: no transparent backgrounds in Phase 1. A later per-call format choice (an
`output_format`/`background` argument on the tool) restores them.
+ - Known limitation (orchestrator decision, 2026-10-14): a file is saved before the row that names it commits. A
+ cancel, crash or kill in between leaves a file no row references. Such files are content-addressed, so they never
+ duplicate, and the per-response image budget bounds them. A startup sweep of the agent media root removes them
+ (#2588, before the 3.2.1 RC).
+ - Avibe-authored failure reasons in a record's `error` are English model-facing text. Their display is localized
+ by a stable `error_code` at the display boundary (#2589, before the 3.2.1 RC).
- **The user sees the image.** The Workbench renders it inline from the file, and IM attaches it. That is display,
separate from model context.
- **History and replay never contain base64.**
@@ -597,8 +603,9 @@ Each has a **Re-verify** action with its cost. Unknown shows nothing.
events carry bytes during generation.
- The gateway counts a partial image as model output (`stream_wire.py`), so response headers are released at the
first partial.
- - Partials are previews for the user's display, written to a temporary file and replaced by the final image.
- They never enter history or model context.
+ - Phase 1 drops previews: Vibey counts each one against the response's image budget and keeps none, so no preview
+ reaches a file, history or model context, and the user sees the final image. Showing previews while an image is
+ drawn is a later display change: a temporary file the final image replaces.
- **What was measured.** A failing generation went 35.4 s without a byte after `generating`; healthy generations took
64–130 s.
- **Phase 1 acceptance gate.** Through the gateway, with partials, the largest byte gap of every successful test
diff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.py
index fb1c0376a..ce1b57ca0 100644
--- a/modules/agents/vibey/agent.py
+++ b/modules/agents/vibey/agent.py
@@ -243,7 +243,7 @@ class VibeyAgent(BaseAgent):
environment=self._environment,
on_response=self._on_response,
)
- self._providers = providers or registry_providers(media_loader=self.media)
+ self._providers = providers or registry_providers(media_loader=self.media, media_sink=self.media)
# The client of the Turn's other gateway calls (the hosted-tool executor); None opens one per call.
self._gateway_client = gateway_client
# C-9: the Session parts a checkpoint carries (context.md section 9).
@@ -617,7 +617,7 @@ class VibeyAgent(BaseAgent):
# Job-backed tools receive the loop's tracking wrapper, so Stop kills foreground commands.
tools = mark_skill_loads(
(
- *hosted_tools(turn.router.preflight, self._gateway_client),
+ *hosted_tools(turn.router.preflight, self._gateway_client, self.media),
*suite.create_tools(agent.jobs, self.media.image_sink(session_id)),
)
)
diff --git a/modules/agents/vibey/media.py b/modules/agents/vibey/media.py
index 96e489516..120a6b5e5 100644
--- a/modules/agents/vibey/media.py
+++ b/modules/agents/vibey/media.py
@@ -11,16 +11,20 @@ transcript replays. Loading re-checks the digest.
from __future__ import annotations
import asyncio
+import base64
+import binascii
import hashlib
import os
import secrets
+import stat
from pathlib import Path
from typing import Optional
from sqlalchemy import select
from sqlalchemy.engine import Engine
-from core.agent_core.messages import IMAGE_MIME_TYPES, ImageBlock
+from core.agent_core.messages import IMAGE_MIME_TYPES, HostedImage, ImageBlock
+from core.agent_core.tools.read import detect_supported_image_mime_type
from storage import media_service
from storage.models import agent_sessions
@@ -33,7 +37,7 @@ class MediaUnavailable(RuntimeError):
class MediaSnapshots:
- """``MediaLoader`` for the provider adapters plus the snapshot writer."""
+ """``MediaLoader`` and ``MediaSink`` for the provider adapters, plus the snapshot writer."""
def __init__(self, engine: Engine, root: Path) -> None:
self._engine = engine
@@ -79,17 +83,49 @@ class MediaSnapshots:
return sink
- def _snapshot(self, data: bytes, mime_type: str, session_id: str, name: Optional[str]) -> str:
- if mime_type not in IMAGE_MIME_TYPES:
- raise ValueError(f"unsupported image type: {mime_type}")
+ # --- MediaSink -------------------------------------------------------------
+
+ async def save_image(self, encoded: str) -> HostedImage:
+ """A generated image (``vibey-hosted-tools.md`` §7.3), kept as an immutable file the agent's ``read`` opens.
+ The surfaces register it for display when the row that names it commits."""
+ return await asyncio.to_thread(self._save_image, encoded)
+
+ def _save_image(self, encoded: str) -> HostedImage:
+ try:
+ data = base64.b64decode(encoded, validate=True)
+ except (binascii.Error, ValueError):
+ raise ValueError("the image is not valid base64") from None
+ mime_type = detect_supported_image_mime_type(data)
+ if mime_type not in _EXTENSIONS:
+ raise ValueError("the image is not a PNG, JPEG, GIF or WebP")
+ return HostedImage(path=str(self._store(data, mime_type)), mime=mime_type, bytes=len(data))
+
+ def _store(self, data: bytes, mime_type: str) -> Path:
+ """The content-addressed file holding ``data``. An entry already at that name is reused only while it is a
+ regular file that still holds those bytes: history reads these paths directly, and their owner can change
+ them. Anything else is replaced by one atomic rename, which never follows the entry it replaces, so nothing is
+ repaired in place and a link's target is never touched."""
digest = hashlib.sha256(data).hexdigest()
path = self._root / f"{digest}.{_EXTENSIONS[mime_type]}"
- if not path.is_file():
- self._root.mkdir(parents=True, exist_ok=True)
- tmp = self._root / f".{digest}.{secrets.token_hex(4)}.tmp"
+ try:
+ if stat.S_ISREG(os.lstat(path).st_mode) and hashlib.sha256(path.read_bytes()).hexdigest() == digest:
+ return path
+ except OSError:
+ pass # missing or unreadable: written below
+ self._root.mkdir(parents=True, exist_ok=True)
+ tmp = self._root / f".{digest}.{secrets.token_hex(4)}.tmp"
+ try:
tmp.write_bytes(data)
- os.chmod(tmp, 0o444)
os.replace(tmp, path)
+ except BaseException:
+ tmp.unlink(missing_ok=True)
+ raise
+ return path
+
+ def _snapshot(self, data: bytes, mime_type: str, session_id: str, name: Optional[str]) -> str:
+ if mime_type not in IMAGE_MIME_TYPES:
+ raise ValueError(f"unsupported image type: {mime_type}")
+ path = self._store(data, mime_type)
with self._engine.begin() as conn:
scope_id = conn.execute(
select(agent_sessions.c.scope_id).where(agent_sessions.c.id == session_id)
diff --git a/modules/agents/vibey/models.py b/modules/agents/vibey/models.py
index 6a8ad5906..27676ecba 100644
--- a/modules/agents/vibey/models.py
+++ b/modules/agents/vibey/models.py
@@ -208,21 +208,24 @@ class HubModelRouter:
logger.warning("Vibey could not close its %s provider adapter", protocol, exc_info=True)
-def registry_providers(*, media_loader: Any, client: Any = None) -> ProviderFactory:
+def registry_providers(*, media_loader: Any, media_sink: Any = None, client: Any = None) -> ProviderFactory:
"""Provider adapters from the ``ai`` registry, speaking to the Model Hub gateway.
In gateway mode each adapter reads the served origin from ``x-avibe-served-hop``
- with the engine's own resolver, the one owner of that C-6 rule.
+ with the engine's own resolver, the one owner of that C-6 rule. ``media_sink``
+ keeps the images a Responses hop generates natively, the only protocol that does.
"""
def create(protocol: ProtocolName) -> ProviderAdapter:
from core.agent_core.ai.registry import create_adapter
+ images = {"media_sink": media_sink} if protocol == "openai_responses" else {}
return create_adapter(
protocol,
client=client,
media_loader=media_loader,
gateway=True,
+ **images,
)
return create
diff --git a/modules/agents/vibey/tools.py b/modules/agents/vibey/tools.py
index 8e419e569..b87776dea 100644
--- a/modules/agents/vibey/tools.py
+++ b/modules/agents/vibey/tools.py
@@ -16,7 +16,7 @@ keeps the command in the foreground.
from __future__ import annotations
import asyncio
-from dataclasses import dataclass, field
+from dataclasses import dataclass, field, replace
from typing import Any, Awaitable, Callable, Mapping, Optional, Sequence
import httpx
@@ -24,9 +24,16 @@ import httpx
from core.agent_core.agent.models import ModelSelection
from core.agent_core.agent.recovery import RecoveryRenderer
from core.agent_core.ai._common import CONNECT_TIMEOUT_S, auth_headers, join_endpoint_url
-from core.agent_core.ai.hosted import bounded_error, record_text
-from core.agent_core.ai.provider import HostedExecutor, ModelEndpoint
-from core.agent_core.messages import HostedRecord, HostedResult, TextBlock, ToolResultMessage, message_from_dict
+from core.agent_core.ai.hosted import bounded_error, generate_action, image_dimensions, record_text
+from core.agent_core.ai.provider import HostedExecutor, MediaSink, ModelEndpoint
+from core.agent_core.messages import (
+ HostedImage,
+ HostedRecord,
+ HostedResult,
+ TextBlock,
+ ToolResultMessage,
+ message_from_dict,
+)
from core.agent_core.tools.base import CallInstance, JobHost, Tool, ToolContext, ToolResult, ToolSpec
from core.agent_core.tools.hosted import hosted_tool_spec
from core.agent_core.tools.shell import default_shell
@@ -102,9 +109,9 @@ def local_tool_suite(jobs_dir: Optional[str] = None, *, route: Optional[HandOver
)
-#: The hosted tools whose native results the adapters parse. A generated image arrives as base64 that history must
-#: never hold (§7.3), so ``image_generation`` joins with its media handling.
-PARSED_HOSTED_TOOLS = ("web_search", "x_search")
+#: The hosted tools a Turn registers, each serving both modes. A generated image, native or proxied, is saved through
+#: the media sink as it arrives, so history holds only its path (§7.3).
+PARSED_HOSTED_TOOLS = ("web_search", "x_search", "image_generation")
@dataclass(frozen=True)
@@ -122,11 +129,15 @@ class HostedTool:
#: The Turn's gateway: where the executor endpoint lives, and the token and headers that authorize the call.
endpoint: ModelEndpoint = field(repr=False)
client: Optional[httpx.AsyncClient] = field(default=None, repr=False)
+ #: Where a proxied image is saved: the same sink as a native one.
+ media: Optional[MediaSink] = field(default=None, repr=False)
async def execute(self, arguments: Mapping[str, Any], ctx: ToolContext) -> ToolResult:
del ctx
hosted = await self._run(dict(arguments))
- query = arguments.get("query")
+ # The prompt an image was rendered from, when the executor reports it, as a native call's record shows it.
+ rendered = hosted.action.prompt if hosted.action is not None else None
+ query = rendered or arguments.get("query") or arguments.get("prompt")
text = record_text(self.spec.name, hosted.record, query=query if isinstance(query, str) else None)
failed = hosted.record.status in ("failed", "incomplete")
return ToolResult(content=(TextBlock(text),), is_error=failed, hosted=hosted)
@@ -149,19 +160,53 @@ class HostedTool:
async with httpx.AsyncClient(timeout=timeout, trust_env=False) as client:
response = await client.post(url, json=body, headers=headers)
except httpx.HTTPError as error:
- return _failed(f"the gateway could not run the call ({type(error).__name__})")
+ return _failed(self.spec.name, f"the gateway could not run the call ({type(error).__name__})")
if response.status_code != 200:
- return _failed(f"the gateway refused the call (HTTP {response.status_code} {_error_code(response)})")
+ return _failed(
+ self.spec.name, f"the gateway refused the call (HTTP {response.status_code} {_error_code(response)})"
+ )
try:
- return _hosted_result(self.spec.name, response.json())
+ # A proxied image's answer carries megabytes of base64: parsed off the controller loop.
+ answer = await asyncio.to_thread(response.json)
+ hosted = _hosted_result(self.spec.name, answer)
except (TypeError, ValueError):
- return _failed("the gateway answered with no hosted result")
+ return _failed(self.spec.name, "the gateway answered with no hosted result")
+ if self.spec.name == "image_generation" and hosted.record.status == "completed":
+ hosted = await self._saved(hosted, answer)
+ return hosted
+
+ async def _saved(self, hosted: HostedResult, answer: Mapping[str, Any]) -> HostedResult:
+ """A proxied image, saved through the media sink as a native one is (§7.3, item 27): the executor returns its
+ base64, and the record lists the file. A completed call that saved no image failed."""
+
+ generation = answer.get("generation")
+ generation = generation if isinstance(generation, Mapping) else {}
+ width, height = image_dimensions(generation.get("size"))
+ saved: list[HostedImage] = []
+ try:
+ for item in answer.get("images") or ():
+ encoded = item.get("data") if isinstance(item, Mapping) else None
+ if not isinstance(encoded, str) or self.media is None:
+ raise ValueError("nothing here can keep a generated image")
+ saved.append(replace(await self.media.save_image(encoded), width=width, height=height))
+ except (ValueError, OSError) as error:
+ return replace(hosted, record=_failed_record(self.spec.name, f"the image could not be saved: {error}"))
+ if not saved:
+ return replace(hosted, record=_failed_record(self.spec.name, "the executor returned no image"))
+ # The executor's rendered prompt and resolved size and quality: where a native call's block carries them.
+ return replace(hosted, record=replace(hosted.record, images=tuple(saved)), action=generate_action(generation))
+
+
+def _failed_record(tool: str, reason: str) -> HostedRecord:
+ return HostedRecord(
+ status="failed", error=bounded_error(reason), images=() if tool == "image_generation" else None
+ )
-def _failed(reason: str) -> HostedResult:
+def _failed(tool: str, reason: str) -> HostedResult:
"""A call that never reached an executor: a failed record, and no execution (§4.2)."""
- return HostedResult(record=HostedRecord(status="failed", error=bounded_error(reason)))
+ return HostedResult(record=_failed_record(tool, reason))
def _error_code(response: httpx.Response) -> str:
@@ -179,6 +224,9 @@ def _hosted_result(tool: str, body: Any) -> HostedResult:
if not isinstance(body, Mapping) or not isinstance(body.get("record"), Mapping):
raise ValueError("no hosted record")
hosted = {key: body[key] for key in ("record", "execution") if key in body}
+ if tool == "image_generation":
+ # The executor answers an image's bytes beside the record (``images``); the record lists what is saved.
+ hosted["record"] = {**hosted["record"], "images": []}
message = message_from_dict(
{
"role": "tool_result",
@@ -194,7 +242,11 @@ def _hosted_result(tool: str, body: Any) -> HostedResult:
return message.hosted
-def hosted_tools(selection: Optional[ModelSelection], client: Optional[httpx.AsyncClient] = None) -> tuple[Tool, ...]:
+def hosted_tools(
+ selection: Optional[ModelSelection],
+ client: Optional[httpx.AsyncClient] = None,
+ media: Optional[MediaSink] = None,
+) -> tuple[Tool, ...]:
"""The Turn's hosted tools: every tool the user enabled, in Model Hub's order, whatever preflight's hop runs it as.
They lead the Turn's tools, so its last tool stays a local one whatever a hop renders them as, and the list stays
the same for the whole Turn."""
@@ -203,7 +255,7 @@ def hosted_tools(selection: Optional[ModelSelection], client: Optional[httpx.Asy
return ()
endpoint = selection.endpoint
return tuple(
- HostedTool(hosted_tool_spec(name), route.executor, endpoint, client)
+ HostedTool(hosted_tool_spec(name), route.executor, endpoint, client, media)
for name, route in endpoint.hosted_tools.items()
if name in PARSED_HOSTED_TOOLS
)
diff --git a/tests/agent_core/ai/test_hosted_images.py b/tests/agent_core/ai/test_hosted_images.py
new file mode 100644
index 000000000..2ff4fbc49
--- /dev/null
+++ b/tests/agent_core/ai/test_hosted_images.py
@@ -0,0 +1,246 @@
+"""Native image generation (``vibey-hosted-tools.md`` §7.3, §7.5). Scenario MH-HOSTED-VIBEY-007.
+
+A generated image is saved to a file as its done item is parsed, and the call's record names that file: no base64
+enters the message, the transcript or the model's context. Partial previews are never kept, and the terminal response's
+copy of the image is never decoded. A stream that may carry an image gets the whole event cap as its line cap.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+from pathlib import Path
+from typing import Any
+
+import httpx
+import pytest
+
+from core.agent_core.ai import openai_responses
+from core.agent_core.ai.hosted import in_place_text
+from core.agent_core.ai.provider import Done, HostedToolRoute, ModelEndpoint, ModelRequest, ProviderError
+from core.agent_core.ai.registry import create_adapter
+from core.agent_core.cancel import CancelToken
+from core.agent_core.messages import HostedAction, HostedImage, HostedToolBlock, TextBlock, UserMessage, message_to_dict
+from core.agent_core.tools.hosted import hosted_tool_spec
+from core.agent_core.tools.read import MAX_INLINE_IMAGE_BYTES
+
+SOURCE = "src_served00001"
+DECLARATION = {"type": "image_generation", "partial_images": 2, "output_format": "jpeg", "output_compression": 90}
+JPEG = b"\xff\xd8\xff\xe0" + b"\x00\x10JFIF" + bytes(range(256)) * 4
+
+
+class Sink:
+ """The adapter layer's media store, as a directory: each saved image is one file."""
+
+ def __init__(self, root: Path) -> None:
+ self.root = root
+ self.saved: list[Path] = []
+
+ async def save_image(self, encoded: str) -> HostedImage:
+ data = base64.b64decode(encoded, validate=True)
+ path = self.root / f"image-{len(self.saved)}.jpg"
+ path.write_bytes(data)
+ self.saved.append(path)
+ return HostedImage(path=str(path), mime="image/jpeg", bytes=len(data))
+
+
+def _sse(*events: tuple[str | None, Any]) -> str:
+ """Named SSE events; a string payload goes out as it is, so it need not be JSON."""
+
+ frames = []
+ for name, payload in events:
+ data = payload if isinstance(payload, str) else json.dumps(payload)
+ frames.append((f"event: {name}\n" if name else "") + f"data: {data}\n\n")
+ return "".join(frames)
+
+
+def _image_item(result: str | None, *, status: str = "completed") -> dict[str, Any]:
+ item = {
+ "id": "ig_1",
+ "type": "image_generation_call",
+ "status": status,
+ "revised_prompt": "A lighthouse at dusk, oil painting",
+ "size": "1536x1024",
+ "quality": "high",
+ "output_format": "jpeg",
+ }
+ if result is not None:
+ item["result"] = result
+ return item
+
+
+def _stream(
+ encoded: str,
+ *,
+ done: bool = True,
+ terminal_copy: str = "!!not base64, never decoded!!",
+ previews: int = 1,
+ unnamed_previews: bool = False,
+ status: str = "completed",
+) -> str:
+ events: list[tuple[str | None, Any]] = [
+ ("response.created", {"type": "response.created", "response": {"status": "in_progress"}}),
+ (
+ "response.output_item.added",
+ {"type": "response.output_item.added", "output_index": 0, "item": _image_item(None, status="in_progress")},
+ ),
+ ]
+ # A preview: not JSON at all here, so the stream fails if anything parses it. A source that names no SSE event
+ # sends it as JSON, known only by its type.
+ preview: tuple[str | None, Any] = (
+ (None, {"type": "response.image_generation_call.partial_image", "partial_image_b64": "AAAA"})
+ if unnamed_previews
+ else ("response.image_generation_call.partial_image", "{partial preview bytes")
+ )
+ events += [preview] * previews
+ if done:
+ events.append(
+ (
+ "response.output_item.done",
+ {"type": "response.output_item.done", "output_index": 0, "item": _image_item(encoded, status=status)},
+ )
+ )
+ message = {"id": "msg_1", "type": "message", "content": [{"type": "output_text", "text": "Here it is.", "annotations": []}]}
+ events += [
+ ("response.output_item.added", {"type": "response.output_item.added", "output_index": 1, "item": {**message, "content": []}}),
+ ("response.output_text.delta", {"type": "response.output_text.delta", "output_index": 1, "delta": "Here it is."}),
+ ("response.output_item.done", {"type": "response.output_item.done", "output_index": 1, "item": message}),
+ (
+ "response.completed",
+ {
+ "type": "response.completed",
+ "response": {"status": "completed", "output": [_image_item(terminal_copy), message], "usage": {}},
+ },
+ ),
+ ]
+ return _sse(*events)
+
+
+async def _generate(body: str, sink: Sink, *, declared: bool = True) -> list[Any]:
+ routes = {"image_generation": HostedToolRoute("native", None, False, declaration=DECLARATION)} if declared else {}
+ request = ModelRequest(
+ endpoint=ModelEndpoint(
+ "openai_responses",
+ "http://hub.invalid/vibey/v1",
+ "gpt-6-sol",
+ "hub-token",
+ provider="openai",
+ source_id=SOURCE,
+ hosted_tools=routes,
+ ),
+ system="system",
+ messages=(UserMessage((TextBlock("paint a lighthouse"),)),),
+ tools=(hosted_tool_spec("image_generation"),),
+ max_tokens=256,
+ cache="none",
+ )
+ served = {"provider": "openai", "api": "openai_responses", "model": "gpt-6-sol", "source": SOURCE}
+ headers = {"content-type": "text/event-stream", "x-avibe-served-hop": json.dumps(served, separators=(",", ":"))}
+ async with httpx.AsyncClient(
+ transport=httpx.MockTransport(lambda _: httpx.Response(200, headers=headers, text=body))
+ ) as client:
+ adapter = create_adapter("openai_responses", client=client, gateway=True, media_sink=sink)
+ return [event async for event in adapter.stream(request, CancelToken())]
+
+
+async def test_a_native_image_is_saved_once_from_its_done_item_and_history_holds_only_its_path(tmp_path):
+ """MH-HOSTED-VIBEY-007: the record names the file, the action keeps the provider's revised prompt and resolved
+ size and quality, and no copy of the image, done, partial or terminal, enters the message."""
+
+ sink = Sink(tmp_path)
+ encoded = base64.b64encode(JPEG).decode()
+
+ events = await _generate(_stream(encoded), sink)
+
+ assert isinstance(events[-1], Done), events[-1]
+ message = events[-1].message
+ (call,) = [block for block in message.content if isinstance(block, HostedToolBlock)]
+ assert [path.read_bytes() for path in sink.saved] == [JPEG]
+ image = HostedImage(path=str(sink.saved[0]), mime="image/jpeg", width=1536, height=1024, bytes=len(JPEG))
+ assert call.tool == "image_generation" and call.record.status == "completed" and call.record.images == (image,)
+ assert call.action == HostedAction(
+ "generate", prompt="A lighthouse at dusk, oil painting", size="1536x1024", quality="high"
+ )
+ assert call.native.payload[0]["result"] == str(sink.saved[0])
+ stored = json.dumps(message_to_dict(message))
+ assert encoded not in stored and "never decoded" not in stored
+ assert in_place_text(call).startswith('[image_generation: "A lighthouse at dusk, oil painting"]\nImage saved: ')
+
+
+ ("done", "status", "encoded", "error"),
+ [
+ (False, "completed", base64.b64encode(JPEG).decode(), "the image was not streamed before the response ended"),
+ (True, "completed", "@@@ not base64 @@@", "the image could not be saved: "),
+ # A call the provider did not complete lists no image, so its bytes are never saved: no file without a record.
+ (True, "failed", base64.b64encode(JPEG).decode(), "the provider ended the call failed"),
+ ],
+ ids=["only-in-the-terminal-copy", "unreadable", "failed-with-bytes"],
+)
+async def test_an_image_that_was_not_saved_is_a_failed_call_never_a_completed_one(
+ tmp_path, done, status, encoded, error
+):
+ sink = Sink(tmp_path)
+
+ events = await _generate(_stream(encoded, done=done, terminal_copy=encoded, status=status), sink)
+
+ (call,) = [block for block in events[-1].message.content if isinstance(block, HostedToolBlock)]
+ assert call.record.status == "failed" and call.record.error.startswith(error)
+ assert call.record.images == () and "result" not in call.native.payload[0]
+ assert not sink.saved
+
+
+async def test_a_six_megabyte_image_streams_under_the_image_line_cap_and_its_record_says_read_cannot_show_it(tmp_path):
+ """§7.3, §7.5: an image of 6 MiB is one base64 line over the default 8 MiB line cap, which a stream that may carry
+ an image raises to the event cap. Such an image is over ``read``'s inline limit, so its record says so; a stream
+ that declared no image keeps the default cap."""
+
+ large = JPEG + bytes(6 * 1024 * 1024 - len(JPEG))
+ encoded = base64.b64encode(large).decode()
+
+ events = await _generate(_stream(encoded), Sink(tmp_path))
+ undeclared = await _generate(_stream(encoded), Sink(tmp_path), declared=False)
+
+ (call,) = [block for block in events[-1].message.content if isinstance(block, HostedToolBlock)]
+ assert call.record.images[0].bytes == len(large) > MAX_INLINE_IMAGE_BYTES
+ assert "inline image limit, so read cannot show it" in in_place_text(call)
+ assert isinstance(undeclared[-1], ProviderError) and "line" in undeclared[-1].message
+
+
+ ("previews", "unnamed", "budget", "reason"),
+ [
+ # The declaration asks for 2 previews and the final: 3 events per image call, and a margin of 2.
+ (5, False, None, "more images than the response asked for"),
+ (5, True, None, "more images than the response asked for"),
+ (1, False, 1024, "more image data than one response may carry"),
+ ],
+ ids=["events", "events-known-by-type", "bytes"],
+)
+async def test_a_response_that_streams_images_past_its_budget_ends_as_an_error(
+ tmp_path, monkeypatch, previews, unnamed, budget, reason
+):
+ """Plan item 25: previews are never kept, but each counts, named or known by its type, so a provider cannot
+ stream images without bound."""
+
+ if budget is not None:
+ monkeypatch.setattr(openai_responses, "IMAGE_BYTES_PER_RESPONSE", budget)
+ sink = Sink(tmp_path)
+
+ events = await _generate(
+ _stream(base64.b64encode(JPEG).decode(), previews=previews, unnamed_previews=unnamed), sink
+ )
+
+ assert isinstance(events[-1], ProviderError) and reason in events[-1].message
+ assert not sink.saved
+
+
+def test_the_images_one_response_may_stream_fit_the_terminal_event_that_repeats_them():
+ """The terminal response repeats every final image in one SSE event: the response's image budget, as base64 with a
+ margin for the rest of that event, is never more than one event may carry, so a response within its budget is
+ never rejected by the event cap after its images were saved."""
+
+ from core.agent_core.ai.sse import DEFAULT_MAX_PENDING_EVENT_SIZE
+
+ as_base64 = -(-openai_responses.IMAGE_BYTES_PER_RESPONSE // 3) * 4
+ assert as_base64 + 1024 * 1024 <= DEFAULT_MAX_PENDING_EVENT_SIZE
diff --git a/tests/agent_core/test_hosted_messages.py b/tests/agent_core/test_hosted_messages.py
index 7c119bc31..19bd63881 100644
--- a/tests/agent_core/test_hosted_messages.py
+++ b/tests/agent_core/test_hosted_messages.py
@@ -151,6 +151,8 @@ def _produced() -> list:
executor_billing="monthly",
cost=HostedCost(basis="included"),
),
+ # What the executor rendered: its revised prompt and the resolved size and quality.
+ action=HostedAction(type="generate", prompt="A lighthouse at dusk", size="1024x1024", quality="high"),
),
)
unexecuted = ToolResultMessage(
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index 29acb1479..191fa117e 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -58,6 +58,7 @@ capabilities:
- tests/agent_core/ai/test_hosted_parsing.py
- tests/agent_core/ai/test_hosted_transform.py
- tests/agent_core/ai/test_hosted_replay.py
+ - tests/agent_core/ai/test_hosted_images.py
- tests/test_vibey_agent.py
- tests/test_model_hub_evidence_rules.py
- tests/test_model_hub_admission.py
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 83a4dedd7..6de53e1bf 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -16,6 +16,7 @@ capability:
- tests/agent_core/ai/test_hosted_parsing.py
- tests/agent_core/ai/test_hosted_transform.py
- tests/agent_core/ai/test_hosted_replay.py
+ - tests/agent_core/ai/test_hosted_images.py
- tests/test_vibey_agent.py
- tests/test_model_hub_evidence_rules.py
- tests/test_model_hub_config.py
@@ -321,6 +322,17 @@ scenarios:
related_tests:
- tests/agent_core/ai/test_hosted_replay.py::test_a_hosted_call_goes_back_verbatim_and_pinned_only_to_its_own_source_with_replay_evidence
- tests/agent_core/ai/test_hosted_replay.py::test_a_continuation_goes_back_verbatim_only_to_the_hop_that_served_it
+ - id: MH-HOSTED-VIBEY-007
+ name: A native generated image is saved to a file as its done item is parsed and its record names that file; no base64 enters history, partial and terminal copies are never decoded, and an image over read's inline limit says so
+ status: covered
+ kind: contract
+ layer: contract
+ test: tests/agent_core/ai/test_hosted_images.py::test_a_native_image_is_saved_once_from_its_done_item_and_history_holds_only_its_path
+ related_tests:
+ - tests/agent_core/ai/test_hosted_images.py::test_an_image_that_was_not_saved_is_a_failed_call_never_a_completed_one
+ - tests/agent_core/ai/test_hosted_images.py::test_a_six_megabyte_image_streams_under_the_image_line_cap_and_its_record_says_read_cannot_show_it
+ - tests/agent_core/ai/test_hosted_images.py::test_a_response_that_streams_images_past_its_budget_ends_as_an_error
+ - tests/test_vibey_agent.py::test_a_generated_image_is_kept_as_an_immutable_file_its_bytes_name_and_type
- id: MH-VIBEY-007
name: Vibey starts once with the user's Sources and built-in Agent models, seeded when its first Source exists
status: covered
diff --git a/tests/test_hosted_activity.py b/tests/test_hosted_activity.py
index 0f1abe6fc..7ad86bd87 100644
--- a/tests/test_hosted_activity.py
+++ b/tests/test_hosted_activity.py
@@ -113,7 +113,7 @@ def native_image():
action=HostedAction(type="generate", prompt=PROMPT, size="1536x1024", quality="medium"),
record=HostedRecord(
status="completed",
- images=(HostedImage(path="/media/3f2a.png", mime="image/png", width=1536, height=1024),),
+ images=(HostedImage(path="/media/3f2a.png", mime="image/png", width=1536, height=1024, bytes=1993000),),
),
native=_native("src_relaygpt1"),
),
@@ -136,6 +136,25 @@ def proxy_failed():
)
+def test_a_proxied_image_shows_what_its_executor_rendered_as_a_native_one_does():
+ """A proxied image's card reads the executor's rendered prompt and resolved size and quality from the result's
+ action, as a native image's reads its block's action: one reading, no mode branch."""
+
+ call = ToolCallBlock(id="call_i1", name="image_generation", arguments={"prompt": "a lighthouse", "size": "auto"})
+ activity = proxy_activity(
+ call,
+ HostedResult(
+ record=HostedRecord(status="completed", images=(HostedImage(path="/media/9c1d.jpg", mime="image/jpeg"),)),
+ execution=XAI,
+ action=HostedAction(type="generate", prompt=PROMPT, size="1536x1024", quality="high"),
+ ),
+ source_names=NAMES,
+ )
+
+ assert (activity.subject, activity.revised_prompt) == ("a lighthouse", PROMPT)
+ assert (activity.size, activity.quality) == ("1536x1024", "high")
+
+
@pytest.mark.parametrize("build", [native_web_search, proxy_x_search, native_image, proxy_failed])
def test_payloads_match_the_shape_the_web_card_renders(build):
"""MH-HOSTED-UI-009: every mode and outcome the card distinguishes, from the canonical records each producer writes.
diff --git a/tests/test_vibey_agent.py b/tests/test_vibey_agent.py
index 77f3fe6a7..57e2e063a 100644
--- a/tests/test_vibey_agent.py
+++ b/tests/test_vibey_agent.py
@@ -20,6 +20,7 @@ dispatcher), with a scripted provider and test-owned tools:
from __future__ import annotations
import asyncio
+import base64
import json
import logging
import os
@@ -58,12 +59,14 @@ from core.agent_core.messages import (
ToolResultMessage,
UserMessage,
text,
+ message_to_dict,
)
from core.agent_core.tools.base import CallInstance, JobStatus, ToolResult
from core.message_dispatcher import ConsolidatedMessageDispatcher
from core.services.agent_steering import ActiveSteerTarget, SteerOutcome, SteerRequest
from modules.agents.vibey import VibeyAgent
from modules.agents.vibey.errors import _KIND_KEYS, error_key
+from modules.agents.vibey.media import MediaSnapshots
from modules.agents.vibey.tools import ToolSuite, local_tool_suite
from modules.agents.base import AgentRequest
from modules.agents.model_hub import ModelHubLaunch
@@ -2629,6 +2632,74 @@ async def test_a_proxied_hosted_call_runs_on_the_bound_executor_and_keeps_its_re
assert sent["type"] == "tool_result" and seen in json.dumps(sent)
+async def test_a_proxied_image_is_saved_through_the_media_sink_and_its_record_names_the_file(
+ engine, session, tmp_path, published
+) -> None:
+ """MH-HOSTED-VIBEY-007 (vibey-hosted-tools.md §7.3, item 27): the executor answers a proxied image's bytes beside
+ its record; Vibey saves them through the same sink as a native image, the record lists the file, and no base64
+ reaches the transcript or the model."""
+ import httpx
+
+ from modules.agents.vibey.models import registry_providers
+
+ served = json.dumps(
+ {"provider": "anthropic", "api": "anthropic", "model": "claude-opus-5-5", "source": "src_upstream01"},
+ separators=(",", ":"),
+ )
+ call = '{"type":"tool_use","id":"toolu_1","name":"image_generation","input":{"prompt":"a lighthouse"}}'
+ replies = [
+ _anthropic_reply(call, stop_reason="tool_use"),
+ _anthropic_reply('{"type":"text","text":"here it is"}', stop_reason="end_turn"),
+ ]
+ jpeg = b"\xff\xd8\xff\xe0" + bytes(range(256)) * 8
+ encoded = base64.b64encode(jpeg).decode()
+ answer = {
+ "record": {"status": "completed", "sources": []},
+ "execution": {
+ "mode": "proxy",
+ "executor_origin": {"provider": "openai", "api": "openai_responses", "model": "gpt-image"},
+ "executor_source_id": "src_executor01",
+ "executor_billing": "metered",
+ },
+ "generation": {"revised_prompt": "A lighthouse at dusk", "size": "1536x1024", "quality": "high"},
+ "images": [{"mime": "image/jpeg", "data": encoded}],
+ }
+ models: list[dict] = []
+
+ def gateway(request: httpx.Request) -> httpx.Response:
+ if request.url.path == "/vibey/v1/hosted-tools/image_generation":
+ return httpx.Response(200, json=answer)
+ models.append(json.loads(request.content))
+ return httpx.Response(
+ 200, headers={"content-type": "text/event-stream", "x-avibe-served-hop": served}, text=replies.pop(0)
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:
+ harness = _Harness(
+ engine,
+ tmp_path,
+ "telegram",
+ [],
+ providers=registry_providers(media_loader=None, client=client),
+ gateway_client=client,
+ )
+ harness.controller.hub_hosted_tools = {"image_generation": _PROXY_IMAGE}
+ await harness.agent.handle_message(harness.request("paint a lighthouse"))
+
+ result = next(row.message for row in await harness.context_rows() if isinstance(row.message, ToolResultMessage))
+ (image,) = result.hosted.record.images
+ assert not result.is_error and result.hosted.record.status == "completed"
+ assert Path(image.path).read_bytes() == jpeg
+ assert (image.mime, image.width, image.height, image.bytes) == ("image/jpeg", 1536, 1024, len(jpeg))
+ assert f"Image saved: {image.path}" in result.content[0].text
+ assert encoded not in json.dumps(models) and encoded not in json.dumps(message_to_dict(result))
+ # The executor's rendered prompt and resolved size and quality, kept as a native call's block keeps them.
+ assert result.hosted.action == HostedAction(
+ "generate", prompt="A lighthouse at dusk", size="1536x1024", quality="high"
+ )
+ assert result.content[0].text.startswith('[image_generation: "A lighthouse at dusk"]')
+
+
_NATIVE_SEARCH = {"mode": "native", "declaration": {"type": "web_search"}, "include": [], "executor": None, "replay": False}
_PROXY_IMAGE = {"mode": "proxy", "executor": {"source_id": "src_executor01", "model_id": "gpt-image"}, "replay": False}
@@ -2920,6 +2991,36 @@ async def test_images_read_together_reach_the_model_with_their_own_calls_in_call
assert (await harness.agent.media.load(image.media_token))[0] == pictures[name]
+async def test_a_generated_image_is_kept_as_an_immutable_file_its_bytes_name_and_type(tmp_path):
+ """MH-HOSTED-VIBEY-007, §7.3: the media sink keeps a generated image as a content-addressed file, typed by what its
+ bytes are, reused only while it still holds them, and refuses anything that is not a supported image."""
+
+ media = MediaSnapshots(None, tmp_path / "media") # type: ignore[arg-type]
+ jpeg = b"\xff\xd8\xff\xe0" + bytes(range(256)) * 8
+
+ image = await media.save_image(base64.b64encode(jpeg).decode())
+ again = await media.save_image(base64.b64encode(jpeg).decode())
+
+ assert image == again and image.mime == "image/jpeg" and image.bytes == len(jpeg)
+ path = Path(image.path)
+ assert path.is_absolute() and path.parent == tmp_path / "media" and path.read_bytes() == jpeg
+ # Its owner can change it: a changed file is written again, never reused.
+ path.write_bytes(b"changed by an agent's shell")
+ assert await media.save_image(base64.b64encode(jpeg).decode()) == image and path.read_bytes() == jpeg
+ # A link put in its place is replaced by one rename, never followed: its target keeps its bytes and its mode.
+ secret = tmp_path / "secret.key"
+ secret.write_bytes(b"key")
+ os.chmod(secret, 0o600)
+ path.unlink()
+ path.symlink_to(secret)
+ assert await media.save_image(base64.b64encode(jpeg).decode()) == image
+ assert not path.is_symlink() and path.read_bytes() == jpeg
+ assert secret.read_bytes() == b"key" and secret.stat().st_mode & 0o777 == 0o600
+ for encoded in ("@@@ not base64 @@@", base64.b64encode(b"plain text, not an image").decode()):
+ with pytest.raises(ValueError):
+ await media.save_image(encoded)
+
+
@pytest.mark.parametrize("state", ["exited", "running"])
async def test_resume_settles_a_real_bash_job_through_the_real_renderer(
engine, session, tmp_path, published, state
diff --git a/ui/src/lib/hostedActivity.fixture.json b/ui/src/lib/hostedActivity.fixture.json
index d54ed141e..0ddae23f5 100644
--- a/ui/src/lib/hostedActivity.fixture.json
+++ b/ui/src/lib/hostedActivity.fixture.json
@@ -59,7 +59,7 @@
"size": "1536x1024",
"quality": "medium",
"sources": [],
- "images": [{ "path": "/media/3f2a.png", "mime": "image/png", "width": 1536, "height": 1024 }]
+ "images": [{ "path": "/media/3f2a.png", "mime": "image/png", "width": 1536, "height": 1024, "bytes": 1993000 }]
},
"proxy_failed": {
"version": 1,